diff --git a/.gitattributes b/.gitattributes index 6723e0273..b46ec9964 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,4 @@ *.sh text eol=lf *.bat text eol=crlf +* -crlf diff --git a/README-Swim-Hybrid b/README-Swim-Hybrid new file mode 100644 index 000000000..0559b1f6b --- /dev/null +++ b/README-Swim-Hybrid @@ -0,0 +1,10 @@ +Use ./compile.sh to build Rainbow. +Set the following environment variables + +(1) RAINBOW - should point to the Rainbow directory. This path is used to location final_ibl.prism file used to generate Pism specification. The path to this file should be $RAINBOW/pladapt/templates/final_ibl.prism +(2) PRISM - should point to the directory where Prism is installed. + +Other potential settings that might need a change. + +Path to SWIG installation might depend on a specific machine. SWIG is used to compile pladapt project. Refer to the compilation instruction for pladapt project. + diff --git a/README.md b/README.md index f5faabd14..0fde89ffa 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Research into Rainbow at CMU can be found in quite a few papers, detailed on the - [Building from Source](#building) - [New and Noteworthy in Rainbow Yellow](NewAndNoteworthy.md) - [Rainbow Simple Example Setup](deployments/rainbow-example/docker/INSTRUCTIONS.md) +- [Rainbow Configuration IDE with Eclipse and XText](documents/RCL.md) ## Repository organization This repository is organized into the following folders: @@ -19,7 +20,7 @@ This repository is organized into the following folders: - **libs**: Contains the source of some in-house libraries used by Rainbow for distributed communication. - **rainbow**: Contains Rainbow framework code, including definition of general Acme models for use inside the Models Manager, and the source for the adaptation language *Stitch*. - **deployments**: Contains code to implement various specializations of Rainbow used in research projects -- **ide**: Contains code to implement specialized UIs, IDE integration, etc. that are probably not of general interest but are here for completeness. +- **ide**: Contains code to implement specialized UIs, IDE integration, etc. The Eclipse Rainbow configuration plugins live here, as well as some redundant and old code. - **documents**: Contains various documentation associated with using Rainbow - **scripts**: Contains the scripts that are placed in the deployment that is constructed when building Rainbow - **target-system/znn**: Contains the code for implementing one of the benchmark systems described in papers, ZNN. diff --git a/build.sh b/build.sh index 207b40a82..84edf1c43 100755 --- a/build.sh +++ b/build.sh @@ -102,57 +102,64 @@ cd libs/ echo "Doing $target for auxtestlib" cd auxtestlib -mvn $SKIPTESTS $target || exit 1 +mvn $SKIPTESTS $target echo "Doing $target for incubator" cd ../incubator -mvn $SKIPTESTS $target || exit 1 +mvn $SKIPTESTS $target echo "Doing $target for parsec" cd ../parsec -mvn -DskipTests $jcctarget || exit 1 +mvn -DskipTests $jcctarget echo "Doing $target for typelib" cd ../typelib -mvn $SKIPTESTS $jcctarget || exit 1 +mvn $SKIPTESTS $jcctarget echo "Doing $target for eselib" cd ../eseblib -mvn -DskipTests $target || exit 1 +mvn -DskipTests $target cd ../../rainbow echo "Doing $target for rainbow-core" cd rainbow-core -mvn -DskipTests $target || exit 1 +mvn -DskipTests $target echo "Doing $target for rainbow-gui" cd ../rainbow-gui -mvn -DskipTests $target || exit 1 +mvn -DskipTests $target echo "Doing $target for rainbow-acme-model" cd ../rainbow-acme-model -mvn -DskipTests $target || exit 1 +mvn -DskipTests $target + +echo "Doing $target for rainbow-stitch" +cd ../rainbow-stitch +mvn $SKIPTESTS $target echo "Doing $target for rainbow-utility-model" -cd ../rainbow-utility-model || exit 1 -mvn $target +cd ../rainbow-utility-model +mvn $SKIPTESTS $target -echo "Doing $target for rainbow-stitch" +echo "Doing $target for rainbow-mem-comms" +cd ../rainbow-mem-comms +mvn $SKIPTESTS $target -cd ../rainbow-stitch -mvn $SKIPTESTS $target || exit 1 +cd ../../ide/org.acme.xtext.parent +mvn $SKIPTESTS $target -echo "Doing $target for rainbow-gui" +cd ../../ide/org.sa.rainbow.stitch.parent +mvn $SKIPTESTS $target -cd ../rainbow-gui -mvn $SKIPTESTS $target || exit 1 +cd ../../ide/org.sa.rainbow.configuration.parent +mvn $SKIPTESTS $target cd ../.. BUILDDIR=`pwd` cd $DEPLOYMENT echo "Doing $target in $(pwd)" -mvn $SKIPTESTS $target || exit 1 +mvn $SKIPTESTS $target if [[ "$target" == "install" ]]; then mkdir -p $BUILDDIR/bin/lib diff --git a/compile.sh b/compile.sh new file mode 100755 index 000000000..7b5d64633 --- /dev/null +++ b/compile.sh @@ -0,0 +1,5 @@ +#!/bin/bash +./build.sh -s -d rainbow-swim-hybrid -t swim-hybrid +cp rainbow-swim.properties Rainbow-build/targets/swim-hybrid/ +cp -rf pladapt/ Rainbow-build/ + diff --git a/deployments/rainbow-brass/brass-p3-cp1/.gitignore b/deployments/rainbow-brass/brass-p3-cp1/.gitignore index 41d8137ff..d1b63f065 100644 --- a/deployments/rainbow-brass/brass-p3-cp1/.gitignore +++ b/deployments/rainbow-brass/brass-p3-cp1/.gitignore @@ -1,4 +1,4 @@ -/log/ -/prism/ +log/ +prism/ -!/prism/mapbotp2cp1.props +!mapbotp2cp1.props diff --git a/deployments/rainbow-brass/brass-p3-cp1/prism/mapbotp2cp1.props b/deployments/rainbow-brass/brass-p3-cp1/prism/mapbotp2cp1.props new file mode 100644 index 000000000..d6296c1f1 --- /dev/null +++ b/deployments/rainbow-brass/brass-p3-cp1/prism/mapbotp2cp1.props @@ -0,0 +1,5 @@ +R{"time"}min=? [ F goal ] + +R{"energy"}max=? [ F end ] + + diff --git a/deployments/rainbow-brass/brass-p3-cp1/rainbow-cp1_ta.properties b/deployments/rainbow-brass/brass-p3-cp1/rainbow-cp1_ta.properties index 9c80064d2..3b8bf551e 100644 --- a/deployments/rainbow-brass/brass-p3-cp1/rainbow-cp1_ta.properties +++ b/deployments/rainbow-brass/brass-p3-cp1/rainbow-cp1_ta.properties @@ -1,86 +1,86 @@ -logging.level = INFO -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log - -rainbow.deployment.location=cp1_ta -rainbow.master.location.host = cp1_ta -rainbow.master.location.port = 1100 -rainbow.deployment.environment = linux -rainbow.event.service = eseb -rainbow.port.timeout=120000 - -rainbow.delegate.beaconperiod = 10000 -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory - -rainbow.model.number = 7 - -# Rainbow instruction graph model -#/home/vagrant/catkin_ws/src/cp1_gazebo/instructions/newnav.ig -rainbow.model.load.class_3 = org.sa.rainbow.brass.model.instructions.InstructionGraphCommandFactory -rainbow.model.name_3 = ExecutingInstructionGraph -# -rainbow.model.load.class_4 = org.sa.rainbow.brass.model.p2_cp3.mission.MissionCommandFactory -rainbow.model.name_4 = MissionState -rainbow.model.saveOnClose_4=true -rainbow.model.saveLocation_4=model/state-post.txt - -rainbow.model.load.class_5 = org.sa.rainbow.brass.model.map.EnvMapCommandFactory -rainbow.model.name_5 = Map - -rainbow.model.load.class_0=org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowStateCommandFactory -rainbow.model.name_0=RainbowState - - -rainbow.model.load.class_2 =org.sa.rainbow.brass.model.p2_cp1.robot.CP1RobotStateCommandFactory -rainbow.model.name_2 = Robot -rainbow.model.saveOnClose_2=true -rainbow.model.saveLocation_2=model/robot-post.txt - -rainbow.model.load.class_1 = org.sa.rainbow.brass.model.p2_cp3.clock.ClockCommandFactory -rainbow.model.name_1 = Clock - -rainbow.model.load.class_6 = org.sa.rainbow.brass.p3_cp1.model.power.PowerModelCommandFactory -rainbow.model.name_6 = Power -rainbow.model.path_6 = /home/mars/cp1/config_list.json - -rainbow.analyses.size = 4 -rainbow.analyses_0 = org.sa.rainbow.brass.analyses.p2_cp3.UpdateClockModel -rainbow.analyses_1 = org.sa.rainbow.brass.analyses.p2_cp1.BRASSMissionAnalyzer -rainbow.analyses_2 = org.sa.rainbow.brass.analyses.p2_cp1.EnergyConsumptionAnalyzer -rainbow.analyses_3 = org.sa.rainbow.brass.analyses.IGWaypointAnalyzer - -rainbow.adaptation.manager.size = 1 -rainbow.adaptation.manager.class_0 = org.sa.rainbow.brass.adaptation.p2_cp1.CP1BRASSAdaptationPlanner -rainbow.adaptation.manager.model_0 = RainbowState:RainbowState - -rainbow.adaptation.executor.size = 1 -rainbow.adaptation.executor.class_0 = org.sa.rainbow.brass.adaptation.PlanExecutor -rainbow.adaptation.executor.model_0 = RainbowState:RainbowState - -rainbow.effector.manager.size = 1 -rainbow.effector.manager.class_0 = org.sa.rainbow.brass.effectors.BRASSEffectorManager - -rainbow.gui = org.sa.rainbow.gui.RainbowWindow - -# PRISM properties - not relative to target -prism.bin = ~/das/prism-4.3.1-linux64/bin/prism -prism.model = ${rainbow.path}/prism/prismtmp.prism -prism.properties = ${rainbow.path}/prism/mapbotp2cp1.props -prism.parameters = INITIAL_BATTERY=5000 -prism.adv.export = ${rainbow.path}/prism/botpolicy.adv -prism.tmpdir = "${rainbow.path}/prism/" -customize.map.json = ~/catkin_ws/src/cp1_base/maps/cp1_map.json - -customize.model.evaluate.period = 2000 -customize.gauges.path = model/gauges.yml -customize.probes.path = system/probes.yml -customize.effectors.path = system/effectors.yml -customize.scripts.path = stitch - -customize.system.target.master = ${rainbow.master.location.host} -customize.system.target.ros = ${rainbow.master.location.host} -brass.challenge = 3 - -configsource = ~/cp1/config_list.json +logging.level = INFO +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log + +rainbow.master.location.host = 127.0.0.1 +rainbow.master.location.port = 1100 +rainbow.deployment.environment = linux +rainbow.event.service = local + +rainbow.delegate.beaconperiod = 10000 +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.guava.GuavaRainbowPortFactory + +rainbow.model.number = 7 + +# Rainbow instruction graph model +#/home/vagrant/catkin_ws/src/cp1_gazebo/instructions/newnav.ig +rainbow.model.load.class_3 = org.sa.rainbow.brass.model.instructions.InstructionGraphCommandFactory +rainbow.model.name_3 = ExecutingInstructionGraph +# +rainbow.model.load.class_4 = org.sa.rainbow.brass.model.p2_cp3.mission.MissionCommandFactory +rainbow.model.name_4 = MissionState +rainbow.model.saveOnClose_4=true +rainbow.model.saveLocation_4=model/state-post.txt + +rainbow.model.load.class_5 = org.sa.rainbow.brass.model.map.EnvMapCommandFactory +rainbow.model.name_5 = Map + +rainbow.model.load.class_0=org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowStateCommandFactory +rainbow.model.name_0=RainbowState + + +rainbow.model.load.class_2 =org.sa.rainbow.brass.p3_cp1.model.robot.CP1RobotStateCommandFactory +rainbow.model.name_2 = Robot +rainbow.model.saveOnClose_2=true +rainbow.model.saveLocation_2=model/robot-post.txt + +rainbow.model.load.class_1 = org.sa.rainbow.brass.model.p2_cp3.clock.ClockCommandFactory +rainbow.model.name_1 = Clock + +rainbow.model.load.class_6 = org.sa.rainbow.brass.p3_cp1.model.power.PowerModelCommandFactory +rainbow.model.name_6 = Power +rainbow.model.path_6 = /home/mars/cp1/config_list.json + + +rainbow.analyses.size = 5 +rainbow.analyses_0 = org.sa.rainbow.brass.analyses.p2_cp3.UpdateClockModel +rainbow.analyses_1 = org.sa.rainbow.brass.p3_cp1.analysis.BRASSMissionAnalyzer +rainbow.analyses_2 = org.sa.rainbow.brass.p3_cp1.analysis.EnergyConsumptionAnalyzer +rainbow.analyses_3 = org.sa.rainbow.brass.analyses.IGWaypointAnalyzer +rainbow.analyses_4 = org.sa.rainbow.brass.p3_cp1.analysis.MapResetter + +rainbow.adaptation.manager.size = 1 +rainbow.adaptation.manager.class_0 = org.sa.rainbow.brass.p3_cp1.adaptation.CP1BRASSAdaptationPlanner +rainbow.adaptation.manager.model_0 = RainbowState:RainbowState + +rainbow.adaptation.executor.size = 1 +rainbow.adaptation.executor.class_0 = org.sa.rainbow.brass.adaptation.PlanExecutor +rainbow.adaptation.executor.model_0 = RainbowState:RainbowState + +rainbow.effector.manager.size = 1 +rainbow.effector.manager.class_0 = org.sa.rainbow.brass.effectors.BRASSEffectorManager + +rainbow.gui = org.sa.rainbow.gui.RainbowWindow + +# PRISM properties - not relative to target +prism.bin = ~/das/prism-4.3.1-linux64/bin/prism +prism.model = ${rainbow.path}/prism/prismtmp.prism +prism.properties = ${rainbow.path}/prism/mapbotp2cp1.props +prism.parameters = INITIAL_BATTERY=5000 +prism.adv.export = ${rainbow.path}/prism/botpolicy.adv +prism.tmpdir = "/home/mars/logs/prism/" +customize.map.json = ~/catkin_ws/src/cp1_base/maps/cp1_map.json + +customize.model.evaluate.period = 2000 +customize.gauges.path = model/gauges.yml +customize.probes.path = system/probes.yml +customize.effectors.path = system/effectors.yml +customize.scripts.path = stitch + +customize.system.target.master = ${rainbow.master.location.host} +customize.system.target.ros = ${rainbow.master.location.host} +brass.challenge = 3 + +configsource = ~/cp1/config_list.json batteryconfigsource = ~/cp1/config.json \ No newline at end of file diff --git a/deployments/rainbow-brass/brass-p3-cp1/rainbow.properties b/deployments/rainbow-brass/brass-p3-cp1/rainbow.properties index d6334ecce..48e7a5d90 100644 --- a/deployments/rainbow-brass/brass-p3-cp1/rainbow.properties +++ b/deployments/rainbow-brass/brass-p3-cp1/rainbow.properties @@ -1,85 +1,86 @@ -logging.level = INFO -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log - -rainbow.master.location.host = 127.0.0.1 -rainbow.master.location.port = 1100 -rainbow.deployment.environment = linux -rainbow.event.service = eseb - -rainbow.delegate.beaconperiod = 10000 -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory - -rainbow.model.number = 7 - -# Rainbow instruction graph model -#/home/vagrant/catkin_ws/src/cp1_gazebo/instructions/newnav.ig -rainbow.model.load.class_3 = org.sa.rainbow.brass.model.instructions.InstructionGraphCommandFactory -rainbow.model.name_3 = ExecutingInstructionGraph -# -rainbow.model.load.class_4 = org.sa.rainbow.brass.model.p2_cp3.mission.MissionCommandFactory -rainbow.model.name_4 = MissionState -rainbow.model.saveOnClose_4=true -rainbow.model.saveLocation_4=model/state-post.txt - -rainbow.model.load.class_5 = org.sa.rainbow.brass.model.map.EnvMapCommandFactory -rainbow.model.name_5 = Map - -rainbow.model.load.class_0=org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowStateCommandFactory -rainbow.model.name_0=RainbowState - - -rainbow.model.load.class_2 =org.sa.rainbow.brass.p3_cp1.model.robot.CP1RobotStateCommandFactory -rainbow.model.name_2 = Robot -rainbow.model.saveOnClose_2=true -rainbow.model.saveLocation_2=model/robot-post.txt - -rainbow.model.load.class_1 = org.sa.rainbow.brass.model.p2_cp3.clock.ClockCommandFactory -rainbow.model.name_1 = Clock - -rainbow.model.load.class_6 = org.sa.rainbow.brass.model.p3_cp1.model.power.PowerModelCommandFactory -rainbow.model.name_6 = Power -rainbow.model.path_6 = /home/mars/cp1/config_list.json - - -rainbow.analyses.size = 4 -rainbow.analyses_0 = org.sa.rainbow.brass.analyses.p2_cp3.UpdateClockModel -rainbow.analyses_1 = org.sa.rainbow.brass.p3_cp1.analyses.BRASSMissionAnalyzer -rainbow.analyses_2 = org.sa.rainbow.brass.p3_cp1.analyses.EnergyConsumptionAnalyzer -rainbow.analyses_3 = org.sa.rainbow.brass.analyses.IGWaypointAnalyzer - -rainbow.adaptation.manager.size = 1 -rainbow.adaptation.manager.class_0 = org.sa.rainbow.brass.p3_cp1.adaptation.CP1BRASSAdaptationPlanner -rainbow.adaptation.manager.model_0 = RainbowState:RainbowState - -rainbow.adaptation.executor.size = 1 -rainbow.adaptation.executor.class_0 = org.sa.rainbow.brass.adaptation.PlanExecutor -rainbow.adaptation.executor.model_0 = RainbowState:RainbowState - -rainbow.effector.manager.size = 1 -rainbow.effector.manager.class_0 = org.sa.rainbow.brass.effectors.BRASSEffectorManager - -rainbow.gui = org.sa.rainbow.gui.RainbowWindow - -# PRISM properties - not relative to target -prism.bin = ~/das/prism-4.3.1-linux64/bin/prism -prism.model = ${rainbow.path}/prism/prismtmp.prism -prism.properties = ${rainbow.path}/prism/mapbotp2cp1.props -prism.parameters = INITIAL_BATTERY=5000 -prism.adv.export = ${rainbow.path}/prism/botpolicy.adv -prism.tmpdir = "${rainbow.path}/prism/" -customize.map.json = ~/catkin_ws/src/cp1_base/maps/cp1_map.json - -customize.model.evaluate.period = 2000 -customize.gauges.path = model/gauges.yml -customize.probes.path = system/probes.yml -customize.effectors.path = system/effectors.yml -customize.scripts.path = stitch - -customize.system.target.master = ${rainbow.master.location.host} -customize.system.target.ros = ${rainbow.master.location.host} -brass.challenge = 3 - -configsource = ~/cp1/config_list.json +logging.level = INFO +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log + +rainbow.master.location.host = 127.0.0.1 +rainbow.master.location.port = 1100 +rainbow.deployment.environment = linux +rainbow.event.service = local + +rainbow.delegate.beaconperiod = 10000 +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.guava.GuavaRainbowPortFactory + +rainbow.model.number = 7 + +# Rainbow instruction graph model +#/home/vagrant/catkin_ws/src/cp1_gazebo/instructions/newnav.ig +rainbow.model.load.class_3 = org.sa.rainbow.brass.model.instructions.InstructionGraphCommandFactory +rainbow.model.name_3 = ExecutingInstructionGraph +# +rainbow.model.load.class_4 = org.sa.rainbow.brass.model.p2_cp3.mission.MissionCommandFactory +rainbow.model.name_4 = MissionState +rainbow.model.saveOnClose_4=true +rainbow.model.saveLocation_4=model/state-post.txt + +rainbow.model.load.class_5 = org.sa.rainbow.brass.model.map.EnvMapCommandFactory +rainbow.model.name_5 = Map + +rainbow.model.load.class_0=org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowStateCommandFactory +rainbow.model.name_0=RainbowState + + +rainbow.model.load.class_2 =org.sa.rainbow.brass.p3_cp1.model.robot.CP1RobotStateCommandFactory +rainbow.model.name_2 = Robot +rainbow.model.saveOnClose_2=true +rainbow.model.saveLocation_2=model/robot-post.txt + +rainbow.model.load.class_1 = org.sa.rainbow.brass.model.p2_cp3.clock.ClockCommandFactory +rainbow.model.name_1 = Clock + +rainbow.model.load.class_6 = org.sa.rainbow.brass.p3_cp1.model.power.PowerModelCommandFactory +rainbow.model.name_6 = Power +rainbow.model.path_6 = /home/mars/cp1/config_list.json + + +rainbow.analyses.size = 5 +rainbow.analyses_0 = org.sa.rainbow.brass.analyses.p2_cp3.UpdateClockModel +rainbow.analyses_1 = org.sa.rainbow.brass.p3_cp1.analysis.BRASSMissionAnalyzer +rainbow.analyses_2 = org.sa.rainbow.brass.p3_cp1.analysis.EnergyConsumptionAnalyzer +rainbow.analyses_3 = org.sa.rainbow.brass.analyses.IGWaypointAnalyzer +rainbow.analyses_4 = org.sa.rainbow.brass.p3_cp1.analysis.MapResetter + +rainbow.adaptation.manager.size = 1 +rainbow.adaptation.manager.class_0 = org.sa.rainbow.brass.p3_cp1.adaptation.CP1BRASSAdaptationPlanner +rainbow.adaptation.manager.model_0 = RainbowState:RainbowState + +rainbow.adaptation.executor.size = 1 +rainbow.adaptation.executor.class_0 = org.sa.rainbow.brass.adaptation.PlanExecutor +rainbow.adaptation.executor.model_0 = RainbowState:RainbowState + +rainbow.effector.manager.size = 1 +rainbow.effector.manager.class_0 = org.sa.rainbow.brass.effectors.BRASSEffectorManager + +rainbow.gui = org.sa.rainbow.gui.RainbowWindow + +# PRISM properties - not relative to target +prism.bin = ~/das/prism-4.3.1-linux64/bin/prism +prism.model = ${rainbow.path}/prism/prismtmp.prism +prism.properties = ${rainbow.path}/prism/mapbotp2cp1.props +prism.parameters = INITIAL_BATTERY=5000 +prism.adv.export = ${rainbow.path}/prism/botpolicy.adv +prism.tmpdir = "${rainbow.path}/prism/" +customize.map.json = ~/catkin_ws/src/cp1_base/maps/cp1_map.json + +customize.model.evaluate.period = 2000 +customize.gauges.path = model/gauges.yml +customize.probes.path = system/probes.yml +customize.effectors.path = system/effectors.yml +customize.scripts.path = stitch + +customize.system.target.master = ${rainbow.master.location.host} +customize.system.target.ros = ${rainbow.master.location.host} +brass.challenge = 3 + +configsource = ~/cp1/config_list.json batteryconfigsource = ~/cp1/config.json \ No newline at end of file diff --git a/deployments/rainbow-brass/brass-p3-cp1/system/effectors.yml b/deployments/rainbow-brass/brass-p3-cp1/system/effectors.yml index 4dc751ddd..03ef565d0 100644 --- a/deployments/rainbow-brass/brass-p3-cp1/system/effectors.yml +++ b/deployments/rainbow-brass/brass-p3-cp1/system/effectors.yml @@ -1,42 +1,50 @@ -vars: - _effectors.path: "${rainbow.path}/system/effectors" - -effector-types: - changeInstructionGraphT: - command: setInstructions($) - type: script - scriptInfo: - path: "${_effectors.path}/setInstructionFile.sh" - argument: "{0}" - - completedTaskFailedT: - command: setModelProblem(INSTRUCTION_GRAPH_FAILED) - type: script - scriptInfo: - path: "${_effectors.path}/current-task-finished.sh" - argument: 0 - - completedTaskSuccessT: - command: removeModelProblem(INSTRUCTION_GRAPH_FAILED) - type: script - scriptInfo: - path: "${_effectors.path}/current-task-finished.sh" - argument: 1 - -effectors: - - changeInstructionGraph: - effector-type: changeInstructionGraphT - location: "${customize.system.target.master}" - - taskFailed: - effector-type: completedTaskFailedT - location: "${customize.system.target.master}" - - taskSucceeded: - effector-type: completedTaskSuccessT - location: "${customize.system.target.master}" - -# changeDeadline: -# effector-type: changeDeadlineT +vars: + _effectors.path: "${rainbow.path}/system/effectors" + +effector-types: + changeInstructionGraphT: + command: setInstructions($) + type: script + scriptInfo: + path: "${_effectors.path}/setInstructionFile.sh" + argument: "{0}" + + completedTaskFailedT: + command: setModelProblem(INSTRUCTION_GRAPH_FAILED) + type: script + scriptInfo: + path: "${_effectors.path}/current-task-finished.sh" + argument: 0 + + completedTaskSuccessT: + command: removeModelProblem(INSTRUCTION_GRAPH_FAILED) + type: script + scriptInfo: + path: "${_effectors.path}/current-task-finished.sh" + argument: 1 + +effectors: + + changeInstructionGraph: + effector-type: changeInstructionGraphT + location: "${customize.system.target.master}" + + taskFailed: + effector-type: completedTaskFailedT + location: "${customize.system.target.master}" + + taskSucceeded: + effector-type: completedTaskSuccessT + location: "${customize.system.target.master}" + + cancelInstructions: + command: cancelInstructions() + location: "${customize.system.target.master}" + type: script + scriptInfo: + path: "${_effectors.path}/setInstructionFile.sh" + argument: ~"NONE" + +# changeDeadline: +# effector-type: changeDeadlineT # location: "${customize.system.target.master}" \ No newline at end of file diff --git a/deployments/rainbow-brass/brass-p3-cp1/system/effectors/cancelInstructions.sh b/deployments/rainbow-brass/brass-p3-cp1/system/effectors/cancelInstructions.sh new file mode 100644 index 000000000..864344055 --- /dev/null +++ b/deployments/rainbow-brass/brass-p3-cp1/system/effectors/cancelInstructions.sh @@ -0,0 +1,4 @@ +#!/bin/bash +. /opt/ros/kinetic/setup.bash +. ~/catkin_ws/devel/setup.bash +python ~/catkin_ws/src/ig-interpreter/ig_action_client/src/ig_client.py CANCEL diff --git a/deployments/rainbow-brass/pom.xml b/deployments/rainbow-brass/pom.xml index f549a6e9a..f9aad9f56 100644 --- a/deployments/rainbow-brass/pom.xml +++ b/deployments/rainbow-brass/pom.xml @@ -47,7 +47,7 @@ rainbow rainbow-core - 2.1.3-SNAPSHOT + 3.0 org.jyaml @@ -134,13 +134,24 @@ rainbow rainbow-acme-model - 2.1-SNAPSHOT + 3.0 net.sourceforge.argparse4j argparse4j 0.8.1 + + rainbow + rainbow-mem-comms + 3.0 + + + rainbow + rainbow-testing + 1.0.0-SNAPSHOT + test + diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/BRASSAdaptationPlanner.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/BRASSAdaptationPlanner.java index b9bb597f0..0d8d8bdb0 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/BRASSAdaptationPlanner.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/BRASSAdaptationPlanner.java @@ -147,7 +147,7 @@ public void markStrategyExecuted (AdaptationTree plan) { try { plan.visit (v); } catch (RainbowException e1) { - // TODO Auto-generated catch block + log(e1.getMessage()); e1.printStackTrace(); } if (v.m_allOk) { diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/BrassPlan.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/BrassPlan.java index e5d9795c2..adeda52df 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/BrassPlan.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/BrassPlan.java @@ -1,21 +1,21 @@ -package org.sa.rainbow.brass.adaptation; - -import org.sa.rainbow.core.adaptation.IEvaluable; - -/** - * Created by schmerl on 12/13/2016. - */ -public abstract class BrassPlan implements IEvaluable { - - // Evaluates (executes) the plan, returning a result - @Override - public abstract Object evaluate (Object[] argsIn); - - // This is deprecated - @Override - public long estimateAvgTimeCost () { - return 0; - } - - public abstract boolean getOutcome (); -} +package org.sa.rainbow.brass.adaptation; + +import org.sa.rainbow.core.adaptation.IEvaluable; + +/** + * Created by schmerl on 12/13/2016. + */ +public abstract class BrassPlan implements IEvaluable { + + // Evaluates (executes) the plan, returning a result + @Override + public abstract Object evaluate (Object[] argsIn); + + // This is deprecated + @Override + public long estimateAvgTimeCost () { + return 0; + } + + public abstract boolean getOutcome (); +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/NewInstructionGraph.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/NewInstructionGraph.java index a20dd25a3..b4e0a6ed2 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/NewInstructionGraph.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/NewInstructionGraph.java @@ -1,65 +1,65 @@ -package org.sa.rainbow.brass.adaptation; - -import org.sa.rainbow.brass.model.IP2ModelAccessor; -import org.sa.rainbow.brass.model.instructions.InstructionGraphCommandFactory; -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.SetInstructionsCmd; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.adaptation.IAdaptationExecutor; -import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; -import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; -import org.sa.rainbow.core.ports.IModelsManagerPort; - -/** - * An class that just publishes an operation to set the instruction graph. - * - * @author Bradley Schmerl: schmerl - * - */ -public class NewInstructionGraph extends BrassPlan { - - private String m_instructionGraph; - private InstructionGraphModelInstance m_reference; - - private IModelsManagerPort m_modelsManager; - private boolean m_outcome; - private IP2ModelAccessor m_models; - - protected NewInstructionGraph (InstructionGraphModelInstance m, String instructionGraph) { - m_instructionGraph = instructionGraph; - m_reference = m; - - throw new IllegalAccessError("This constructor should not be called"); - - } - - public NewInstructionGraph (IP2ModelAccessor models, String instructionGraph) { - m_models = models; - m_instructionGraph = instructionGraph; - - } - - @Override - public Object evaluate (Object[] argsIn) { -// IAdaptationExecutor executor = Rainbow.instance ().getRainbowMaster () -// .strategyExecutor (m_reference.getModelInstance ().getModelReference ().toString ()); -// InstructionGraphCommandFactory cf = m_reference.getCommandFactory (); -// SetInstructionsCmd cmd = cf.setInstructionsCmd (m_instructionGraph); - IAdaptationExecutor executor = Rainbow.instance().getRainbowMaster().strategyExecutor(m_models.getRainbowStateModel().getModelInstance().getModelReference().toString()); - InstructionGraphCommandFactory cf = m_models.getInstructionGraphModel().getCommandFactory(); - SetInstructionsCmd cmd = cf.setInstructionsCmd(m_instructionGraph); - System.out.println ("Changing Instructions"); - OperationResult result = executor.getOperationPublishingPort ().publishOperation (cmd); - m_outcome = result.result == Result.SUCCESS; - System.out.println ("Done"); - return m_outcome; - - - } - - @Override - public boolean getOutcome () { - return m_outcome; - } - -} +package org.sa.rainbow.brass.adaptation; + +import org.sa.rainbow.brass.model.IP2ModelAccessor; +import org.sa.rainbow.brass.model.instructions.InstructionGraphCommandFactory; +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.SetInstructionsCmd; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; +import org.sa.rainbow.core.ports.IModelsManagerPort; + +/** + * An class that just publishes an operation to set the instruction graph. + * + * @author Bradley Schmerl: schmerl + * + */ +public class NewInstructionGraph extends BrassPlan { + + private String m_instructionGraph; + private InstructionGraphModelInstance m_reference; + + private IModelsManagerPort m_modelsManager; + private boolean m_outcome; + private IP2ModelAccessor m_models; + + protected NewInstructionGraph (InstructionGraphModelInstance m, String instructionGraph) { + m_instructionGraph = instructionGraph; + m_reference = m; + + throw new IllegalAccessError("This constructor should not be called"); + + } + + public NewInstructionGraph (IP2ModelAccessor models, String instructionGraph) { + m_models = models; + m_instructionGraph = instructionGraph; + + } + + @Override + public Object evaluate (Object[] argsIn) { +// IAdaptationExecutor executor = Rainbow.instance ().getRainbowMaster () +// .strategyExecutor (m_reference.getModelInstance ().getModelReference ().toString ()); +// InstructionGraphCommandFactory cf = m_reference.getCommandFactory (); +// SetInstructionsCmd cmd = cf.setInstructionsCmd (m_instructionGraph); + IAdaptationExecutor executor = (IAdaptationExecutor) Rainbow.instance().getRainbowMaster().adaptationExecutors().get(m_models.getRainbowStateModel().getModelInstance().getModelReference().toString()); + InstructionGraphCommandFactory cf = m_models.getInstructionGraphModel().getCommandFactory(); + SetInstructionsCmd cmd = cf.setInstructionsCmd(m_instructionGraph); + System.out.println ("Changing Instructions"); + OperationResult result = executor.getOperationPublishingPort ().publishOperation (cmd); + m_outcome = result.result == Result.SUCCESS; + System.out.println ("Done"); + return m_outcome; + + + } + + @Override + public boolean getOutcome () { + return m_outcome; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/PlanExecutor.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/PlanExecutor.java index 3ac4f162b..8794da352 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/PlanExecutor.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/PlanExecutor.java @@ -122,8 +122,8 @@ protected void runAction () { } if (!Rainbow.instance ().shouldTerminate ()) { - final IAdaptationManager adaptationManager = Rainbow.instance ().getRainbowMaster () - .adaptationManagerForModel (this.m_modelRef.toString ()); + final IAdaptationManager adaptationManager = (IAdaptationManager) Rainbow.instance ().getRainbowMaster () + .adaptationManagers().get (this.m_modelRef.toString ()); if (adaptationManager != null) { adaptationManager.markStrategyExecuted (at); } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/PrismConnectorAPI.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/PrismConnectorAPI.java index 78dbd4da9..18c113d99 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/PrismConnectorAPI.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/PrismConnectorAPI.java @@ -185,7 +185,9 @@ else if (propertyToCheck == -1) { m_propertiesToCheck.add(m_propertiesFile.getPropertyObject(i)); } } else { + logInfo("Checking property " + propertyToCheck); m_propertiesToCheck.add(m_propertiesFile.getPropertyObject(propertyToCheck)); + logInfo("Done"); numPropertiesToCheck=1; } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/Recalibrate.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/Recalibrate.java index 93f61ec18..5d5709637 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/Recalibrate.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/Recalibrate.java @@ -6,6 +6,7 @@ import org.sa.rainbow.brass.model.mission.RecalibrateCmd; import org.sa.rainbow.core.Rainbow; import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.error.RainbowException; import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; @@ -21,13 +22,18 @@ public Recalibrate (MissionStateModelInstance m, InstructionGraphModelInstance e @Override public Object evaluate (Object[] argsIn) { - IAdaptationExecutor executor = Rainbow.instance ().getRainbowMaster () - .strategyExecutor (m_executorModel.getModelInstance ().getModelReference ().toString ()); - MissionCommandFactory cf = m_reference.getCommandFactory (); - RecalibrateCmd cmd = cf.recalibrate (false); - OperationResult result = executor.getOperationPublishingPort ().publishOperation (cmd); - m_outcome = result.result == Result.SUCCESS; - return m_outcome; + try { + IAdaptationExecutor executor = (IAdaptationExecutor) Rainbow.instance ().getRainbowMaster () + .adaptationExecutors().get (m_executorModel.getModelInstance ().getModelReference ().toString ()); + MissionCommandFactory cf = m_reference.getCommandFactory (); + RecalibrateCmd cmd = cf.recalibrate (false); + OperationResult result = executor.getOperationPublishingPort ().publishOperation (cmd); + m_outcome = result.result == Result.SUCCESS; + return m_outcome; + } catch (RainbowException e) { + e.printStackTrace(); + return m_outcome; + } } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/SetDeadline.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/SetDeadline.java index a973c5c26..b9c0a0ad5 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/SetDeadline.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/SetDeadline.java @@ -6,6 +6,7 @@ import org.sa.rainbow.brass.model.mission.SetDeadlineCmd; import org.sa.rainbow.core.Rainbow; import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.error.RainbowException; import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; @@ -25,14 +26,19 @@ public SetDeadline (MissionStateModelInstance m, InstructionGraphModelInstance e @Override public Object evaluate (Object[] argsIn) { - IAdaptationExecutor executor = Rainbow.instance ().getRainbowMaster () - .strategyExecutor (m_executorModel.getModelInstance ().getModelReference ().toString ()); - MissionCommandFactory cf = m_reference.getCommandFactory (); - SetDeadlineCmd cmd = cf.setDeadlineCmd (m_deadline); - System.out.println ("Setting deadline to " + m_deadline); - OperationResult result = executor.getOperationPublishingPort ().publishOperation (cmd); - m_outcome = result.result == Result.SUCCESS; - System.out.println ("DOne"); + try { + IAdaptationExecutor executor = (IAdaptationExecutor) Rainbow.instance ().getRainbowMaster () + .adaptationExecutors().get (m_executorModel.getModelInstance ().getModelReference ().toString ()); + MissionCommandFactory cf = m_reference.getCommandFactory (); + SetDeadlineCmd cmd = cf.setDeadlineCmd (m_deadline); + System.out.println ("Setting deadline to " + m_deadline); + OperationResult result = executor.getOperationPublishingPort ().publishOperation (cmd); + m_outcome = result.result == Result.SUCCESS; + System.out.println ("DOne"); + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } return m_outcome; } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp1/CP1BRASSAdaptationPlanner.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp1/CP1BRASSAdaptationPlanner.java index eb6b87d8f..7bf846577 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp1/CP1BRASSAdaptationPlanner.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp1/CP1BRASSAdaptationPlanner.java @@ -129,6 +129,7 @@ public void markStrategyExecuted(AdaptationTree plan) { } catch (RainbowException e1) { // TODO Auto-generated catch block e1.printStackTrace(); + log(e1.getMessage()); } if (m_reportAdapted) { if (v.m_allOk) { diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp1/CompletedTask.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp1/CompletedTask.java index 6f952a7ec..7860e8b68 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp1/CompletedTask.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp1/CompletedTask.java @@ -1,45 +1,51 @@ -package org.sa.rainbow.brass.adaptation.p2_cp1; - -import org.sa.rainbow.brass.adaptation.BrassPlan; -import org.sa.rainbow.brass.model.p2_cp1.CP1ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.adaptation.IAdaptationExecutor; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; -import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; - -public class CompletedTask extends BrassPlan { - - private CP1ModelAccessor m_models; - private Boolean m_successOrOtherwise; - private boolean m_outcome; - - public CompletedTask(CP1ModelAccessor models, boolean success) { - m_models = models; - m_successOrOtherwise = success; - - } - - @Override - public Object evaluate(Object[] argsIn) { - IAdaptationExecutor executor = Rainbow.instance().getRainbowMaster().strategyExecutor(m_models.getRainbowStateModel().getModelInstance().getModelReference().toString()); - IRainbowOperation op = null; - if (m_successOrOtherwise) { - op = m_models.getRainbowStateModel().getCommandFactory().removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); - } - else { - op = m_models.getRainbowStateModel().getCommandFactory().setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); - } - OperationResult result = executor.getOperationPublishingPort().publishOperation(op); - m_outcome = result.result == Result.SUCCESS; - return m_outcome; - } - - - @Override - public boolean getOutcome() { - return m_outcome; - } - -} +package org.sa.rainbow.brass.adaptation.p2_cp1; + +import org.sa.rainbow.brass.adaptation.BrassPlan; +import org.sa.rainbow.brass.model.p2_cp1.CP1ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; + +public class CompletedTask extends BrassPlan { + + private CP1ModelAccessor m_models; + private Boolean m_successOrOtherwise; + private boolean m_outcome; + + public CompletedTask(CP1ModelAccessor models, boolean success) { + m_models = models; + m_successOrOtherwise = success; + + } + + @Override + public Object evaluate(Object[] argsIn) { + IAdaptationExecutor executor = (IAdaptationExecutor) Rainbow.instance().getRainbowMaster().adaptationExecutors().get(m_models.getRainbowStateModel().getModelInstance().getModelReference().toString()); + IRainbowOperation op = null; + try { + if (m_successOrOtherwise) { + op = m_models.getRainbowStateModel().getCommandFactory().removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); + } + else { + op = m_models.getRainbowStateModel().getCommandFactory().setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); + } + OperationResult result = executor.getOperationPublishingPort().publishOperation(op); + m_outcome = result.result == Result.SUCCESS; + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return m_outcome; + } + + + @Override + public boolean getOutcome() { + return m_outcome; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp3/CP3BRASSAdaptationPlanner.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp3/CP3BRASSAdaptationPlanner.java index cdc8ddfe4..3eea19413 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp3/CP3BRASSAdaptationPlanner.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp3/CP3BRASSAdaptationPlanner.java @@ -149,6 +149,7 @@ public void markStrategyExecuted(AdaptationTree plan) { } catch (RainbowException e1) { // TODO Auto-generated catch block e1.printStackTrace(); + log(e1.getMessage()); } if (v.m_allOk) { log("Adaptation was successfully deployed"); diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp3/TurnOnHeadlamp.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp3/TurnOnHeadlamp.java index 2b5b0b3f8..ee3d621ee 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp3/TurnOnHeadlamp.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/adaptation/p2_cp3/TurnOnHeadlamp.java @@ -1,42 +1,48 @@ -package org.sa.rainbow.brass.adaptation.p2_cp3; - -import org.sa.rainbow.brass.adaptation.BrassPlan; -import org.sa.rainbow.brass.model.p2_cp3.ICP3ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotStateCommandFactory; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotStateModelInstance; -import org.sa.rainbow.brass.model.p2_cp3.robot.SetSensorCmd; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.adaptation.IAdaptationExecutor; -import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; -import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; - -public class TurnOnHeadlamp extends BrassPlan { - - private boolean m_on; - private boolean m_outcome; - private ICP3ModelAccessor m_models; - - public TurnOnHeadlamp(ICP3ModelAccessor models, boolean b) { - m_models = models; - m_on = b; - } - - @Override - public Object evaluate(Object[] argsIn) { - IAdaptationExecutor executor = Rainbow.instance(). - getRainbowMaster(). - strategyExecutor(m_models.getRainbowStateModel().getModelInstance().getModelReference().toString()); - CP3RobotStateCommandFactory cf = (CP3RobotStateCommandFactory) m_models.getRobotStateModel().getCommandFactory(); - SetSensorCmd tohl = cf.setSensorCmd(Sensors.HEADLAMP, m_on); - OperationResult result = executor.getOperationPublishingPort().publishOperation(tohl); - m_outcome = result.result == Result.SUCCESS; - return m_outcome; - } - - @Override - public boolean getOutcome() { - return m_outcome; - } - -} +package org.sa.rainbow.brass.adaptation.p2_cp3; + +import org.sa.rainbow.brass.adaptation.BrassPlan; +import org.sa.rainbow.brass.model.p2_cp3.ICP3ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotStateCommandFactory; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotStateModelInstance; +import org.sa.rainbow.brass.model.p2_cp3.robot.SetSensorCmd; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; + +public class TurnOnHeadlamp extends BrassPlan { + + private boolean m_on; + private boolean m_outcome; + private ICP3ModelAccessor m_models; + + public TurnOnHeadlamp(ICP3ModelAccessor models, boolean b) { + m_models = models; + m_on = b; + } + + @Override + public Object evaluate(Object[] argsIn) { + try { + IAdaptationExecutor executor = (IAdaptationExecutor) Rainbow.instance(). + getRainbowMaster(). + adaptationExecutors().get(m_models.getRainbowStateModel().getModelInstance().getModelReference().toString()); + CP3RobotStateCommandFactory cf = (CP3RobotStateCommandFactory) m_models.getRobotStateModel().getCommandFactory(); + SetSensorCmd tohl = cf.setSensorCmd(Sensors.HEADLAMP, m_on); + OperationResult result = executor.getOperationPublishingPort().publishOperation(tohl); + m_outcome = result.result == Result.SUCCESS; + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return m_outcome; + } + + @Override + public boolean getOutcome() { + return m_outcome; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/AccuracyAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/AccuracyAnalyzer.java index e7b7b297b..8398d7f3d 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/AccuracyAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/AccuracyAnalyzer.java @@ -32,6 +32,7 @@ import org.sa.rainbow.core.RainbowConstants; import org.sa.rainbow.core.analysis.IRainbowAnalysis; import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; import org.sa.rainbow.core.event.IRainbowMessage; import org.sa.rainbow.core.models.ModelReference; import org.sa.rainbow.core.ports.IModelChangeBusPort; @@ -173,70 +174,74 @@ protected void runAction() { // Only performing timing analysis once per instruction // if (isNewOrUnpassedInstruction(currentInstruction)) { - if (m_missionState != null && !(currentInstruction instanceof ChargeInstruction)) { - - // TODO: This may be a hack - // Update the robot's configuration (Kinect and localization) in MissionState - if (currentInstruction instanceof SetLocalizationFidelityInstruction) { - SetLocalizationFidelityInstruction inst = (SetLocalizationFidelityInstruction) currentInstruction; - MissionStateModelInstance missionStateModel = (MissionStateModelInstance) m_modelsManagerPort - . getModelInstance(m_msRef); - SetRobotLocalizationFidelityCmd robotLocFidelityCmd = missionStateModel.getCommandFactory() - .setRobotLocalizationFidelityCmd(inst.getLocalizationFidelity()); - m_modelUSPort.updateModel(robotLocFidelityCmd); - } - - // The remaining instructions, excluding the current instruction - List remainingInstructions = (List) m_igProgress.getRemainingInstructions(); - Double batteryCharge = m_missionState.getBatteryCharge (); - if (batteryCharge == null) return; // Don't have charge information yet - double planEnergyConsumption = hasEnoughEnergy (currentInstruction, remainingInstructions); - boolean hasEnoughEnergy = batteryCharge >= planEnergyConsumption; - log ("Current charge = " + batteryCharge + ", needed charge = " + planEnergyConsumption); - if (hasEnoughEnergy) { - // Keep track of the latest instruction that we have analyzed the accuracy property, - // and it passed - m_prevAnalyzedAndPassedInstruction = currentInstruction; - } - - if (hasEnoughEnergy && !m_missionState.isRobotAccurate()) { - // Previous plan was not accurate; new plan is expected to be accurate - // Update MissionState model to indicate that the robot can now get close enough to the goal - MissionStateModelInstance missionStateModel = (MissionStateModelInstance) m_modelsManagerPort - . getModelInstance(m_msRef); - SetRobotAccurateCmd robotAccurateCmd = missionStateModel.getCommandFactory().setRobotAccurateCmd(true); - m_modelUSPort.updateModel (robotAccurateCmd); - } else if (!hasEnoughEnergy) { - log ("Do not have enough battery. Current charge = " + batteryCharge + ", needed charge = " - + planEnergyConsumption); - planEnergyConsumption = hasEnoughEnergy (currentInstruction, remainingInstructions); - // Update MissionState model to indicate that the robot cannot get close enough to the goal - MissionStateModelInstance missionStateModel = (MissionStateModelInstance) m_modelsManagerPort - . getModelInstance(m_msRef); - - LocationRecording pose = m_missionState.getCurrentPose (); - - // Get source and target positions of the failing instruction - IInstruction currentInst = m_igProgress.getCurrentInstruction (); - - // The current instruction is of type MoveAbsH - insertNode (pose, currentInst, missionStateModel); - - SetRobotAccurateCmd robotAccurateCmd = missionStateModel.getCommandFactory().setRobotAccurateCmd(false); - m_modelUSPort.updateModel (robotAccurateCmd); - - // Wait for the planner to come up with an adaptation plan - m_waitForPlanner = true; - } + try { + if (m_missionState != null && !(currentInstruction instanceof ChargeInstruction)) { + + // TODO: This may be a hack + // Update the robot's configuration (Kinect and localization) in MissionState + if (currentInstruction instanceof SetLocalizationFidelityInstruction) { + SetLocalizationFidelityInstruction inst = (SetLocalizationFidelityInstruction) currentInstruction; + MissionStateModelInstance missionStateModel = (MissionStateModelInstance) m_modelsManagerPort + . getModelInstance(m_msRef); + SetRobotLocalizationFidelityCmd robotLocFidelityCmd = missionStateModel.getCommandFactory() + .setRobotLocalizationFidelityCmd(inst.getLocalizationFidelity()); + m_modelUSPort.updateModel(robotLocFidelityCmd); + } + + // The remaining instructions, excluding the current instruction + List remainingInstructions = (List) m_igProgress.getRemainingInstructions(); + Double batteryCharge = m_missionState.getBatteryCharge (); + if (batteryCharge == null) return; // Don't have charge information yet + double planEnergyConsumption = hasEnoughEnergy (currentInstruction, remainingInstructions); + boolean hasEnoughEnergy = batteryCharge >= planEnergyConsumption; + log ("Current charge = " + batteryCharge + ", needed charge = " + planEnergyConsumption); + if (hasEnoughEnergy) { + // Keep track of the latest instruction that we have analyzed the accuracy property, + // and it passed + m_prevAnalyzedAndPassedInstruction = currentInstruction; + } + + if (hasEnoughEnergy && !m_missionState.isRobotAccurate()) { + // Previous plan was not accurate; new plan is expected to be accurate + // Update MissionState model to indicate that the robot can now get close enough to the goal + MissionStateModelInstance missionStateModel = (MissionStateModelInstance) m_modelsManagerPort + . getModelInstance(m_msRef); + SetRobotAccurateCmd robotAccurateCmd = missionStateModel.getCommandFactory().setRobotAccurateCmd(true); + m_modelUSPort.updateModel (robotAccurateCmd); + } else if (!hasEnoughEnergy) { + log ("Do not have enough battery. Current charge = " + batteryCharge + ", needed charge = " + + planEnergyConsumption); + planEnergyConsumption = hasEnoughEnergy (currentInstruction, remainingInstructions); + // Update MissionState model to indicate that the robot cannot get close enough to the goal + MissionStateModelInstance missionStateModel = (MissionStateModelInstance) m_modelsManagerPort + . getModelInstance(m_msRef); + + LocationRecording pose = m_missionState.getCurrentPose (); + + // Get source and target positions of the failing instruction + IInstruction currentInst = m_igProgress.getCurrentInstruction (); + + // The current instruction is of type MoveAbsH + insertNode (pose, currentInst, missionStateModel); + + SetRobotAccurateCmd robotAccurateCmd = missionStateModel.getCommandFactory().setRobotAccurateCmd(false); + m_modelUSPort.updateModel (robotAccurateCmd); + + // Wait for the planner to come up with an adaptation plan + m_waitForPlanner = true; + } // } - } - else if (m_missionState != null && !m_missionState.isRobotAccurate ()) { - MissionStateModelInstance missionStateModel = (MissionStateModelInstance )m_modelsManagerPort - . getModelInstance (m_msRef); - SetRobotAccurateCmd robotAccurateCmd = missionStateModel.getCommandFactory () - .setRobotAccurateCmd (true); - m_modelUSPort.updateModel (robotAccurateCmd); - } + } + else if (m_missionState != null && !m_missionState.isRobotAccurate ()) { + MissionStateModelInstance missionStateModel = (MissionStateModelInstance )m_modelsManagerPort + . getModelInstance (m_msRef); + SetRobotAccurateCmd robotAccurateCmd = missionStateModel.getCommandFactory () + .setRobotAccurateCmd (true); + m_modelUSPort.updateModel (robotAccurateCmd); + } + } catch (RainbowException e) { + e.printStackTrace(); + } } } } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/BRASSMissionAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/BRASSMissionAnalyzer.java index 85d1969b8..b5153c0a5 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/BRASSMissionAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/BRASSMissionAnalyzer.java @@ -1,238 +1,243 @@ -package org.sa.rainbow.brass.analyses; - -import org.sa.rainbow.brass.das.BRASSHttpConnector; -import org.sa.rainbow.brass.das.IBRASSConnector.DASPhase1StatusT; -import org.sa.rainbow.brass.das.IBRASSConnector.Phases; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.EnvMapModelInstance; -import org.sa.rainbow.brass.model.map.InsertNodeCmd; -import org.sa.rainbow.brass.model.mission.MissionState; -import org.sa.rainbow.brass.model.mission.MissionState.LocationRecording; -import org.sa.rainbow.brass.model.mission.MissionStateModelInstance; -import org.sa.rainbow.brass.model.mission.SetRobotObstructedCmd; -import org.sa.rainbow.core.AbstractRainbowRunnable; -import org.sa.rainbow.core.IRainbowRunnable; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.RainbowConstants; -import org.sa.rainbow.core.analysis.IRainbowAnalysis; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.ports.IModelUSBusPort; -import org.sa.rainbow.core.ports.IModelsManagerPort; -import org.sa.rainbow.core.ports.IRainbowReportingPort; -import org.sa.rainbow.core.ports.RainbowPortFactory; - -/** - * Created by schmerl on 12/13/2016. - * Analyzes the current situation and triggers adaptation if necessary - */ -public class BRASSMissionAnalyzer extends AbstractRainbowRunnable implements IRainbowAnalysis { - - public static final String NAME = "BRASS Mission Evaluator"; - private IModelsManagerPort m_modelsManagerPort; - private IModelUSBusPort m_modelUSPort; - private boolean m_awaitingNewIG; - private boolean m_awaitingPose; - - public BRASSMissionAnalyzer () { - super(NAME); - String per = Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); - if (per != null) { - setSleepTime (Long.parseLong (per)); - } else { - setSleepTime (IRainbowRunnable.LONG_SLEEP_TIME); - } - } - - @Override - public void initialize (IRainbowReportingPort port) throws RainbowConnectionException { - super.initialize (port); - initializeConnections (); - log ("Initialized missions analyzer"); - } - - private void initializeConnections () throws RainbowConnectionException { - // Create a port to subscribe to model changes (if analyzer is event based) - // m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort (); - - // Create a port to query things about a model - m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort (); - - // Create a port to change a model (e.g., to trigger adaptation, to set predicted score, etc.) - m_modelUSPort = RainbowPortFactory.createModelsManagerClientUSPort (this); - - } - - @Override - public void setProperty (String key, String value) { - - } - - @Override - public String getProperty (String key) { - return null; - } - - @Override - public void dispose () { - m_reportingPort.dispose (); - m_modelUSPort.dispose (); - } - - @Override - protected void log (String txt) { - m_reportingPort.info (RainbowComponentT.ANALYSIS, txt); - } - - @Override - protected void runAction () { - // Do the periodic analysis on the models of interest - ModelReference missionStateRef = new ModelReference("RobotAndEnvironmentState", MissionStateModelInstance.MISSION_STATE_TYPE); - ModelReference igRef = new ModelReference("ExecutingInstructionGraph", InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE); - MissionStateModelInstance missionStateModel = (MissionStateModelInstance) m_modelsManagerPort - . getModelInstance(missionStateRef); - InstructionGraphModelInstance igModel = (InstructionGraphModelInstance) m_modelsManagerPort - . getModelInstance(igRef); - ModelReference emRef = new ModelReference ("Map", EnvMapModelInstance.ENV_MAP_TYPE); - EnvMapModelInstance envModel = (EnvMapModelInstance) m_modelsManagerPort. getModelInstance (emRef); - - if (missionStateModel != null && igModel != null && envModel != null) { - MissionState missionState = missionStateModel.getModelInstance(); - InstructionGraphProgress igProgress = igModel.getModelInstance(); - EnvMap envMap = envModel.getModelInstance(); - boolean currentOK = igProgress.getCurrentOK(); -// if (missionState.isAdaptationNeeded ()) return; - - // If we start off with nothing (i.e., no instruction graph), this is a problem -// if (emptyInstructions (igProgress) -// && !missionState.isRobotObstructed () && missionState.getCurrentPose () != null) { -// log ("Robot has no instructions - triggering planning to get started"); -// SetRobotObstructedCmd cmd = missionStateModel.getCommandFactory ().setRobotObstructedCmd (true); -// m_modelUSPort.updateModel (cmd); -// } - -// log ("Mission Progress Analyzer"); -// log ("Finished succesfully? " -// + (igProgress.getInstructionGraphState () == IGExecutionStateT.FINISHED_SUCCESS)); -// log ("Finished failed? " + (igProgress.getInstructionGraphState () == IGExecutionStateT.FINISHED_FAILED)); -// log ("Awaiting pose? " + (missionState.getCurrentPose () == null) + ", " + m_awaitingPose); -// log ("CurrentOK? " + currentOK); -// log ("Executing Instruction?" + (igProgress.getExecutingInstruction () != null)); -// log ("Awaiting new IG?" + m_awaitingNewIG); -// log ("Empty instructions?" + emptyInstructions (igProgress)); -// log ("Robot obstructed known? " + missionState.isRobotObstructed ()); - if (igProgress.getInstructionGraphState () == IGExecutionStateT.FINISHED_SUCCESS) { - BRASSHttpConnector.instance (Phases.Phase1).reportDone (false, "Finished all the instructions in the task"); - Rainbow.instance ().signalTerminate (); - return; - - } - if (missionState.getCurrentPose () == null) { - m_awaitingPose = true; - } - else if (missionState.getCurrentPose () != null && m_awaitingPose) { - m_awaitingPose = false; - BRASSHttpConnector.instance (Phases.Phase1).reportReady (true); - - } - else if (!currentOK && igProgress.getExecutingInstruction () != null && !m_awaitingNewIG - /*&& igProgress.getInstructionGraphState () == IGExecutionStateT.FINISHED_FAILED*/) { - // Current IG failed - m_reportingPort.info (getComponentType (), "Instruction graph failed...updating map model"); - BRASSHttpConnector.instance (Phases.Phase1).reportStatus (DASPhase1StatusT.PERTURBATION_DETECTED.name(), - "Obstruction to path detected"); - // Get current robot position - LocationRecording pose = missionState.getCurrentPose (); - - // Get source and target positions of the failing instruction - IInstruction currentInst = igProgress.getCurrentInstruction(); - - // The current instruction is of type MoveAbsH - if (currentInst instanceof MoveAbsHInstruction) { - MoveAbsHInstruction currentMoveAbsH = (MoveAbsHInstruction) currentInst; - MoveAbsHInstruction prevMoveAbsH = getPreviousMoveAbsH(currentMoveAbsH, igProgress); - - double sourceX; - double sourceY; - double targetX = currentMoveAbsH.getTargetX(); - double targetY = currentMoveAbsH.getTargetY(); - - if (prevMoveAbsH != null) { - sourceX = prevMoveAbsH.getTargetX(); - sourceY = prevMoveAbsH.getTargetY(); - } else { - // The current instruction is the first MoveAbsH instruction in IG - // Use the initial pose as the source pose - sourceX = missionState.getInitialPose().getX(); - sourceY = missionState.getInitialPose().getY(); - } - - // Find the corresponding environment map nodes of the source and target positions - // Node naming assumption: node's label is lX where X is the order in which the node is added - int numNodes = envMap.getNodeCount() + 1; - String n = "l" + numNodes; - String na = envMap.getNode (sourceX, sourceY).getLabel (); - String nb = envMap.getNode (targetX, targetY).getLabel (); - - // Update the environment map - String rx = Double.toString (pose.getX ()); - String ry = Double.toString (pose.getY ()); - InsertNodeCmd insertNodeCmd = envModel.getCommandFactory () - .insertNodeCmd (n, na, nb, rx, ry, "true"); - log ("Inserting node '" + n + "' at (" + rx + ", " + ry + ") between " + na + " and " + nb); - - // Set robot obstructed flag -- trigger planning for adaptation - SetRobotObstructedCmd robotObstructedCmd = missionStateModel.getCommandFactory () - .setRobotObstructedCmd (true); - - SetExecutionFailedCmd resetFailedCmd = igModel.getCommandFactory ().setExecutionFailedCmd ("false"); - - // Send the commands -- different models, so can't bundle them - m_modelUSPort.updateModel (resetFailedCmd); - m_modelUSPort.updateModel (insertNodeCmd); - m_modelUSPort.updateModel (robotObstructedCmd); - m_awaitingNewIG = true; - } - } - else if (currentOK && !emptyInstructions (igProgress) && missionState.isRobotObstructed ()) { - // New IG resumed after robot obstructed - log ("New instruction model was detected. Reseting models to ok"); - m_reportingPort.info (getComponentType (), "New instruction graph detected"); - m_awaitingNewIG = false; - // Clear robot obstructed flag - SetRobotObstructedCmd clearRobotObstructedCmd = missionStateModel.getCommandFactory () - .setRobotObstructedCmd (false); - m_modelUSPort.updateModel(clearRobotObstructedCmd); - } - } - } - - boolean emptyInstructions (InstructionGraphProgress igProgress) { - return igProgress.getInstructions () == null || igProgress.getInstructions ().isEmpty (); - } - - private MoveAbsHInstruction getPreviousMoveAbsH (MoveAbsHInstruction currentMoveAbsH, InstructionGraphProgress igProgress) { - int j = Integer.valueOf (currentMoveAbsH.getInstructionLabel()) - 1; - for (int i = j; i > 0; i--) { - String label = String.valueOf (i); - IInstruction instruction = igProgress.getInstruction(label); - - if (instruction instanceof MoveAbsHInstruction) return (MoveAbsHInstruction) instruction; - } - - // No previous MoveAbsH instruction - return null; - } - - @Override - public RainbowComponentT getComponentType () { - return RainbowComponentT.ANALYSIS; - } -} +package org.sa.rainbow.brass.analyses; + +import org.sa.rainbow.brass.das.BRASSHttpConnector; +import org.sa.rainbow.brass.das.IBRASSConnector.DASPhase1StatusT; +import org.sa.rainbow.brass.das.IBRASSConnector.Phases; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.EnvMapModelInstance; +import org.sa.rainbow.brass.model.map.InsertNodeCmd; +import org.sa.rainbow.brass.model.mission.MissionState; +import org.sa.rainbow.brass.model.mission.MissionState.LocationRecording; +import org.sa.rainbow.brass.model.mission.MissionStateModelInstance; +import org.sa.rainbow.brass.model.mission.SetRobotObstructedCmd; +import org.sa.rainbow.core.AbstractRainbowRunnable; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.analysis.IRainbowAnalysis; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.IModelUSBusPort; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; + +/** + * Created by schmerl on 12/13/2016. + * Analyzes the current situation and triggers adaptation if necessary + */ +public class BRASSMissionAnalyzer extends AbstractRainbowRunnable implements IRainbowAnalysis { + + public static final String NAME = "BRASS Mission Evaluator"; + private IModelsManagerPort m_modelsManagerPort; + private IModelUSBusPort m_modelUSPort; + private boolean m_awaitingNewIG; + private boolean m_awaitingPose; + + public BRASSMissionAnalyzer () { + super(NAME); + String per = Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (per != null) { + setSleepTime (Long.parseLong (per)); + } else { + setSleepTime (IRainbowRunnable.LONG_SLEEP_TIME); + } + } + + @Override + public void initialize (IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize (port); + initializeConnections (); + log ("Initialized missions analyzer"); + } + + private void initializeConnections () throws RainbowConnectionException { + // Create a port to subscribe to model changes (if analyzer is event based) + // m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort (); + + // Create a port to query things about a model + m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort (); + + // Create a port to change a model (e.g., to trigger adaptation, to set predicted score, etc.) + m_modelUSPort = RainbowPortFactory.createModelsManagerClientUSPort (this); + + } + + @Override + public void setProperty (String key, String value) { + + } + + @Override + public String getProperty (String key) { + return null; + } + + @Override + public void dispose () { + m_reportingPort.dispose (); + m_modelUSPort.dispose (); + } + + @Override + protected void log (String txt) { + m_reportingPort.info (RainbowComponentT.ANALYSIS, txt); + } + + @Override + protected void runAction () { + // Do the periodic analysis on the models of interest + ModelReference missionStateRef = new ModelReference("RobotAndEnvironmentState", MissionStateModelInstance.MISSION_STATE_TYPE); + ModelReference igRef = new ModelReference("ExecutingInstructionGraph", InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE); + MissionStateModelInstance missionStateModel = (MissionStateModelInstance) m_modelsManagerPort + . getModelInstance(missionStateRef); + InstructionGraphModelInstance igModel = (InstructionGraphModelInstance) m_modelsManagerPort + . getModelInstance(igRef); + ModelReference emRef = new ModelReference ("Map", EnvMapModelInstance.ENV_MAP_TYPE); + EnvMapModelInstance envModel = (EnvMapModelInstance) m_modelsManagerPort. getModelInstance (emRef); + + try { + if (missionStateModel != null && igModel != null && envModel != null) { + MissionState missionState = missionStateModel.getModelInstance(); + InstructionGraphProgress igProgress = igModel.getModelInstance(); + EnvMap envMap = envModel.getModelInstance(); + boolean currentOK = igProgress.getCurrentOK(); +// if (missionState.isAdaptationNeeded ()) return; + + // If we start off with nothing (i.e., no instruction graph), this is a problem +// if (emptyInstructions (igProgress) +// && !missionState.isRobotObstructed () && missionState.getCurrentPose () != null) { +// log ("Robot has no instructions - triggering planning to get started"); +// SetRobotObstructedCmd cmd = missionStateModel.getCommandFactory ().setRobotObstructedCmd (true); +// m_modelUSPort.updateModel (cmd); +// } + +// log ("Mission Progress Analyzer"); +// log ("Finished succesfully? " +// + (igProgress.getInstructionGraphState () == IGExecutionStateT.FINISHED_SUCCESS)); +// log ("Finished failed? " + (igProgress.getInstructionGraphState () == IGExecutionStateT.FINISHED_FAILED)); +// log ("Awaiting pose? " + (missionState.getCurrentPose () == null) + ", " + m_awaitingPose); +// log ("CurrentOK? " + currentOK); +// log ("Executing Instruction?" + (igProgress.getExecutingInstruction () != null)); +// log ("Awaiting new IG?" + m_awaitingNewIG); +// log ("Empty instructions?" + emptyInstructions (igProgress)); +// log ("Robot obstructed known? " + missionState.isRobotObstructed ()); + if (igProgress.getInstructionGraphState () == IGExecutionStateT.FINISHED_SUCCESS) { + BRASSHttpConnector.instance (Phases.Phase1).reportDone (false, "Finished all the instructions in the task"); + Rainbow.instance ().signalTerminate (); + return; + + } + if (missionState.getCurrentPose () == null) { + m_awaitingPose = true; + } + else if (missionState.getCurrentPose () != null && m_awaitingPose) { + m_awaitingPose = false; + BRASSHttpConnector.instance (Phases.Phase1).reportReady (true); + + } + else if (!currentOK && igProgress.getExecutingInstruction () != null && !m_awaitingNewIG + /*&& igProgress.getInstructionGraphState () == IGExecutionStateT.FINISHED_FAILED*/) { + // Current IG failed + m_reportingPort.info (getComponentType (), "Instruction graph failed...updating map model"); + BRASSHttpConnector.instance (Phases.Phase1).reportStatus (DASPhase1StatusT.PERTURBATION_DETECTED.name(), + "Obstruction to path detected"); + // Get current robot position + LocationRecording pose = missionState.getCurrentPose (); + + // Get source and target positions of the failing instruction + IInstruction currentInst = igProgress.getCurrentInstruction(); + + // The current instruction is of type MoveAbsH + if (currentInst instanceof MoveAbsHInstruction) { + MoveAbsHInstruction currentMoveAbsH = (MoveAbsHInstruction) currentInst; + MoveAbsHInstruction prevMoveAbsH = getPreviousMoveAbsH(currentMoveAbsH, igProgress); + + double sourceX; + double sourceY; + double targetX = currentMoveAbsH.getTargetX(); + double targetY = currentMoveAbsH.getTargetY(); + + if (prevMoveAbsH != null) { + sourceX = prevMoveAbsH.getTargetX(); + sourceY = prevMoveAbsH.getTargetY(); + } else { + // The current instruction is the first MoveAbsH instruction in IG + // Use the initial pose as the source pose + sourceX = missionState.getInitialPose().getX(); + sourceY = missionState.getInitialPose().getY(); + } + + // Find the corresponding environment map nodes of the source and target positions + // Node naming assumption: node's label is lX where X is the order in which the node is added + int numNodes = envMap.getNodeCount() + 1; + String n = "l" + numNodes; + String na = envMap.getNode (sourceX, sourceY).getLabel (); + String nb = envMap.getNode (targetX, targetY).getLabel (); + + // Update the environment map + String rx = Double.toString (pose.getX ()); + String ry = Double.toString (pose.getY ()); + InsertNodeCmd insertNodeCmd = envModel.getCommandFactory () + .insertNodeCmd (n, na, nb, rx, ry, "true"); + log ("Inserting node '" + n + "' at (" + rx + ", " + ry + ") between " + na + " and " + nb); + + // Set robot obstructed flag -- trigger planning for adaptation + SetRobotObstructedCmd robotObstructedCmd = missionStateModel.getCommandFactory () + .setRobotObstructedCmd (true); + + SetExecutionFailedCmd resetFailedCmd = igModel.getCommandFactory ().setExecutionFailedCmd ("false"); + + // Send the commands -- different models, so can't bundle them + m_modelUSPort.updateModel (resetFailedCmd); + m_modelUSPort.updateModel (insertNodeCmd); + m_modelUSPort.updateModel (robotObstructedCmd); + m_awaitingNewIG = true; + } + } + else if (currentOK && !emptyInstructions (igProgress) && missionState.isRobotObstructed ()) { + // New IG resumed after robot obstructed + log ("New instruction model was detected. Reseting models to ok"); + m_reportingPort.info (getComponentType (), "New instruction graph detected"); + m_awaitingNewIG = false; + // Clear robot obstructed flag + SetRobotObstructedCmd clearRobotObstructedCmd = missionStateModel.getCommandFactory () + .setRobotObstructedCmd (false); + m_modelUSPort.updateModel(clearRobotObstructedCmd); + } + } + } catch (RainbowException e) { + e.printStackTrace(); + } + } + + boolean emptyInstructions (InstructionGraphProgress igProgress) { + return igProgress.getInstructions () == null || igProgress.getInstructions ().isEmpty (); + } + + private MoveAbsHInstruction getPreviousMoveAbsH (MoveAbsHInstruction currentMoveAbsH, InstructionGraphProgress igProgress) { + int j = Integer.valueOf (currentMoveAbsH.getInstructionLabel()) - 1; + for (int i = j; i > 0; i--) { + String label = String.valueOf (i); + IInstruction instruction = igProgress.getInstruction(label); + + if (instruction instanceof MoveAbsHInstruction) return (MoveAbsHInstruction) instruction; + } + + // No previous MoveAbsH instruction + return null; + } + + @Override + public RainbowComponentT getComponentType () { + return RainbowComponentT.ANALYSIS; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/CalibrationAnalysis.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/CalibrationAnalysis.java index 7af8ba5f5..c0e6bae90 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/CalibrationAnalysis.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/CalibrationAnalysis.java @@ -30,6 +30,7 @@ import org.sa.rainbow.core.RainbowConstants; import org.sa.rainbow.core.analysis.IRainbowAnalysis; import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; import org.sa.rainbow.core.models.ModelReference; import org.sa.rainbow.core.ports.IModelUSBusPort; import org.sa.rainbow.core.ports.IModelsManagerPort; @@ -115,7 +116,7 @@ private MoveAbsHInstruction getPreviousMoveAbsH (MoveAbsHInstruction currentMove protected int m_calibrationErrorObsSize = 0; @Override - protected void runAction () { + protected void runAction () throws RainbowException { ModelReference missionStateRef = new ModelReference ("RobotAndEnvironmentState", MissionStateModelInstance.MISSION_STATE_TYPE); MissionStateModelInstance missionStateModel = (MissionStateModelInstance )m_modelsManagerPort @@ -227,7 +228,7 @@ void insertCurrentLocationInMap (MissionStateModelInstance missionStateModel, InstructionGraphModelInstance igModel, EnvMapModelInstance envModel, InstructionGraphProgress igProgress, - MissionState missionState) { + MissionState missionState) throws RainbowException { EnvMap envMap = envModel.getModelInstance (); // Get current robot position LocationRecording pose = missionState.getCurrentPose (); diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/IGWaypointAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/IGWaypointAnalyzer.java index ea641853b..5c3c476ad 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/IGWaypointAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/IGWaypointAnalyzer.java @@ -1,151 +1,155 @@ -package org.sa.rainbow.brass.analyses; - -import java.util.Collection; -import java.util.Date; - -import org.sa.rainbow.brass.model.IP2ModelAccessor; -import org.sa.rainbow.brass.model.P2ModelAccessor; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.EnvMapNode; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; -import org.sa.rainbow.core.ports.IModelChangeBusPort; -import org.sa.rainbow.core.ports.RainbowPortFactory; - -public class IGWaypointAnalyzer extends P2Analyzer implements IRainbowModelChangeCallback { - - public IGWaypointAnalyzer() { - super("IG to Waypoint"); - } - - private IP2ModelAccessor m_modelAccessor; - private boolean m_newIG = false; - private IRainbowChangeBusSubscription m_newIGSubscription = new IRainbowChangeBusSubscription() { - - @Override - public boolean matches(IRainbowMessage message) { - String modelName = (String) message.getProperty(IModelChangeBusPort.MODEL_NAME_PROP); - String modelType = (String) message.getProperty(IModelChangeBusPort.MODEL_TYPE_PROP); - String commandName = (String) message.getProperty(IModelChangeBusPort.COMMAND_PROP); - - // New IG event - boolean isNewIGEvent = InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE.equals(modelType) - && "setInstructions".equals(commandName); - - return isNewIGEvent; - } - }; - - @Override - public void initializeConnections() throws RainbowConnectionException { - super.initializeConnections(); - m_modelAccessor = new P2ModelAccessor(m_modelsManagerPort); - m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort(); - m_modelChangePort.subscribe(m_newIGSubscription, this); - } - - protected IP2ModelAccessor getModels() { - return m_modelAccessor; - } - - private Long m_time; - - private void handleProblem() { - if (m_time == null) - m_time = new Date().getTime() / 1000; - if (new Date().getTime() / 1000 - 15 > m_time) - throw new NullPointerException( - "IGWaypointAnalyzer waited too long for the current pose or finding the corresponding map position"); - } - - @Override - protected void runAction() { - boolean go = false; - synchronized (this) { - if (m_newIG) - go = true; - } - if (go) { - try { - LocationRecording currentPose = getModels().getMissionStateModel().getModelInstance().getCurrentPose(); - EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); - if (currentPose == null || envMap == null) { - log("Still waiting for pose information"); - handleProblem(); - return; - } - EnvMapNode srcNode = envMap.getNode(currentPose.getX(), currentPose.getY()); - if (srcNode == null) { - log("Robot is not at a location in the map: (" + currentPose.getX() + ", " + currentPose.getY() - + ")"); - log("Robot is not a a location in the map"); - log("The source node is not set, using current pose to guess where robot is coming from"); - String closestNode = "none"; - double distance = Double.MAX_VALUE; - for (EnvMapNode node : envMap.getNodes().values()) { - double d = envMap.distanceBetweenCoords(currentPose.getX(), currentPose.getY(), node.getX(), - node.getY()); - if (d < distance) { - distance = d; - closestNode = node.getLabel(); - srcNode = node; - } - } - log("Guessing that current source is " + closestNode); - - } - - String currentSrc = srcNode == null ? null : srcNode.getLabel(); - Collection instructions = getModels().getInstructionGraphModel() - .getModelInstance().getInstructions(); - for (IInstruction i : instructions) { - if (i instanceof MoveAbsHInstruction) { - MoveAbsHInstruction mai = (MoveAbsHInstruction) i; - if (currentSrc == null) { - log("Current source is null"); - } - mai.setSourceWaypoint(currentSrc); - EnvMapNode node = envMap.getNode(mai.getTargetX(), mai.getTargetY()); - if (node != null) { - String tgtWp = node.getLabel(); - mai.setTargetWaypoint(tgtWp); - currentSrc = tgtWp; - } else { - throw new NullPointerException("Node from " + mai.getTargetX() + ", " + mai.getTargetY() - + " does not exist in envmap in instruction " + mai.getInstruction()); - } - } - } - - log("Received and processed a new IG"); - synchronized (this) { - m_newIG = false; - } - } catch (Throwable e) { - e.printStackTrace(); - log("IG processor encountered an error"); - } finally { - m_modelUSPort.updateModel(getModels().getRainbowStateModel().getCommandFactory().clearModelProblems()); - getModels().getRainbowStateModel().getModelInstance().m_waitForIG = false; - } - - } - } - - @Override - public void onEvent(ModelReference reference, IRainbowMessage message) { - log("Notified of a new IG"); - synchronized (this) { - m_newIG = true; - } - - } - -} +package org.sa.rainbow.brass.analyses; + +import java.util.Collection; +import java.util.Date; + +import org.sa.rainbow.brass.model.IP2ModelAccessor; +import org.sa.rainbow.brass.model.P2ModelAccessor; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.EnvMapNode; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; + +public class IGWaypointAnalyzer extends P2Analyzer implements IRainbowModelChangeCallback { + + public IGWaypointAnalyzer() { + super("IG to Waypoint"); + } + + private IP2ModelAccessor m_modelAccessor; + private boolean m_newIG = false; + private IRainbowChangeBusSubscription m_newIGSubscription = new IRainbowChangeBusSubscription() { + + @Override + public boolean matches(IRainbowMessage message) { + String modelName = (String) message.getProperty(IModelChangeBusPort.MODEL_NAME_PROP); + String modelType = (String) message.getProperty(IModelChangeBusPort.MODEL_TYPE_PROP); + String commandName = (String) message.getProperty(IModelChangeBusPort.COMMAND_PROP); + + // New IG event + boolean isNewIGEvent = InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE.equals(modelType) + && "setInstructions".equals(commandName); + + return isNewIGEvent; + } + }; + + @Override + public void initializeConnections() throws RainbowConnectionException { + super.initializeConnections(); + m_modelAccessor = new P2ModelAccessor(m_modelsManagerPort); + m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort(); + m_modelChangePort.subscribe(m_newIGSubscription, this); + } + + protected IP2ModelAccessor getModels() { + return m_modelAccessor; + } + + private Long m_time; + + private void handleProblem() { + if (m_time == null) + m_time = new Date().getTime() / 1000; + if (new Date().getTime() / 1000 - 15 > m_time) + throw new NullPointerException( + "IGWaypointAnalyzer waited too long for the current pose or finding the corresponding map position"); + } + + @Override + protected void runAction() throws RainbowException { + boolean go = false; + synchronized (this) { + if (m_newIG) + go = true; + } + if (go) { + try { + LocationRecording currentPose = getModels().getMissionStateModel().getModelInstance().getCurrentPose(); + EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); + if (currentPose == null || envMap == null) { + log("Still waiting for pose information"); + handleProblem(); + return; + } + EnvMapNode srcNode = envMap.getNode(currentPose.getX(), currentPose.getY()); + if (srcNode == null) { + log("Robot is not at a location in the map: (" + currentPose.getX() + ", " + currentPose.getY() + + ")"); + log("Robot is not a a location in the map"); + log("The source node is not set, using current pose to guess where robot is coming from"); + String closestNode = "none"; + double distance = Double.MAX_VALUE; + for (EnvMapNode node : envMap.getNodes().values()) { + double d = envMap.distanceBetweenCoords(currentPose.getX(), currentPose.getY(), node.getX(), + node.getY()); + if (d < distance) { + distance = d; + closestNode = node.getLabel(); + srcNode = node; + } + } + log("Guessing that current source is " + closestNode); + + } + + String currentSrc = srcNode == null ? null : srcNode.getLabel(); + Collection instructions = getModels().getInstructionGraphModel() + .getModelInstance().getInstructions(); + StringBuilder sb = new StringBuilder("Current instructions are:"); + for (IInstruction i : instructions) { + if (i instanceof MoveAbsHInstruction) { + MoveAbsHInstruction mai = (MoveAbsHInstruction) i; + if (currentSrc == null) { + log("Current source is null"); + } + mai.setSourceWaypoint(currentSrc); + EnvMapNode node = envMap.getNode(mai.getTargetX(), mai.getTargetY()); + if (node != null) { + String tgtWp = node.getLabel(); + mai.setTargetWaypoint(tgtWp); + currentSrc = tgtWp; + } else { + throw new NullPointerException("Node from " + mai.getTargetX() + ", " + mai.getTargetY() + + " does not exist in envmap in instruction " + mai.getInstruction()); + } + } + sb.append("\n").append(i.toString()); + } + log(sb.toString()); + + log("Received and processed a new IG"); + synchronized (this) { + m_newIG = false; + } + } catch (Throwable e) { + e.printStackTrace(); + log("IG processor encountered an error"); + } finally { + m_modelUSPort.updateModel(getModels().getRainbowStateModel().getCommandFactory().clearModelProblems()); + getModels().getRainbowStateModel().getModelInstance().m_waitForIG = false; + } + + } + } + + @Override + public void onEvent(ModelReference reference, IRainbowMessage message) { + log("Notified of a new IG"); + synchronized (this) { + m_newIG = true; + } + + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/P2Analyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/P2Analyzer.java index c4d599f5a..262d5d805 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/P2Analyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/P2Analyzer.java @@ -1,84 +1,84 @@ -package org.sa.rainbow.brass.analyses; - -import org.apache.log4j.Logger; -import org.sa.rainbow.core.AbstractRainbowRunnable; -import org.sa.rainbow.core.IRainbowEnvironment; -import org.sa.rainbow.core.IRainbowRunnable; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.RainbowConstants; -import org.sa.rainbow.core.analysis.IRainbowAnalysis; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; -import org.sa.rainbow.core.ports.IModelUSBusPort; -import org.sa.rainbow.core.ports.IModelsManagerPort; -import org.sa.rainbow.core.ports.IRainbowReportingPort; -import org.sa.rainbow.core.ports.RainbowPortFactory; - -public abstract class P2Analyzer extends AbstractRainbowRunnable implements IRainbowAnalysis { - static protected final Logger LOGGER = Logger.getLogger("Analyzer"); - - protected IModelUSBusPort m_modelUSPort; - protected IModelsManagerPort m_modelsManagerPort; - protected IModelChangeBusSubscriberPort m_modelChangePort; - - public P2Analyzer(String name) { - super(name); - - } - - public P2Analyzer(String name, IRainbowEnvironment env) { - super(name, env); - } - - @Override - public RainbowComponentT getComponentType() { - return RainbowComponentT.ANALYSIS; - - } - - @Override - public void log(String txt) { - m_reportingPort.info(RainbowComponentT.ANALYSIS, id() + ": " + txt, LOGGER); - } - - protected void initializeConnections() throws RainbowConnectionException { - m_modelUSPort = RainbowPortFactory.createModelsManagerClientUSPort(this); - m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort(); - m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort(); - } - - @Override - public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { - super.initialize(port); - String period = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); - if (period != null) { - setSleepTime(Long.parseLong(period)); - } else { - setSleepTime(IRainbowRunnable.LONG_SLEEP_TIME); - } - initializeConnections(); - } - - @Override - public void setProperty(String arg0, String arg1) { - // TODO Auto-generated method stub - - } - - @Override - public String getProperty(String arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void dispose() { - m_reportingPort.dispose(); - m_modelUSPort.dispose(); - - } - - - -} +package org.sa.rainbow.brass.analyses; + +import org.apache.log4j.Logger; +import org.sa.rainbow.core.AbstractRainbowRunnable; +import org.sa.rainbow.core.IRainbowEnvironment; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.analysis.IRainbowAnalysis; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelUSBusPort; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; + +public abstract class P2Analyzer extends AbstractRainbowRunnable implements IRainbowAnalysis { + static protected final Logger LOGGER = Logger.getLogger("Analyzer"); + + protected IModelUSBusPort m_modelUSPort; + protected IModelsManagerPort m_modelsManagerPort; + protected IModelChangeBusSubscriberPort m_modelChangePort; + + public P2Analyzer(String name) { + super(name); + + } + + public P2Analyzer(String name, IRainbowEnvironment env) { + super(name, env); + } + + @Override + public RainbowComponentT getComponentType() { + return RainbowComponentT.ANALYSIS; + + } + + @Override + public void log(String txt) { + m_reportingPort.info(RainbowComponentT.ANALYSIS, id() + ": " + txt, LOGGER); + } + + protected void initializeConnections() throws RainbowConnectionException { + m_modelUSPort = RainbowPortFactory.createModelsManagerClientUSPort(this); + m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort(); + m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort(); + } + + @Override + public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize(port); + String period = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (period != null) { + setSleepTime(Long.parseLong(period)); + } else { + setSleepTime(IRainbowRunnable.LONG_SLEEP_TIME); + } + initializeConnections(); + } + + @Override + public void setProperty(String arg0, String arg1) { + // TODO Auto-generated method stub + + } + + @Override + public String getProperty(String arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void dispose() { + m_reportingPort.dispose(); + m_modelUSPort.dispose(); + + } + + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/TimingAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/TimingAnalyzer.java index fc10d3b3f..c335a53d9 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/TimingAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/TimingAnalyzer.java @@ -28,6 +28,7 @@ import org.sa.rainbow.core.RainbowConstants; import org.sa.rainbow.core.analysis.IRainbowAnalysis; import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; import org.sa.rainbow.core.event.IRainbowMessage; import org.sa.rainbow.core.models.ModelReference; import org.sa.rainbow.core.ports.IModelChangeBusPort; @@ -145,7 +146,7 @@ public RainbowComponentT getComponentType () { } @Override - public void onEvent (ModelReference mr, IRainbowMessage message) { + public void onEvent (ModelReference mr, IRainbowMessage message) throws RainbowException { synchronized (this) { // Either a new deadline or a new IG has been set (or both) // Timing analyzer can resume periodic analysis @@ -170,7 +171,7 @@ protected void log (String text) { } @Override - protected void runAction () { + protected void runAction () throws RainbowException { // If adaptation planning is in progress, wait for it to finish before performing analysis if (!m_waitForPlanner) { // Do the periodic analysis on the models of interest diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/BRASSMissionAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/BRASSMissionAnalyzer.java index ae4af78ab..6874585a4 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/BRASSMissionAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/BRASSMissionAnalyzer.java @@ -1,170 +1,171 @@ -package org.sa.rainbow.brass.analyses.p2_cp1; - -import java.util.Arrays; - -import org.sa.rainbow.brass.das.BRASSHttpConnector; -import org.sa.rainbow.brass.das.IBRASSConnector.Phases; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.InsertNodeCmd; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RemoveModelProblemCmd; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.SetModelProblemCmd; -import org.sa.rainbow.core.IRainbowRunnable; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowConstants; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IRainbowReportingPort; - -/** - * Created by schmerl on 12/13/2016. Analyzes the current situation and triggers - * adaptation if necessary - */ -public class BRASSMissionAnalyzer extends P2CP1Analyzer { - - public static final String NAME = "BRASS Mission Evaluator"; - - private boolean m_reportedReady = false; - private boolean m_wasOK; - - private boolean m_awaitingNewIG; - - private boolean m_reportedCompleted; - - public BRASSMissionAnalyzer() { - super(NAME); - String per = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); - if (per != null) { - setSleepTime(Long.parseLong(per)); - } else { - setSleepTime(IRainbowRunnable.LONG_SLEEP_TIME); - } - } - - @Override - public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { - super.initialize(port); - log("Initialized missions analyzer"); - } - - @Override - protected void runAction() { - MissionState ms = getModels().getMissionStateModel().getModelInstance(); - if (!m_reportedReady && ms.getInitialPose() != null) { - m_reportedReady = true; - BRASSHttpConnector.instance(Phases.Phase2).setClock(getModels().getMissionStateModel().getModelInstance()); - BRASSHttpConnector.instance(Phases.Phase2).reportReady(true); - m_wasOK = true; - } - if (getModels().getRainbowStateModel().getModelInstance().waitForIG()) { - m_wasOK = true; - return; - } - // Do the periodic analysis on the models of interest - InstructionGraphModelInstance ig = getModels().getInstructionGraphModel(); - - - if (ms.isMissionStarted() && ms.getInitialPose() != null) { - - boolean currentOK = ig.getModelInstance().getCurrentOK(); -// if (ig.getModelInstance().getInstructionGraphState() == IGExecutionStateT.FINISHED_SUCCESS && !m_reportedCompleted) { -// m_reportedCompleted = true; -// m_awaitingNewIG = true; -// SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory().setModelProblem(CP3ModelState.MISSION_COMPLETED); -// return; -// } - if (!currentOK && m_wasOK && !getModels().getRainbowStateModel().getModelInstance().waitForIG()) { - m_wasOK = false; - m_reportingPort.info(getComponentType(), "Instruction graph failed...updating map model"); - SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() - .setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); - SetModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() - .setModelProblem(CP3ModelState.IS_OBSTRUCTED); - m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); - m_awaitingNewIG = true; - } - else if (currentOK && !emptyInstructions(ig.getModelInstance()) && getModels().getRainbowStateModel().getModelInstance() - .getProblems().contains(RainbowState.CP3ModelState.IS_OBSTRUCTED)) { - // New IG resumed after robot obstructed - log("New instruction model was detected. Reseting models to ok"); - m_reportingPort.info(getComponentType(), "New instruction graph detected"); - m_awaitingNewIG = false; - getModels().getRainbowStateModel().getModelInstance().m_waitForIG = false; - // Clear robot obstructed flag - RemoveModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() - .removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); - RemoveModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() - .removeModelProblem(CP3ModelState.IS_OBSTRUCTED); - m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); - - } - } - - -// if (getModels().getInstructionGraphModel() == null) -// return; -// InstructionGraphProgress igModel = getModels().getInstructionGraphModel().getModelInstance(); -// boolean currentOK = igModel.getCurrentOK(); - -// org.sa.rainbow.brass.model.p2_cp3.mission.MissionState missionState = getModels().getMissionStateModel() -// .getModelInstance(); -// EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); -// if (missionState.getCurrentPose() == null) { -// m_awaitingPose = true; -// } else if (missionState.getCurrentPose() != null && m_awaitingPose) { -// m_awaitingPose = false; -// BRASSHttpConnector.instance(Phases.Phase2).reportReady(true); -// -// } else if (!currentOK && igModel.getExecutingInstruction() != null && !m_awaitingNewIG) { -// // Current IG failed -// m_reportingPort.info(getComponentType(), "Instruction graph failed...updating map model"); -// // BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.PERTURBATION_DETECTED, -// // "Obstruction to path detected"); -// // // Get current robot position -// // org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording pose -// // = missionState -// // .getCurrentPose(); -// // -// // // Get source and target positions of the failing instruction -// // IInstruction currentInst = igModel.getCurrentInstruction(); -// // -// // // The current instruction is of type MoveAbsH -// // insertNodeIntoMap(pose, currentInst); -// SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() -// .setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); -// SetModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() -// .setModelProblem(CP3ModelState.IS_OBSTRUCTED); -// m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); -// m_awaitingNewIG = true; -// } else if (currentOK && !emptyInstructions(igModel) && getModels().getRainbowStateModel().getModelInstance() -// .getProblems().contains(RainbowState.CP3ModelState.IS_OBSTRUCTED)) { -// // New IG resumed after robot obstructed -// log("New instruction model was detected. Reseting models to ok"); -// m_reportingPort.info(getComponentType(), "New instruction graph detected"); -// m_awaitingNewIG = false; -// getModels().getRainbowStateModel().getModelInstance().m_waitForIG = false; -// // Clear robot obstructed flag -// -// RemoveModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() -// .removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); -// RemoveModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() -// .removeModelProblem(CP3ModelState.IS_OBSTRUCTED); -// m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); -// -// } - - } - - boolean emptyInstructions(InstructionGraphProgress igProgress) { - return igProgress.getInstructions() == null || igProgress.getInstructions().isEmpty(); - } - -} +package org.sa.rainbow.brass.analyses.p2_cp1; + +import java.util.Arrays; + +import org.sa.rainbow.brass.das.BRASSHttpConnector; +import org.sa.rainbow.brass.das.IBRASSConnector.Phases; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.InsertNodeCmd; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RemoveModelProblemCmd; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.SetModelProblemCmd; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IRainbowReportingPort; + +/** + * Created by schmerl on 12/13/2016. Analyzes the current situation and triggers + * adaptation if necessary + */ +public class BRASSMissionAnalyzer extends P2CP1Analyzer { + + public static final String NAME = "BRASS Mission Evaluator"; + + private boolean m_reportedReady = false; + private boolean m_wasOK; + + private boolean m_awaitingNewIG; + + private boolean m_reportedCompleted; + + public BRASSMissionAnalyzer() { + super(NAME); + String per = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (per != null) { + setSleepTime(Long.parseLong(per)); + } else { + setSleepTime(IRainbowRunnable.LONG_SLEEP_TIME); + } + } + + @Override + public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize(port); + log("Initialized missions analyzer"); + } + + @Override + protected void runAction() throws RainbowException { + MissionState ms = getModels().getMissionStateModel().getModelInstance(); + if (!m_reportedReady && ms.getInitialPose() != null) { + m_reportedReady = true; + BRASSHttpConnector.instance(Phases.Phase2).setClock(getModels().getMissionStateModel().getModelInstance()); + BRASSHttpConnector.instance(Phases.Phase2).reportReady(true); + m_wasOK = true; + } + if (getModels().getRainbowStateModel().getModelInstance().waitForIG()) { + m_wasOK = true; + return; + } + // Do the periodic analysis on the models of interest + InstructionGraphModelInstance ig = getModels().getInstructionGraphModel(); + + + if (ms.isMissionStarted() && ms.getInitialPose() != null) { + + boolean currentOK = ig.getModelInstance().getCurrentOK(); +// if (ig.getModelInstance().getInstructionGraphState() == IGExecutionStateT.FINISHED_SUCCESS && !m_reportedCompleted) { +// m_reportedCompleted = true; +// m_awaitingNewIG = true; +// SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory().setModelProblem(CP3ModelState.MISSION_COMPLETED); +// return; +// } + if (!currentOK && m_wasOK && !getModels().getRainbowStateModel().getModelInstance().waitForIG()) { + m_wasOK = false; + m_reportingPort.info(getComponentType(), "Instruction graph failed...updating map model"); + SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() + .setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); + SetModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() + .setModelProblem(CP3ModelState.IS_OBSTRUCTED); + m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); + m_awaitingNewIG = true; + } + else if (currentOK && !emptyInstructions(ig.getModelInstance()) && getModels().getRainbowStateModel().getModelInstance() + .getProblems().contains(RainbowState.CP3ModelState.IS_OBSTRUCTED)) { + // New IG resumed after robot obstructed + log("New instruction model was detected. Reseting models to ok"); + m_reportingPort.info(getComponentType(), "New instruction graph detected"); + m_awaitingNewIG = false; + getModels().getRainbowStateModel().getModelInstance().m_waitForIG = false; + // Clear robot obstructed flag + RemoveModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() + .removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); + RemoveModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() + .removeModelProblem(CP3ModelState.IS_OBSTRUCTED); + m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); + + } + } + + +// if (getModels().getInstructionGraphModel() == null) +// return; +// InstructionGraphProgress igModel = getModels().getInstructionGraphModel().getModelInstance(); +// boolean currentOK = igModel.getCurrentOK(); + +// org.sa.rainbow.brass.model.p2_cp3.mission.MissionState missionState = getModels().getMissionStateModel() +// .getModelInstance(); +// EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); +// if (missionState.getCurrentPose() == null) { +// m_awaitingPose = true; +// } else if (missionState.getCurrentPose() != null && m_awaitingPose) { +// m_awaitingPose = false; +// BRASSHttpConnector.instance(Phases.Phase2).reportReady(true); +// +// } else if (!currentOK && igModel.getExecutingInstruction() != null && !m_awaitingNewIG) { +// // Current IG failed +// m_reportingPort.info(getComponentType(), "Instruction graph failed...updating map model"); +// // BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.PERTURBATION_DETECTED, +// // "Obstruction to path detected"); +// // // Get current robot position +// // org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording pose +// // = missionState +// // .getCurrentPose(); +// // +// // // Get source and target positions of the failing instruction +// // IInstruction currentInst = igModel.getCurrentInstruction(); +// // +// // // The current instruction is of type MoveAbsH +// // insertNodeIntoMap(pose, currentInst); +// SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() +// .setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); +// SetModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() +// .setModelProblem(CP3ModelState.IS_OBSTRUCTED); +// m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); +// m_awaitingNewIG = true; +// } else if (currentOK && !emptyInstructions(igModel) && getModels().getRainbowStateModel().getModelInstance() +// .getProblems().contains(RainbowState.CP3ModelState.IS_OBSTRUCTED)) { +// // New IG resumed after robot obstructed +// log("New instruction model was detected. Reseting models to ok"); +// m_reportingPort.info(getComponentType(), "New instruction graph detected"); +// m_awaitingNewIG = false; +// getModels().getRainbowStateModel().getModelInstance().m_waitForIG = false; +// // Clear robot obstructed flag +// +// RemoveModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() +// .removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); +// RemoveModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() +// .removeModelProblem(CP3ModelState.IS_OBSTRUCTED); +// m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); +// +// } + + } + + boolean emptyInstructions(InstructionGraphProgress igProgress) { + return igProgress.getInstructions() == null || igProgress.getInstructions().isEmpty(); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/EnergyConsumptionAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/EnergyConsumptionAnalyzer.java index f5b54efb8..1bcd46634 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/EnergyConsumptionAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/EnergyConsumptionAnalyzer.java @@ -1,142 +1,143 @@ -package org.sa.rainbow.brass.analyses.p2_cp1; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.sa.rainbow.brass.confsynthesis.Configuration; -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.brass.model.instructions.ChargeInstruction; -import org.sa.rainbow.brass.model.instructions.ForwardInstruction; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.instructions.SetConfigInstruction; -import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; -import org.sa.rainbow.brass.model.map.BatteryPredictor; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.EnvMapModelInstance; -import org.sa.rainbow.brass.model.map.MapTranslator; -import org.sa.rainbow.brass.model.mission.MissionStateModelInstance; -import org.sa.rainbow.brass.model.mission.MissionState.Heading; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IRainbowReportingPort; -import org.sa.rainbow.core.util.Pair; - -public class EnergyConsumptionAnalyzer extends P2CP1Analyzer { - public static final String NAME = "BRASS Accuracy Evaluator"; - private IInstruction m_prevAnalyzedAndPassedInstruction; - private SimpleConfigurationStore m_powerModel; - - public EnergyConsumptionAnalyzer() { - super(NAME); - } - - @Override - public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { - super.initialize(port); - m_powerModel = new SimpleConfigurationStore(Rainbow.instance().allProperties()); - m_powerModel.populate(); - } - - @Override - protected void runAction() { - if (getModels().getInstructionGraphModel() == null) - return; - // Need to work out how to wait for planner in CP1 -- is it - if (getModels().getRainbowStateModel().getModelInstance().waitForIG()) - return; - InstructionGraphProgress igModel = getModels().getInstructionGraphModel().getModelInstance(); - IInstruction currentInstruction = igModel.getCurrentInstruction(); - if (currentInstruction == m_prevAnalyzedAndPassedInstruction) - return; - - if (!(currentInstruction instanceof ChargeInstruction)) { - List remainingInstructions = igModel.getRemainingInstructions(); - double batteryCharge = -1; - try { - batteryCharge = getModels().getRobotStateModel().getModelInstance().getCharge(); - if (batteryCharge <= 0) { - IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() - .setModelProblem(CP3ModelState.OUT_OF_BATTERY); - m_modelUSPort.updateModel(op); - return; - } - } catch (IllegalStateException e) { - // Don't have battery information yet - return; - } - - // We need to break the instructions into chunks that are segmented by charge - // and then ask - // is there enough energy to get to each charge instruction or the target? - String tgtWP = getModels().getMissionStateModel().getModelInstance().getTargetWaypoint(); - List> segments = InstructionGraphProgress - .segmentByInstructionType(remainingInstructions, ChargeInstruction.class); - Iterator> it = segments.iterator(); - boolean first = true; - boolean hasEnoughEnergy = true; - EnergyConsumptionPredictor predictor = new EnergyConsumptionPredictor( - getModels().getEnvMapModel().getModelInstance(), - getModels().getMissionStateModel().getModelInstance(), m_powerModel); - predictor.setConfig(getModels().getRobotStateModel().getModelInstance().getConfigId()); - try { - while (it.hasNext()) { - if (first) { - first = false; - hasEnoughEnergy &= predictor.getPlanEnergyConsumption(currentInstruction, it.next(), - tgtWP) < batteryCharge; - } else { - hasEnoughEnergy &= predictor.getPlanEnergyConsumption(null, it.next(), - tgtWP) < MapTranslator.ROBOT_BATTERY_RANGE_MAX; - } - } - } catch (NullPointerException e) { - log("Could not yet analyze the instruction graph -- could be waypoints have not been set up"); - m_reportingPort.error(RainbowComponentT.ANALYSIS, e.getMessage(), e, LOGGER); - return; - } - // double planEnergyConsumption = hasEnoughEnergy(currentInstruction, - // remainingInstructions); - // boolean hasEnoughEnergy = batteryCharge >= planEnergyConsumption; - // log("Current charge = " + batteryCharge + ", needed charge = " + - // planEnergyConsumption); - if (hasEnoughEnergy) { - // Keep track of the latest instruction that we have analyzed the accuracy - // property, - // and it passed - m_prevAnalyzedAndPassedInstruction = currentInstruction; - } - boolean knowAboutLowBattery = getModels().getRainbowStateModel().getModelInstance().getProblems() - .contains(CP3ModelState.LOW_ON_BATTERY); - if (hasEnoughEnergy && knowAboutLowBattery) { - IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() - .removeModelProblem(CP3ModelState.LOW_ON_BATTERY); - m_modelUSPort.updateModel(op); - } else if (!hasEnoughEnergy && !knowAboutLowBattery) { - log("Do not have enough battery."); - LocationRecording pose = getModels().getMissionStateModel().getModelInstance().getCurrentPose(); - insertNodeIntoMap(pose, currentInstruction); - IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() - .setModelProblem(CP3ModelState.LOW_ON_BATTERY); - m_modelUSPort.updateModel(op); - - } - } else if (getModels().getRainbowStateModel().getModelInstance().getProblems() - .contains(CP3ModelState.LOW_ON_BATTERY)) { - IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() - .removeModelProblem(CP3ModelState.LOW_ON_BATTERY); - m_modelUSPort.updateModel(op); - } - } - -} +package org.sa.rainbow.brass.analyses.p2_cp1; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.sa.rainbow.brass.confsynthesis.Configuration; +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.brass.model.instructions.ChargeInstruction; +import org.sa.rainbow.brass.model.instructions.ForwardInstruction; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.instructions.SetConfigInstruction; +import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; +import org.sa.rainbow.brass.model.map.BatteryPredictor; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.EnvMapModelInstance; +import org.sa.rainbow.brass.model.map.MapTranslator; +import org.sa.rainbow.brass.model.mission.MissionStateModelInstance; +import org.sa.rainbow.brass.model.mission.MissionState.Heading; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.util.Pair; + +public class EnergyConsumptionAnalyzer extends P2CP1Analyzer { + public static final String NAME = "BRASS Accuracy Evaluator"; + private IInstruction m_prevAnalyzedAndPassedInstruction; + private SimpleConfigurationStore m_powerModel; + + public EnergyConsumptionAnalyzer() { + super(NAME); + } + + @Override + public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize(port); + m_powerModel = new SimpleConfigurationStore(Rainbow.instance().allProperties()); + m_powerModel.populate(); + } + + @Override + protected void runAction() throws RainbowException { + if (getModels().getInstructionGraphModel() == null) + return; + // Need to work out how to wait for planner in CP1 -- is it + if (getModels().getRainbowStateModel().getModelInstance().waitForIG()) + return; + InstructionGraphProgress igModel = getModels().getInstructionGraphModel().getModelInstance(); + IInstruction currentInstruction = igModel.getCurrentInstruction(); + if (currentInstruction == m_prevAnalyzedAndPassedInstruction) + return; + + if (!(currentInstruction instanceof ChargeInstruction)) { + List remainingInstructions = igModel.getRemainingInstructions(); + double batteryCharge = -1; + try { + batteryCharge = getModels().getRobotStateModel().getModelInstance().getCharge(); + if (batteryCharge <= 0) { + IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() + .setModelProblem(CP3ModelState.OUT_OF_BATTERY); + m_modelUSPort.updateModel(op); + return; + } + } catch (IllegalStateException e) { + // Don't have battery information yet + return; + } + + // We need to break the instructions into chunks that are segmented by charge + // and then ask + // is there enough energy to get to each charge instruction or the target? + String tgtWP = getModels().getMissionStateModel().getModelInstance().getTargetWaypoint(); + List> segments = InstructionGraphProgress + .segmentByInstructionType(remainingInstructions, ChargeInstruction.class); + Iterator> it = segments.iterator(); + boolean first = true; + boolean hasEnoughEnergy = true; + EnergyConsumptionPredictor predictor = new EnergyConsumptionPredictor( + getModels().getEnvMapModel().getModelInstance(), + getModels().getMissionStateModel().getModelInstance(), m_powerModel); + predictor.setConfig(getModels().getRobotStateModel().getModelInstance().getConfigId()); + try { + while (it.hasNext()) { + if (first) { + first = false; + hasEnoughEnergy &= predictor.getPlanEnergyConsumption(currentInstruction, it.next(), + tgtWP) < batteryCharge; + } else { + hasEnoughEnergy &= predictor.getPlanEnergyConsumption(null, it.next(), + tgtWP) < MapTranslator.ROBOT_BATTERY_RANGE_MAX; + } + } + } catch (NullPointerException e) { + log("Could not yet analyze the instruction graph -- could be waypoints have not been set up"); + m_reportingPort.error(RainbowComponentT.ANALYSIS, e.getMessage(), e, LOGGER); + return; + } + // double planEnergyConsumption = hasEnoughEnergy(currentInstruction, + // remainingInstructions); + // boolean hasEnoughEnergy = batteryCharge >= planEnergyConsumption; + // log("Current charge = " + batteryCharge + ", needed charge = " + + // planEnergyConsumption); + if (hasEnoughEnergy) { + // Keep track of the latest instruction that we have analyzed the accuracy + // property, + // and it passed + m_prevAnalyzedAndPassedInstruction = currentInstruction; + } + boolean knowAboutLowBattery = getModels().getRainbowStateModel().getModelInstance().getProblems() + .contains(CP3ModelState.LOW_ON_BATTERY); + if (hasEnoughEnergy && knowAboutLowBattery) { + IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() + .removeModelProblem(CP3ModelState.LOW_ON_BATTERY); + m_modelUSPort.updateModel(op); + } else if (!hasEnoughEnergy && !knowAboutLowBattery) { + log("Do not have enough battery."); + LocationRecording pose = getModels().getMissionStateModel().getModelInstance().getCurrentPose(); + insertNodeIntoMap(pose, currentInstruction); + IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() + .setModelProblem(CP3ModelState.LOW_ON_BATTERY); + m_modelUSPort.updateModel(op); + + } + } else if (getModels().getRainbowStateModel().getModelInstance().getProblems() + .contains(CP3ModelState.LOW_ON_BATTERY)) { + IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() + .removeModelProblem(CP3ModelState.LOW_ON_BATTERY); + m_modelUSPort.updateModel(op); + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/EnergyConsumptionPredictor.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/EnergyConsumptionPredictor.java index 5f65f4d3a..6a58bfda3 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/EnergyConsumptionPredictor.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/EnergyConsumptionPredictor.java @@ -1,319 +1,319 @@ -package org.sa.rainbow.brass.analyses.p2_cp1; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.sa.rainbow.brass.confsynthesis.Configuration; -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.brass.model.instructions.ChargeInstruction; -import org.sa.rainbow.brass.model.instructions.ForwardInstruction; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.instructions.SetConfigInstruction; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.MapTranslator; -import org.sa.rainbow.brass.model.mission.MissionState.Heading; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.core.util.Pair; - -public class EnergyConsumptionPredictor { - private static final int GOAL_RADIUS = 50; // centimeters //TODO - - private EnvMap m_envMap; - private MissionState m_missionState; - private String m_config; - - private SimpleConfigurationStore m_powerModel; - - public EnergyConsumptionPredictor(EnvMap e, MissionState m, SimpleConfigurationStore powerModel) { - m_envMap = e; - m_missionState = m; - m_powerModel = powerModel; - } - - public void setConfig(String config) { - m_config = config; - } - - // TODO check the signature - public double getEnergyConsumption(Configuration config, double time) { - if(config == null) { - throw new IllegalArgumentException("The configuration cannot be null"); - } - - double powerLoad = config.getEnergyDischargeRate(); - - if(powerLoad <= 0.0) { - throw new IllegalArgumentException("The power load has to be greater than 0"); - } - - if(time == 0.0) { - throw new IllegalArgumentException("There are no more tasks to do"); - } - - if(time < 0.0) { - throw new IllegalArgumentException("The time to complete tasks cannot be negative"); - } - - - return this.getEnergyConsumption(powerLoad, time); - } - - /** - * Get the energy consumed in a given time period. - * - * @param powerLoad - * @param time - * @return - */ - public double getEnergyConsumption(double powerLoad, double time) { - if(powerLoad <= 0.0) { - throw new IllegalArgumentException("The power load has to be greater than 0"); - } - - if(time == 0.0) { - throw new IllegalArgumentException("There are no more tasks to do"); - } - - if(time < 0.0) { - throw new IllegalArgumentException("The time to complete tasks cannot be negative"); - } - - double energy = powerLoad * time; - return energy; - } - - /** - * Check if the task can be completed based on the energyConsumption that will be consumed and the current energyConsumption. - * - * @param curEnergy - * @param energyConsumed - * @return - */ - public boolean canCompleteTask(double curEnergy, double energyConsumed) { - if(curEnergy < 0.0) { - throw new IllegalArgumentException("The current energy cannot be less than 0"); - } - - if(curEnergy == 0.0) { - throw new IllegalArgumentException("The battery is empty"); - } - - if(energyConsumed <= 0.0) { - throw new IllegalArgumentException("The energy consumed has to be greater than 0"); - } - - return curEnergy >= energyConsumed; - } - - /** - * Checks if the instructions can be completed with the remaining energy - */ - public double getPlanEnergyConsumption (IInstruction currentInstruction, List remainingInstructions, String tgtWP) { - double planEnergyConsumption = getExpectedIGEnergyConsumption(currentInstruction, remainingInstructions, tgtWP); - return planEnergyConsumption; - } - - private double getExpectedIGEnergyConsumption(IInstruction currentInstruction, List remainingInstructions, String tgtWP) { - double totalEnergy = 0; - - // Goal location - double goalX = m_envMap.getNodeX(m_missionState.getTargetWaypoint()); - double goalY = m_envMap.getNodeY(m_missionState.getTargetWaypoint()); - if (goalX == Double.NEGATIVE_INFINITY || goalY == Double.NEGATIVE_INFINITY) return 0; - - double sourceX = m_missionState.getCurrentPose().getX(); - double sourceY = m_missionState.getCurrentPose().getY(); - double sourceW = m_missionState.getCurrentPose().getRotation(); - - List allInstructions = new ArrayList<>(); - if (currentInstruction != null) allInstructions.add(currentInstruction); - allInstructions.addAll(remainingInstructions); - int i = 0; - for (IInstruction instruction : allInstructions) { - double instEnergy = 0; - - // Special case: for the last instruction, only calculate the energy required to get - // within a certain radius from the goal location - if (i == allInstructions.size() - 1 && instruction instanceof MoveAbsHInstruction && (((MoveAbsHInstruction )instruction).getTargetWaypoint().equals(tgtWP))) { - // For MoveAbsH, use the target location that is GOAL_RADIUS from the goal, and is nearest the source - Pair targetLocation = getNearestTargetLocation(sourceX, sourceY, goalX, goalY, GOAL_RADIUS); - double targetX = targetLocation.firstValue(); - double targetY = targetLocation.secondValue(); - - MoveAbsHInstruction moveAbsH = (MoveAbsHInstruction) instruction; - String newMoveAbsH = - MessageFormat.format ( - "MoveAbsH({0,number,##.##}, {1,number,##.##}, {2,number,##.##}, {3,number,##.###})", - targetX, targetY, moveAbsH.getSpeed (), moveAbsH.getTargetW ()); -// String.format("MoveAbsH(%d, %d, %d, %d)", targetX, targetY, moveAbsH.getSpeed(), moveAbsH.getTargetW()); - MoveAbsHInstruction moveAbsHCopy = - new MoveAbsHInstruction(moveAbsH.getInstructionLabel(), newMoveAbsH, moveAbsH.getNextInstructionLabel()); - instEnergy = getMoveAbsHEnergyConsumption(moveAbsHCopy, sourceX, sourceY, sourceW, m_config); - - } else if (i == allInstructions.size() - 1 && instruction instanceof ForwardInstruction) { - // For Forward, use the distance that is GOAL_RADIUS shorter than the original distance - ForwardInstruction forward = (ForwardInstruction) instruction; - String newForward = MessageFormat.format ("Forward({0,number,##.##}, {1,number,##.##})", - forward.getDistance () - GOAL_RADIUS, forward.getSpeed ()); -// String.format("Forward(%d, %d)", forward.getDistance() - GOAL_RADIUS, forward.getSpeed()); - ForwardInstruction forwardCopy = - new ForwardInstruction(forward.getInstructionLabel(), newForward, forward.getNextInstructionLabel()); - instEnergy = getForwardEnergyConsumption(forwardCopy, sourceX, sourceY, sourceW, m_config); - - } else if (instruction instanceof MoveAbsHInstruction) { - MoveAbsHInstruction moveAbsH = (MoveAbsHInstruction) instruction; - instEnergy = getMoveAbsHEnergyConsumption(moveAbsH, sourceX, sourceY, sourceW, m_config); - - // Update source pose for the next instruction - sourceX = moveAbsH.getTargetX();; - sourceY = moveAbsH.getTargetY(); - sourceW = moveAbsH.getTargetW(); - } else if (instruction instanceof ForwardInstruction) { - ForwardInstruction forward = (ForwardInstruction) instruction; - instEnergy = getForwardEnergyConsumption(forward, sourceX, sourceY, sourceW, m_config); - - // Update source pose for the next instruction - sourceX = sourceX + forward.getDistance() * Math.cos(sourceW);; - sourceY = sourceY + forward.getDistance() * Math.sin(sourceW); - } else if (instruction instanceof ChargeInstruction) { - // This should not happen because we should segment on Charges - // double energyGain = bp.batteryCharge(charge.getChargingTime()); - // Charge should be refilling the battery, and so totalEnergy consumed - // should be reset to 0 (i.e., after this instruction we have - - } - else if (instruction instanceof SetConfigInstruction) { - SetConfigInstruction configI = (SetConfigInstruction) instruction; - m_config = configI.getConfig(); - } else { - // This instruction doesn't consume or produce energy - instEnergy = 0; - } - - totalEnergy += instEnergy; - i++; - } - - return totalEnergy; - } - - /** - * Finds the nearest (x, y) location to the source location that is a given distance away from the goal. - */ - private Pair getNearestTargetLocation(double sourceX, double sourceY, - double goalX, double goalY, double buffer) { - double lowerBoundX = goalX - buffer; - double upperBoundX = goalX + buffer; - double lowerBoundY = goalY - buffer; - double upperBoundY = goalY + buffer; - - List targetXs = new ArrayList<>(); - List targetYs = new ArrayList<>(); - targetXs.add(goalX); - targetYs.add(upperBoundY); - targetXs.add(upperBoundX); - targetYs.add(goalY); - targetXs.add(goalX); - targetYs.add(lowerBoundY); - targetXs.add(lowerBoundX); - targetYs.add(goalY); - - List manhattanDistances = new ArrayList<>(); - manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(0), targetXs.get(0))); - manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(1), targetXs.get(1))); - manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(2), targetXs.get(2))); - manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(3), targetXs.get(3))); - int minIndex = manhattanDistances.indexOf(Collections.min(manhattanDistances)); - double targetX = targetXs.get(minIndex); - double targetY = targetYs.get(minIndex); - Pair targetLocation = new Pair(targetX, targetY); - return targetLocation; - } - - private double getManhattanDistance(double sourceX, double sourceY, double targetX, double targetY) { - return Math.abs(sourceX - targetX) + Math.abs(sourceY - targetY); - } - - /** - * Calculates the energy consumption of MoveAbs(x, y, v, w) - */ - private double getMoveAbsHEnergyConsumption(MoveAbsHInstruction moveAbsH, double sourceX, double sourceY, double sourceW, String config) { - double targetX = moveAbsH.getTargetX(); - double targetY = moveAbsH.getTargetY(); - double targetW = moveAbsH.getTargetW(); - double moveSpeed = moveAbsH.getSpeed(); - double rotateSpeed = MapTranslator.ROBOT_ROTATIONAL_SPEED_VALUE; - - - double moveAbsHEnergy = getMovementEnergyConsumption (false, sourceX, sourceY, sourceW, targetX, targetY, - targetW, - moveSpeed, rotateSpeed, config); - return moveAbsHEnergy; - } - - /** - * Calculates the energy consumption of Forward(d, v) - */ - private double getForwardEnergyConsumption(ForwardInstruction forward, double sourceX, double sourceY, double sourceW, String config) { - double distance = forward.getDistance(); - double speed = forward.getSpeed(); - // Approximate target location - // Assume that the current location is close to the location where this Forward command was issued - // TODO: ensure this - double targetX = sourceX + distance * Math.cos(sourceW); - double targetY = sourceY + distance * Math.sin(sourceW); - double forwardEnergy = getMovementEnergyConsumption(false, sourceX, sourceY, sourceW, targetX, targetY, sourceW, - speed, 0, config); - return forwardEnergy; - } - - /** - * Calculates the energy consumption of a movement - */ - private double getMovementEnergyConsumption(boolean isManhattanDistance, - double sourceX, double sourceY, double sourceW, - double targetX, double targetY, double targetW, - double moveSpeed, double rotateSpeed, String config) { - String moveSpeedStr; - - if (moveSpeed == (double )MapTranslator.ROBOT_HALF_SPEED_VALUE) { - moveSpeedStr = MapTranslator.ROBOT_HALF_SPEED_CONST; - } else if (moveSpeed == (double )MapTranslator.ROBOT_FULL_SPEED_VALUE) { - moveSpeedStr = MapTranslator.ROBOT_FULL_SPEED_CONST; - } else { - moveSpeedStr = MapTranslator.ROBOT_HALF_SPEED_CONST; - } - - double distance; - if (isManhattanDistance) { - // Manhattan distance - distance = Math.abs(sourceX - targetX) + Math.abs(sourceY - targetY); - } else { - // Euclidean distance - distance = Math.sqrt(Math.pow(sourceX - targetX, 2) + Math.pow(sourceY - targetY, 2)); - } - - // Energy consumed by straight move - Configuration configuration = m_powerModel.getConfiguration(config); - double moveEnergy = - getEnergyConsumption(configuration, distance/configuration.getSpeed()); - - double instEnergy = moveEnergy; - - boolean rotating = Heading.convertFromRadians(sourceW) != Heading.convertFromRadians(targetW); - - // Energy consumed by rotation, if any - if (rotating) { - double abs = Math.abs(sourceW - targetW); - abs = (abs > Math.PI) ? 2 * Math.PI - abs : abs; - double rotateTime = abs / rotateSpeed; - double rotateEnergy = getEnergyConsumption(configuration, rotateTime); - instEnergy += rotateEnergy; - } - - return instEnergy; - } - +package org.sa.rainbow.brass.analyses.p2_cp1; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.sa.rainbow.brass.confsynthesis.Configuration; +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.brass.model.instructions.ChargeInstruction; +import org.sa.rainbow.brass.model.instructions.ForwardInstruction; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.instructions.SetConfigInstruction; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.MapTranslator; +import org.sa.rainbow.brass.model.mission.MissionState.Heading; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.core.util.Pair; + +public class EnergyConsumptionPredictor { + private static final int GOAL_RADIUS = 50; // centimeters //TODO + + private EnvMap m_envMap; + private MissionState m_missionState; + private String m_config; + + private SimpleConfigurationStore m_powerModel; + + public EnergyConsumptionPredictor(EnvMap e, MissionState m, SimpleConfigurationStore powerModel) { + m_envMap = e; + m_missionState = m; + m_powerModel = powerModel; + } + + public void setConfig(String config) { + m_config = config; + } + + // TODO check the signature + public double getEnergyConsumption(Configuration config, double time) { + if(config == null) { + throw new IllegalArgumentException("The configuration cannot be null"); + } + + double powerLoad = config.getEnergyDischargeRate(); + + if(powerLoad <= 0.0) { + throw new IllegalArgumentException("The power load has to be greater than 0"); + } + + if(time == 0.0) { + throw new IllegalArgumentException("There are no more tasks to do"); + } + + if(time < 0.0) { + throw new IllegalArgumentException("The time to complete tasks cannot be negative"); + } + + + return this.getEnergyConsumption(powerLoad, time); + } + + /** + * Get the energy consumed in a given time period. + * + * @param powerLoad + * @param time + * @return + */ + public double getEnergyConsumption(double powerLoad, double time) { + if(powerLoad <= 0.0) { + throw new IllegalArgumentException("The power load has to be greater than 0"); + } + + if(time == 0.0) { + throw new IllegalArgumentException("There are no more tasks to do"); + } + + if(time < 0.0) { + throw new IllegalArgumentException("The time to complete tasks cannot be negative"); + } + + double energy = powerLoad * time; + return energy; + } + + /** + * Check if the task can be completed based on the energyConsumption that will be consumed and the current energyConsumption. + * + * @param curEnergy + * @param energyConsumed + * @return + */ + public boolean canCompleteTask(double curEnergy, double energyConsumed) { + if(curEnergy < 0.0) { + throw new IllegalArgumentException("The current energy cannot be less than 0"); + } + + if(curEnergy == 0.0) { + throw new IllegalArgumentException("The battery is empty"); + } + + if(energyConsumed <= 0.0) { + throw new IllegalArgumentException("The energy consumed has to be greater than 0"); + } + + return curEnergy >= energyConsumed; + } + + /** + * Checks if the instructions can be completed with the remaining energy + */ + public double getPlanEnergyConsumption (IInstruction currentInstruction, List remainingInstructions, String tgtWP) { + double planEnergyConsumption = getExpectedIGEnergyConsumption(currentInstruction, remainingInstructions, tgtWP); + return planEnergyConsumption; + } + + private double getExpectedIGEnergyConsumption(IInstruction currentInstruction, List remainingInstructions, String tgtWP) { + double totalEnergy = 0; + + // Goal location + double goalX = m_envMap.getNodeX(m_missionState.getTargetWaypoint()); + double goalY = m_envMap.getNodeY(m_missionState.getTargetWaypoint()); + if (goalX == Double.NEGATIVE_INFINITY || goalY == Double.NEGATIVE_INFINITY) return 0; + + double sourceX = m_missionState.getCurrentPose().getX(); + double sourceY = m_missionState.getCurrentPose().getY(); + double sourceW = m_missionState.getCurrentPose().getRotation(); + + List allInstructions = new ArrayList<>(); + if (currentInstruction != null) allInstructions.add(currentInstruction); + allInstructions.addAll(remainingInstructions); + int i = 0; + for (IInstruction instruction : allInstructions) { + double instEnergy = 0; + + // Special case: for the last instruction, only calculate the energy required to get + // within a certain radius from the goal location + if (i == allInstructions.size() - 1 && instruction instanceof MoveAbsHInstruction && (((MoveAbsHInstruction )instruction).getTargetWaypoint().equals(tgtWP))) { + // For MoveAbsH, use the target location that is GOAL_RADIUS from the goal, and is nearest the source + Pair targetLocation = getNearestTargetLocation(sourceX, sourceY, goalX, goalY, GOAL_RADIUS); + double targetX = targetLocation.firstValue(); + double targetY = targetLocation.secondValue(); + + MoveAbsHInstruction moveAbsH = (MoveAbsHInstruction) instruction; + String newMoveAbsH = + MessageFormat.format ( + "MoveAbsH({0,number,##.##}, {1,number,##.##}, {2,number,##.##}, {3,number,##.###})", + targetX, targetY, moveAbsH.getSpeed (), moveAbsH.getTargetW ()); +// String.format("MoveAbsH(%d, %d, %d, %d)", targetX, targetY, moveAbsH.getSpeed(), moveAbsH.getTargetW()); + MoveAbsHInstruction moveAbsHCopy = + new MoveAbsHInstruction(moveAbsH.getInstructionLabel(), newMoveAbsH, moveAbsH.getNextInstructionLabel()); + instEnergy = getMoveAbsHEnergyConsumption(moveAbsHCopy, sourceX, sourceY, sourceW, m_config); + + } else if (i == allInstructions.size() - 1 && instruction instanceof ForwardInstruction) { + // For Forward, use the distance that is GOAL_RADIUS shorter than the original distance + ForwardInstruction forward = (ForwardInstruction) instruction; + String newForward = MessageFormat.format ("Forward({0,number,##.##}, {1,number,##.##})", + forward.getDistance () - GOAL_RADIUS, forward.getSpeed ()); +// String.format("Forward(%d, %d)", forward.getDistance() - GOAL_RADIUS, forward.getSpeed()); + ForwardInstruction forwardCopy = + new ForwardInstruction(forward.getInstructionLabel(), newForward, forward.getNextInstructionLabel()); + instEnergy = getForwardEnergyConsumption(forwardCopy, sourceX, sourceY, sourceW, m_config); + + } else if (instruction instanceof MoveAbsHInstruction) { + MoveAbsHInstruction moveAbsH = (MoveAbsHInstruction) instruction; + instEnergy = getMoveAbsHEnergyConsumption(moveAbsH, sourceX, sourceY, sourceW, m_config); + + // Update source pose for the next instruction + sourceX = moveAbsH.getTargetX();; + sourceY = moveAbsH.getTargetY(); + sourceW = moveAbsH.getTargetW(); + } else if (instruction instanceof ForwardInstruction) { + ForwardInstruction forward = (ForwardInstruction) instruction; + instEnergy = getForwardEnergyConsumption(forward, sourceX, sourceY, sourceW, m_config); + + // Update source pose for the next instruction + sourceX = sourceX + forward.getDistance() * Math.cos(sourceW);; + sourceY = sourceY + forward.getDistance() * Math.sin(sourceW); + } else if (instruction instanceof ChargeInstruction) { + // This should not happen because we should segment on Charges + // double energyGain = bp.batteryCharge(charge.getChargingTime()); + // Charge should be refilling the battery, and so totalEnergy consumed + // should be reset to 0 (i.e., after this instruction we have + + } + else if (instruction instanceof SetConfigInstruction) { + SetConfigInstruction configI = (SetConfigInstruction) instruction; + m_config = configI.getConfig(); + } else { + // This instruction doesn't consume or produce energy + instEnergy = 0; + } + + totalEnergy += instEnergy; + i++; + } + + return totalEnergy; + } + + /** + * Finds the nearest (x, y) location to the source location that is a given distance away from the goal. + */ + private Pair getNearestTargetLocation(double sourceX, double sourceY, + double goalX, double goalY, double buffer) { + double lowerBoundX = goalX - buffer; + double upperBoundX = goalX + buffer; + double lowerBoundY = goalY - buffer; + double upperBoundY = goalY + buffer; + + List targetXs = new ArrayList<>(); + List targetYs = new ArrayList<>(); + targetXs.add(goalX); + targetYs.add(upperBoundY); + targetXs.add(upperBoundX); + targetYs.add(goalY); + targetXs.add(goalX); + targetYs.add(lowerBoundY); + targetXs.add(lowerBoundX); + targetYs.add(goalY); + + List manhattanDistances = new ArrayList<>(); + manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(0), targetXs.get(0))); + manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(1), targetXs.get(1))); + manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(2), targetXs.get(2))); + manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(3), targetXs.get(3))); + int minIndex = manhattanDistances.indexOf(Collections.min(manhattanDistances)); + double targetX = targetXs.get(minIndex); + double targetY = targetYs.get(minIndex); + Pair targetLocation = new Pair(targetX, targetY); + return targetLocation; + } + + private double getManhattanDistance(double sourceX, double sourceY, double targetX, double targetY) { + return Math.abs(sourceX - targetX) + Math.abs(sourceY - targetY); + } + + /** + * Calculates the energy consumption of MoveAbs(x, y, v, w) + */ + private double getMoveAbsHEnergyConsumption(MoveAbsHInstruction moveAbsH, double sourceX, double sourceY, double sourceW, String config) { + double targetX = moveAbsH.getTargetX(); + double targetY = moveAbsH.getTargetY(); + double targetW = moveAbsH.getTargetW(); + double moveSpeed = moveAbsH.getSpeed(); + double rotateSpeed = MapTranslator.ROBOT_ROTATIONAL_SPEED_VALUE; + + + double moveAbsHEnergy = getMovementEnergyConsumption (false, sourceX, sourceY, sourceW, targetX, targetY, + targetW, + moveSpeed, rotateSpeed, config); + return moveAbsHEnergy; + } + + /** + * Calculates the energy consumption of Forward(d, v) + */ + private double getForwardEnergyConsumption(ForwardInstruction forward, double sourceX, double sourceY, double sourceW, String config) { + double distance = forward.getDistance(); + double speed = forward.getSpeed(); + // Approximate target location + // Assume that the current location is close to the location where this Forward command was issued + // TODO: ensure this + double targetX = sourceX + distance * Math.cos(sourceW); + double targetY = sourceY + distance * Math.sin(sourceW); + double forwardEnergy = getMovementEnergyConsumption(false, sourceX, sourceY, sourceW, targetX, targetY, sourceW, + speed, 0, config); + return forwardEnergy; + } + + /** + * Calculates the energy consumption of a movement + */ + private double getMovementEnergyConsumption(boolean isManhattanDistance, + double sourceX, double sourceY, double sourceW, + double targetX, double targetY, double targetW, + double moveSpeed, double rotateSpeed, String config) { + String moveSpeedStr; + + if (moveSpeed == (double )MapTranslator.ROBOT_HALF_SPEED_VALUE) { + moveSpeedStr = MapTranslator.ROBOT_HALF_SPEED_CONST; + } else if (moveSpeed == (double )MapTranslator.ROBOT_FULL_SPEED_VALUE) { + moveSpeedStr = MapTranslator.ROBOT_FULL_SPEED_CONST; + } else { + moveSpeedStr = MapTranslator.ROBOT_HALF_SPEED_CONST; + } + + double distance; + if (isManhattanDistance) { + // Manhattan distance + distance = Math.abs(sourceX - targetX) + Math.abs(sourceY - targetY); + } else { + // Euclidean distance + distance = Math.sqrt(Math.pow(sourceX - targetX, 2) + Math.pow(sourceY - targetY, 2)); + } + + // Energy consumed by straight move + Configuration configuration = m_powerModel.getConfiguration(config); + double moveEnergy = + getEnergyConsumption(configuration, distance/configuration.getSpeed()); + + double instEnergy = moveEnergy; + + boolean rotating = Heading.convertFromRadians(sourceW) != Heading.convertFromRadians(targetW); + + // Energy consumed by rotation, if any + if (rotating) { + double abs = Math.abs(sourceW - targetW); + abs = (abs > Math.PI) ? 2 * Math.PI - abs : abs; + double rotateTime = abs / rotateSpeed; + double rotateEnergy = getEnergyConsumption(configuration, rotateTime); + instEnergy += rotateEnergy; + } + + return instEnergy; + } + } \ No newline at end of file diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/P2CP1Analyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/P2CP1Analyzer.java index 446d3487c..be5e905d7 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/P2CP1Analyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp1/P2CP1Analyzer.java @@ -1,92 +1,92 @@ -package org.sa.rainbow.brass.analyses.p2_cp1; - -import org.sa.rainbow.brass.analyses.P2Analyzer; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.InsertNodeCmd; -import org.sa.rainbow.brass.model.p2_cp1.CP1ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; -import org.sa.rainbow.core.error.RainbowConnectionException; - -public abstract class P2CP1Analyzer extends P2Analyzer { - public P2CP1Analyzer(String name) { - super(name); - } - - private CP1ModelAccessor m_modelAccessor; - - @Override - public void initializeConnections() throws RainbowConnectionException { - super.initializeConnections(); - m_modelAccessor = new CP1ModelAccessor(m_modelsManagerPort); - } - - protected CP1ModelAccessor getModels () { - return m_modelAccessor; - } - - private MoveAbsHInstruction getPreviousMoveAbsH(MoveAbsHInstruction currentMoveAbsH) { - int j = Integer.valueOf (currentMoveAbsH.getInstructionLabel ()) - 1; - for (int i = j; i > 0; i--) { - String label = String.valueOf (i); - IInstruction instruction = getModels().getInstructionGraphModel().getModelInstance().getInstruction (label); - - if (instruction instanceof MoveAbsHInstruction) return (MoveAbsHInstruction )instruction; - } - - // No previous MoveAbsH instruction - return null; - } - - protected void insertNodeIntoMap(LocationRecording pose, IInstruction currentInst) { - if (currentInst instanceof MoveAbsHInstruction) { - MoveAbsHInstruction currentMoveAbsH = (MoveAbsHInstruction )currentInst; - MoveAbsHInstruction prevMoveAbsH = getPreviousMoveAbsH (currentMoveAbsH); - - double sourceX; - double sourceY; - double targetX = currentMoveAbsH.getTargetX (); - double targetY = currentMoveAbsH.getTargetY (); - - if (prevMoveAbsH != null) { - sourceX = prevMoveAbsH.getTargetX (); - sourceY = prevMoveAbsH.getTargetY (); - } - else { - // The current instruction is the first MoveAbsH instruction in IG - // Use the initial pose as the source pose - LocationRecording initialPose = getModels().getMissionStateModel().getModelInstance().getInitialPose (); - sourceX = initialPose.getX (); - sourceY = initialPose.getY (); - } - - // Find the corresponding environment map nodes of the source and target positions - // Node naming assumption: node's label is lX where X is the order in which the node is added - EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); - int numNodes = envMap.getNodeCount () + 1; - String n = "l" + numNodes; - String na = envMap.getNode (sourceX, sourceY).getLabel (); - String nb = envMap.getNode (targetX, targetY).getLabel (); - - // Update the environment map - String rx = Double.toString (pose.getX ()); - String ry = Double.toString (pose.getY ()); - - InsertNodeCmd insertNodeCmd = getModels().getEnvMapModel().getCommandFactory ().insertNodeCmd (n, na, nb, - rx, ry, "false"); - log ("Inserting node '" + n + "' at (" + rx + ", " + ry + ") between " + na + " and " - + nb); - - SetExecutionFailedCmd resetFailedCmd = getModels().getInstructionGraphModel().getCommandFactory () - .setExecutionFailedCmd ("false"); - - - // Send the commands -- different models, so can't bundle them - m_modelUSPort.updateModel (resetFailedCmd); - m_modelUSPort.updateModel (insertNodeCmd); - } - } - -} +package org.sa.rainbow.brass.analyses.p2_cp1; + +import org.sa.rainbow.brass.analyses.P2Analyzer; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.InsertNodeCmd; +import org.sa.rainbow.brass.model.p2_cp1.CP1ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; +import org.sa.rainbow.core.error.RainbowConnectionException; + +public abstract class P2CP1Analyzer extends P2Analyzer { + public P2CP1Analyzer(String name) { + super(name); + } + + private CP1ModelAccessor m_modelAccessor; + + @Override + public void initializeConnections() throws RainbowConnectionException { + super.initializeConnections(); + m_modelAccessor = new CP1ModelAccessor(m_modelsManagerPort); + } + + protected CP1ModelAccessor getModels () { + return m_modelAccessor; + } + + private MoveAbsHInstruction getPreviousMoveAbsH(MoveAbsHInstruction currentMoveAbsH) { + int j = Integer.valueOf (currentMoveAbsH.getInstructionLabel ()) - 1; + for (int i = j; i > 0; i--) { + String label = String.valueOf (i); + IInstruction instruction = getModels().getInstructionGraphModel().getModelInstance().getInstruction (label); + + if (instruction instanceof MoveAbsHInstruction) return (MoveAbsHInstruction )instruction; + } + + // No previous MoveAbsH instruction + return null; + } + + protected void insertNodeIntoMap(LocationRecording pose, IInstruction currentInst) { + if (currentInst instanceof MoveAbsHInstruction) { + MoveAbsHInstruction currentMoveAbsH = (MoveAbsHInstruction )currentInst; + MoveAbsHInstruction prevMoveAbsH = getPreviousMoveAbsH (currentMoveAbsH); + + double sourceX; + double sourceY; + double targetX = currentMoveAbsH.getTargetX (); + double targetY = currentMoveAbsH.getTargetY (); + + if (prevMoveAbsH != null) { + sourceX = prevMoveAbsH.getTargetX (); + sourceY = prevMoveAbsH.getTargetY (); + } + else { + // The current instruction is the first MoveAbsH instruction in IG + // Use the initial pose as the source pose + LocationRecording initialPose = getModels().getMissionStateModel().getModelInstance().getInitialPose (); + sourceX = initialPose.getX (); + sourceY = initialPose.getY (); + } + + // Find the corresponding environment map nodes of the source and target positions + // Node naming assumption: node's label is lX where X is the order in which the node is added + EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); + int numNodes = envMap.getNodeCount () + 1; + String n = "l" + numNodes; + String na = envMap.getNode (sourceX, sourceY).getLabel (); + String nb = envMap.getNode (targetX, targetY).getLabel (); + + // Update the environment map + String rx = Double.toString (pose.getX ()); + String ry = Double.toString (pose.getY ()); + + InsertNodeCmd insertNodeCmd = getModels().getEnvMapModel().getCommandFactory ().insertNodeCmd (n, na, nb, + rx, ry, "false"); + log ("Inserting node '" + n + "' at (" + rx + ", " + ry + ") between " + na + " and " + + nb); + + SetExecutionFailedCmd resetFailedCmd = getModels().getInstructionGraphModel().getCommandFactory () + .setExecutionFailedCmd ("false"); + + + // Send the commands -- different models, so can't bundle them + m_modelUSPort.updateModel (resetFailedCmd); + m_modelUSPort.updateModel (insertNodeCmd); + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/ConfigurationAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/ConfigurationAnalyzer.java index 6fd0da065..d14b70d76 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/ConfigurationAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/ConfigurationAnalyzer.java @@ -1,232 +1,233 @@ -package org.sa.rainbow.brass.analyses.p2_cp3; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import org.acmestudio.acme.core.exception.AcmeException; -import org.acmestudio.acme.element.IAcmeDesignRule; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.environment.error.AcmeError; -import org.acmestudio.acme.rule.node.feedback.ExpressionEvaluationError; -import org.acmestudio.acme.type.verification.NodeScopeLookup; -import org.acmestudio.acme.type.verification.RuleTypeChecker; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.KillNodesInstruction; -import org.sa.rainbow.brass.model.instructions.SetReconfiguringInstruction; -import org.sa.rainbow.brass.model.instructions.SetSensorInstruction; -import org.sa.rainbow.brass.model.instructions.StartNodesInstruction; -import org.sa.rainbow.brass.model.p2_cp3.acme.TurtlebotModelInstance; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RemoveModelProblemCmd; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.SetModelProblemCmd; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; -import org.sa.rainbow.core.IRainbowRunnable; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowConstants; - -public class ConfigurationAnalyzer extends P2CP3Analyzer { - - private String m_lastPrintedLog; - private boolean m_wasArchitectureOK = false; - private boolean m_wasConfigurationOK = false; - - private static final Map>INST_TO_ARCH_MAP = new HashMap<>(); - static { - INST_TO_ARCH_MAP.put("amcl", new HashSet(Arrays.asList("amcl"))); - INST_TO_ARCH_MAP.put("mrpt", new HashSet(Arrays.asList("mrpt"))); - INST_TO_ARCH_MAP.put("mapServer", new HashSet(Arrays.asList("map_server"))); - INST_TO_ARCH_MAP.put("mapServerObs", new HashSet(Arrays.asList("map_server_obs"))); - INST_TO_ARCH_MAP.put("aruco", new HashSet(Arrays.asList("aruco_marker_publisher_back", "marker_pose_publisher","aruco_marker_publisher_front"))); - INST_TO_ARCH_MAP.put("laserscanNodelet", new HashSet(Arrays.asList("laserScan_nodelet"))); - } - - public ConfigurationAnalyzer() { - super("TurtlebotConfigurationAnalyzer"); - String period = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); - if (period != null) { - setSleepTime(Long.parseLong(period)); - } else { - setSleepTime(IRainbowRunnable.LONG_SLEEP_TIME); - } - } - - @Override - protected void runAction() { - CP3RobotState rs = getModels().getRobotStateModel().getModelInstance(); - MissionState ms = getModels().getMissionStateModel().getModelInstance(); - TurtlebotModelInstance tb = getModels().getTurtlebotModel(); - InstructionGraphModelInstance ig = getModels().getInstructionGraphModel(); - if (getModels().getRainbowStateModel().getModelInstance().waitForIG()) { - m_wasArchitectureOK = true; - m_wasConfigurationOK = true; - return; - } - if (ig == null) return; - - EnumSet sensors = rs.getSensors(); - Collection components = tb.getActiveComponents(); - StringBuffer log = new StringBuffer("Components: "); - for (String c : components) { - log.append(c); - log.append(" "); - } - log.append("\nSensors: "); - for (Sensors s : sensors) { - log.append(s.name()); - } - if (m_lastPrintedLog == null || !m_lastPrintedLog.equals(log.toString())) { - m_lastPrintedLog = log.toString(); - log(m_lastPrintedLog); - } - - if (ms.isMissionStarted()) { - IInstruction currentInst = ig.getModelInstance().getCurrentInstruction(); - if (currentInst == null || currentInst instanceof SetSensorInstruction || currentInst instanceof StartNodesInstruction || currentInst instanceof KillNodesInstruction || currentInst instanceof SetReconfiguringInstruction) { - // Currrently executing a command to change the configuration, so let's abort this - return; - } - checkAcmeRules(tb); - checkConfigurationConsistentWithIG(ig, rs, tb); - } - } - - private void checkConfigurationConsistentWithIG(InstructionGraphModelInstance ig, CP3RobotState rs, TurtlebotModelInstance tb) { - Collection instructions = ig.getModelInstance().getInstructions(); - IInstruction currentInst = ig.getModelInstance().getCurrentInstruction(); - - Iterator instIt = instructions.iterator(); - boolean reachedCurrentInstruction = false; - EnumSet sensorsTurnedOn = EnumSet.noneOf(Sensors.class); - EnumSet sensorsTurnedOff = EnumSet.noneOf(Sensors.class); - Set nodesTurnedOn = new HashSet<> (); - Set nodesTurnedOff = new HashSet<> (); - while (instIt.hasNext() && !reachedCurrentInstruction) { - IInstruction inst = instIt.next(); - if (inst.getInstructionLabel().equals(currentInst.getInstructionLabel())) { - reachedCurrentInstruction = true; - continue; - } - if (inst instanceof SetSensorInstruction) { - SetSensorInstruction i = (SetSensorInstruction) inst; - if (i.getEnablement()) { - sensorsTurnedOn.add(i.getSensor()); - sensorsTurnedOff.remove(i.getSensor()); - } - } - else if (inst instanceof StartNodesInstruction) { - StartNodesInstruction i = (StartNodesInstruction) inst; - nodesTurnedOff.removeAll(INST_TO_ARCH_MAP.get(i.getNode())); - nodesTurnedOn.addAll(INST_TO_ARCH_MAP.get(i.getNode())); - } - else if (inst instanceof KillNodesInstruction) { - KillNodesInstruction i = (KillNodesInstruction) inst; - nodesTurnedOff.addAll(INST_TO_ARCH_MAP.get(i.getNode())); - nodesTurnedOn.removeAll(INST_TO_ARCH_MAP.get(i.getNode())); - } - } - boolean configurationOK = true; - EnumSet detectedSensors = rs.getSensors(); - Collection activeComponents = tb.getActiveComponents(); - - configurationOK = !Collections.disjoint(detectedSensors, EnumSet.of(Sensors.KINECT, Sensors.LIDAR, Sensors.CAMERA)) && detectedSensors.containsAll(sensorsTurnedOn) && - activeComponents.containsAll(nodesTurnedOn); - if (configurationOK) { - EnumSet clone = detectedSensors.clone(); - Set clonea = new HashSet<> (activeComponents); - clone.removeAll(sensorsTurnedOff); - clonea.removeAll(nodesTurnedOff); - // Are any turned off elements currently active - configurationOK = clone.size() == detectedSensors.size() && - clonea.size () == activeComponents.size(); - } - if (!configurationOK && m_wasConfigurationOK) { - m_wasConfigurationOK = false; - log("Configuration Analyzer reporting CONFIGURATION_ERROR"); - log("Sensors active: " + setToString(detectedSensors)); - log("Sensors in IG: " + setToString(sensorsTurnedOn) + " but not " + setToString(sensorsTurnedOff)); - log("Components active: " + setToString(activeComponents)); - log("Components in IG: " + setToString(nodesTurnedOn) + " but not " + setToString(nodesTurnedOff)); - SetModelProblemCmd cmd = getModels().getRainbowStateModel ().getCommandFactory ().setModelProblem(CP3ModelState.CONFIGURATION_ERROR); - m_modelUSPort.updateModel(cmd); - } - else if (configurationOK && !m_wasConfigurationOK) { - m_wasConfigurationOK = true; - log("Configuration Analyzer removing CONFIGURATION_ERROR"); - RemoveModelProblemCmd cmd = getModels().getRainbowStateModel().getCommandFactory ().removeModelProblem(CP3ModelState.CONFIGURATION_ERROR); - m_modelUSPort.updateModel(cmd); - } - - - } - - private String setToString(Collection components) { - StringBuffer sb = new StringBuffer("{"); - boolean first = true; - for (String s : components) { - if (!first) {first = false; sb.append(", ");} - sb.append(s); - } - sb.append("}"); - return sb.toString(); - } - - private String setToString(EnumSet sensors) { - StringBuffer sb = new StringBuffer("{"); - boolean first = true; - for (Sensors s : sensors) { - if (!first) {first = false; sb.append(", ");} - sb.append(s.name()); - } - sb.append("}"); - return sb.toString(); - } - - private void checkAcmeRules(TurtlebotModelInstance tb) { - IAcmeSystem tbs = tb.getModelInstance(); - IAcmeDesignRule localization = tbs.getDesignRule("atLeastOneActiveLocalization"); - IAcmeDesignRule navigation = tbs.getDesignRule("atLeastOneActiveNavigation"); - IAcmeDesignRule instructionGraph = tbs.getDesignRule("atLeastOneActiveIG"); - IAcmeDesignRule mapServer = tbs.getDesignRule("atLeastOneActiveMapServer"); - - IAcmeDesignRule[] rules = new IAcmeDesignRule[] { localization, navigation, instructionGraph, mapServer }; - - Stack errors = new Stack<>(); - boolean ok = true; - Set failingRules = new HashSet<>(); - for (IAcmeDesignRule r : rules) { - try { - boolean b = RuleTypeChecker.evaluateAsBoolean(tbs, r, r.getDesignRuleExpression(), errors, - new NodeScopeLookup()); - if (!b) failingRules.add(r.getName()); - ok &= b; - } catch (AcmeException e) { - errors.push(new ExpressionEvaluationError(tbs, r, r.getDesignRuleExpression(), e.getMessage())); - } - } - if (!ok && m_wasArchitectureOK) { - m_wasArchitectureOK = false; - log("ConfigurationAnalyzer reporting ARCHITECTURE_ERROR"); - log("The following rules failed: " + setToString(failingRules)); - SetModelProblemCmd cmd = getModels().getRainbowStateModel ().getCommandFactory ().setModelProblem(CP3ModelState.ARCHITECTURE_ERROR); - m_modelUSPort.updateModel(cmd); - } - else if (ok && !m_wasArchitectureOK) { - m_wasArchitectureOK = true; - log("ConfigurationAnalyzer removing ARCHITECTURE_ERROR"); - RemoveModelProblemCmd cmd = getModels().getRainbowStateModel().getCommandFactory ().removeModelProblem(CP3ModelState.ARCHITECTURE_ERROR); - m_modelUSPort.updateModel(cmd); - } - } - -} +package org.sa.rainbow.brass.analyses.p2_cp3; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.Stack; + +import org.acmestudio.acme.core.exception.AcmeException; +import org.acmestudio.acme.element.IAcmeDesignRule; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.environment.error.AcmeError; +import org.acmestudio.acme.rule.node.feedback.ExpressionEvaluationError; +import org.acmestudio.acme.type.verification.NodeScopeLookup; +import org.acmestudio.acme.type.verification.RuleTypeChecker; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.KillNodesInstruction; +import org.sa.rainbow.brass.model.instructions.SetReconfiguringInstruction; +import org.sa.rainbow.brass.model.instructions.SetSensorInstruction; +import org.sa.rainbow.brass.model.instructions.StartNodesInstruction; +import org.sa.rainbow.brass.model.p2_cp3.acme.TurtlebotModelInstance; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RemoveModelProblemCmd; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.SetModelProblemCmd; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.error.RainbowException; + +public class ConfigurationAnalyzer extends P2CP3Analyzer { + + private String m_lastPrintedLog; + private boolean m_wasArchitectureOK = false; + private boolean m_wasConfigurationOK = false; + + private static final Map>INST_TO_ARCH_MAP = new HashMap<>(); + static { + INST_TO_ARCH_MAP.put("amcl", new HashSet(Arrays.asList("amcl"))); + INST_TO_ARCH_MAP.put("mrpt", new HashSet(Arrays.asList("mrpt"))); + INST_TO_ARCH_MAP.put("mapServer", new HashSet(Arrays.asList("map_server"))); + INST_TO_ARCH_MAP.put("mapServerObs", new HashSet(Arrays.asList("map_server_obs"))); + INST_TO_ARCH_MAP.put("aruco", new HashSet(Arrays.asList("aruco_marker_publisher_back", "marker_pose_publisher","aruco_marker_publisher_front"))); + INST_TO_ARCH_MAP.put("laserscanNodelet", new HashSet(Arrays.asList("laserScan_nodelet"))); + } + + public ConfigurationAnalyzer() { + super("TurtlebotConfigurationAnalyzer"); + String period = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (period != null) { + setSleepTime(Long.parseLong(period)); + } else { + setSleepTime(IRainbowRunnable.LONG_SLEEP_TIME); + } + } + + @Override + protected void runAction() throws RainbowException { + CP3RobotState rs = getModels().getRobotStateModel().getModelInstance(); + MissionState ms = getModels().getMissionStateModel().getModelInstance(); + TurtlebotModelInstance tb = getModels().getTurtlebotModel(); + InstructionGraphModelInstance ig = getModels().getInstructionGraphModel(); + if (getModels().getRainbowStateModel().getModelInstance().waitForIG()) { + m_wasArchitectureOK = true; + m_wasConfigurationOK = true; + return; + } + if (ig == null) return; + + EnumSet sensors = rs.getSensors(); + Collection components = tb.getActiveComponents(); + StringBuffer log = new StringBuffer("Components: "); + for (String c : components) { + log.append(c); + log.append(" "); + } + log.append("\nSensors: "); + for (Sensors s : sensors) { + log.append(s.name()); + } + if (m_lastPrintedLog == null || !m_lastPrintedLog.equals(log.toString())) { + m_lastPrintedLog = log.toString(); + log(m_lastPrintedLog); + } + + if (ms.isMissionStarted()) { + IInstruction currentInst = ig.getModelInstance().getCurrentInstruction(); + if (currentInst == null || currentInst instanceof SetSensorInstruction || currentInst instanceof StartNodesInstruction || currentInst instanceof KillNodesInstruction || currentInst instanceof SetReconfiguringInstruction) { + // Currrently executing a command to change the configuration, so let's abort this + return; + } + checkAcmeRules(tb); + checkConfigurationConsistentWithIG(ig, rs, tb); + } + } + + private void checkConfigurationConsistentWithIG(InstructionGraphModelInstance ig, CP3RobotState rs, TurtlebotModelInstance tb) throws RainbowException { + Collection instructions = ig.getModelInstance().getInstructions(); + IInstruction currentInst = ig.getModelInstance().getCurrentInstruction(); + + Iterator instIt = instructions.iterator(); + boolean reachedCurrentInstruction = false; + EnumSet sensorsTurnedOn = EnumSet.noneOf(Sensors.class); + EnumSet sensorsTurnedOff = EnumSet.noneOf(Sensors.class); + Set nodesTurnedOn = new HashSet<> (); + Set nodesTurnedOff = new HashSet<> (); + while (instIt.hasNext() && !reachedCurrentInstruction) { + IInstruction inst = instIt.next(); + if (inst.getInstructionLabel().equals(currentInst.getInstructionLabel())) { + reachedCurrentInstruction = true; + continue; + } + if (inst instanceof SetSensorInstruction) { + SetSensorInstruction i = (SetSensorInstruction) inst; + if (i.getEnablement()) { + sensorsTurnedOn.add(i.getSensor()); + sensorsTurnedOff.remove(i.getSensor()); + } + } + else if (inst instanceof StartNodesInstruction) { + StartNodesInstruction i = (StartNodesInstruction) inst; + nodesTurnedOff.removeAll(INST_TO_ARCH_MAP.get(i.getNode())); + nodesTurnedOn.addAll(INST_TO_ARCH_MAP.get(i.getNode())); + } + else if (inst instanceof KillNodesInstruction) { + KillNodesInstruction i = (KillNodesInstruction) inst; + nodesTurnedOff.addAll(INST_TO_ARCH_MAP.get(i.getNode())); + nodesTurnedOn.removeAll(INST_TO_ARCH_MAP.get(i.getNode())); + } + } + boolean configurationOK = true; + EnumSet detectedSensors = rs.getSensors(); + Collection activeComponents = tb.getActiveComponents(); + + configurationOK = !Collections.disjoint(detectedSensors, EnumSet.of(Sensors.KINECT, Sensors.LIDAR, Sensors.CAMERA)) && detectedSensors.containsAll(sensorsTurnedOn) && + activeComponents.containsAll(nodesTurnedOn); + if (configurationOK) { + EnumSet clone = detectedSensors.clone(); + Set clonea = new HashSet<> (activeComponents); + clone.removeAll(sensorsTurnedOff); + clonea.removeAll(nodesTurnedOff); + // Are any turned off elements currently active + configurationOK = clone.size() == detectedSensors.size() && + clonea.size () == activeComponents.size(); + } + if (!configurationOK && m_wasConfigurationOK) { + m_wasConfigurationOK = false; + log("Configuration Analyzer reporting CONFIGURATION_ERROR"); + log("Sensors active: " + setToString(detectedSensors)); + log("Sensors in IG: " + setToString(sensorsTurnedOn) + " but not " + setToString(sensorsTurnedOff)); + log("Components active: " + setToString(activeComponents)); + log("Components in IG: " + setToString(nodesTurnedOn) + " but not " + setToString(nodesTurnedOff)); + SetModelProblemCmd cmd = getModels().getRainbowStateModel ().getCommandFactory ().setModelProblem(CP3ModelState.CONFIGURATION_ERROR); + m_modelUSPort.updateModel(cmd); + } + else if (configurationOK && !m_wasConfigurationOK) { + m_wasConfigurationOK = true; + log("Configuration Analyzer removing CONFIGURATION_ERROR"); + RemoveModelProblemCmd cmd = getModels().getRainbowStateModel().getCommandFactory ().removeModelProblem(CP3ModelState.CONFIGURATION_ERROR); + m_modelUSPort.updateModel(cmd); + } + + + } + + private String setToString(Collection components) { + StringBuffer sb = new StringBuffer("{"); + boolean first = true; + for (String s : components) { + if (!first) {first = false; sb.append(", ");} + sb.append(s); + } + sb.append("}"); + return sb.toString(); + } + + private String setToString(EnumSet sensors) { + StringBuffer sb = new StringBuffer("{"); + boolean first = true; + for (Sensors s : sensors) { + if (!first) {first = false; sb.append(", ");} + sb.append(s.name()); + } + sb.append("}"); + return sb.toString(); + } + + private void checkAcmeRules(TurtlebotModelInstance tb) throws RainbowException { + IAcmeSystem tbs = tb.getModelInstance(); + IAcmeDesignRule localization = tbs.getDesignRule("atLeastOneActiveLocalization"); + IAcmeDesignRule navigation = tbs.getDesignRule("atLeastOneActiveNavigation"); + IAcmeDesignRule instructionGraph = tbs.getDesignRule("atLeastOneActiveIG"); + IAcmeDesignRule mapServer = tbs.getDesignRule("atLeastOneActiveMapServer"); + + IAcmeDesignRule[] rules = new IAcmeDesignRule[] { localization, navigation, instructionGraph, mapServer }; + + Stack errors = new Stack<>(); + boolean ok = true; + Set failingRules = new HashSet<>(); + for (IAcmeDesignRule r : rules) { + try { + boolean b = RuleTypeChecker.evaluateAsBoolean(tbs, r, r.getDesignRuleExpression(), errors, + new NodeScopeLookup()); + if (!b) failingRules.add(r.getName()); + ok &= b; + } catch (AcmeException e) { + errors.push(new ExpressionEvaluationError(tbs, r, r.getDesignRuleExpression(), e.getMessage())); + } + } + if (!ok && m_wasArchitectureOK) { + m_wasArchitectureOK = false; + log("ConfigurationAnalyzer reporting ARCHITECTURE_ERROR"); + log("The following rules failed: " + setToString(failingRules)); + SetModelProblemCmd cmd = getModels().getRainbowStateModel ().getCommandFactory ().setModelProblem(CP3ModelState.ARCHITECTURE_ERROR); + m_modelUSPort.updateModel(cmd); + } + else if (ok && !m_wasArchitectureOK) { + m_wasArchitectureOK = true; + log("ConfigurationAnalyzer removing ARCHITECTURE_ERROR"); + RemoveModelProblemCmd cmd = getModels().getRainbowStateModel().getCommandFactory ().removeModelProblem(CP3ModelState.ARCHITECTURE_ERROR); + m_modelUSPort.updateModel(cmd); + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/DarknessAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/DarknessAnalyzer.java index f5775c87c..d2390b62e 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/DarknessAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/DarknessAnalyzer.java @@ -1,142 +1,143 @@ -package org.sa.rainbow.brass.analyses.p2_cp3; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; - -import org.sa.rainbow.brass.confsynthesis.ConfigurationSynthesizer; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.EnvMapArc; -import org.sa.rainbow.brass.model.map.EnvMapNode; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RemoveModelProblemCmd; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.SetModelProblemCmd; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState; -import org.sa.rainbow.core.IRainbowEnvironment; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; - -public class DarknessAnalyzer extends P2CP3Analyzer implements IRainbowModelChangeCallback { - - private static final double ILLUMINATION_THRESHOLD = 80; - private boolean m_darkBefore = false; - - public DarknessAnalyzer() { - super("Darkness"); - - } - - public DarknessAnalyzer(IRainbowEnvironment env) { - super("Darkness",env); - } - - protected static class LightingData { - boolean m_darkProcessed = false; - boolean m_badLightProcessed = false; - double m_badLightSuccessRate = 0.0; - double m_litSuccessRate = 0.0; - } - - Map> m_lightingData = new HashMap<>(); - - @Override - protected void runAction() { - CP3RobotState rs = getModels().getRobotStateModel().getModelInstance(); - try { - double ill = rs.getIllumination(); - if (ill < ILLUMINATION_THRESHOLD * 2) { // Adjust success rate for light sensitive configs - // TODO: Turn this into commands rather than direct manipulation of the model - LocationRecording currentPose = getModels().getMissionStateModel().getModelInstance().getCurrentPose(); - EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); - EnvMapNode node = envMap.getNode(currentPose.getX(), currentPose.getY(), 0.5); - if (node != null) { - String label = node.getLabel(); - LinkedList neighbors = envMap.getNeighbors(label); - for (String t : neighbors) { - EnvMapArc arc = envMap.getArc(label, t); - if (arc != null) { - processDarkData(ill, arc); - } - arc = envMap.getArc(t, label); - if (arc != null) { - processDarkData(ill, arc); - } - } - } else { - EnvMapArc arc = envMap.getArc(currentPose.getX(), currentPose.getY()); - if (arc != null) { - processDarkData(ill, arc); - } - arc = envMap.getArc(arc.m_target, arc.m_source); - if (arc != null) { - processDarkData(ill, arc); - } - } - } - if (ill < ILLUMINATION_THRESHOLD - && getModels().getTurtlebotModel().getActiveComponents().contains("marker_pose_publisher") - && !m_darkBefore) { - log("DarknessAnalyzer reporting TOO_DARK"); - SetModelProblemCmd cmd = getModels().getRainbowStateModel().getCommandFactory() - .setModelProblem(CP3ModelState.TOO_DARK); - m_darkBefore = true; - m_modelUSPort.updateModel(cmd); - } else if (m_darkBefore && (ill >= ILLUMINATION_THRESHOLD - || !getModels().getTurtlebotModel().getActiveComponents().contains("marker_pose_publisher"))) { - log("DarknessAnalyzer removing TOO_DARK"); - RemoveModelProblemCmd cmd = getModels().getRainbowStateModel().getCommandFactory() - .removeModelProblem(CP3ModelState.TOO_DARK); - m_darkBefore = false; - m_modelUSPort.updateModel(cmd); - } - - } catch (IllegalStateException e) { - - } - } - - void processDarkData(double ill, EnvMapArc arc) { - Map ldm = m_lightingData.get(arc); - if (ldm == null) { - ldm = new HashMap(); - m_lightingData.put(arc, ldm); - } - double factor = ill < ILLUMINATION_THRESHOLD ? 0.5 : 0.75; - for (String c : ConfigurationSynthesizer.getLightSensitiveConfigs()) { - LightingData ld = ldm.get(c); - if (ld == null) { - ld = new LightingData(); - ldm.put(c, ld); - } - Double osr = arc.getSuccessRate(c); - - if ((factor == 0.5 && !ld.m_badLightProcessed) || (factor == 0.75 && !ld.m_badLightProcessed)) { - ld.m_litSuccessRate = osr; - ld.m_badLightProcessed = true; - ld.m_darkProcessed = factor == 0.5; - arc.addSuccessRate(c, osr * factor); - } - - else if (factor == 0.5 && !ld.m_darkProcessed) { - ld.m_badLightSuccessRate = osr; - ld.m_darkProcessed = true; - arc.addSuccessRate(c, osr * factor); - } - } - } - - @Override - public RainbowComponentT getComponentType() { - return RainbowComponentT.ANALYSIS; - } - - @Override - public void onEvent(ModelReference reference, IRainbowMessage message) { - // TODO Auto-generated method stub - - } - -} +package org.sa.rainbow.brass.analyses.p2_cp3; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; + +import org.sa.rainbow.brass.confsynthesis.ConfigurationSynthesizer; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.EnvMapArc; +import org.sa.rainbow.brass.model.map.EnvMapNode; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RemoveModelProblemCmd; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.SetModelProblemCmd; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState; +import org.sa.rainbow.core.IRainbowEnvironment; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; + +public class DarknessAnalyzer extends P2CP3Analyzer implements IRainbowModelChangeCallback { + + private static final double ILLUMINATION_THRESHOLD = 80; + private boolean m_darkBefore = false; + + public DarknessAnalyzer() { + super("Darkness"); + + } + + public DarknessAnalyzer(IRainbowEnvironment env) { + super("Darkness",env); + } + + protected static class LightingData { + boolean m_darkProcessed = false; + boolean m_badLightProcessed = false; + double m_badLightSuccessRate = 0.0; + double m_litSuccessRate = 0.0; + } + + Map> m_lightingData = new HashMap<>(); + + @Override + protected void runAction() throws RainbowException { + CP3RobotState rs = getModels().getRobotStateModel().getModelInstance(); + try { + double ill = rs.getIllumination(); + if (ill < ILLUMINATION_THRESHOLD * 2) { // Adjust success rate for light sensitive configs + // TODO: Turn this into commands rather than direct manipulation of the model + LocationRecording currentPose = getModels().getMissionStateModel().getModelInstance().getCurrentPose(); + EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); + EnvMapNode node = envMap.getNode(currentPose.getX(), currentPose.getY(), 0.5); + if (node != null) { + String label = node.getLabel(); + LinkedList neighbors = envMap.getNeighbors(label); + for (String t : neighbors) { + EnvMapArc arc = envMap.getArc(label, t); + if (arc != null) { + processDarkData(ill, arc); + } + arc = envMap.getArc(t, label); + if (arc != null) { + processDarkData(ill, arc); + } + } + } else { + EnvMapArc arc = envMap.getArc(currentPose.getX(), currentPose.getY()); + if (arc != null) { + processDarkData(ill, arc); + } + arc = envMap.getArc(arc.m_target, arc.m_source); + if (arc != null) { + processDarkData(ill, arc); + } + } + } + if (ill < ILLUMINATION_THRESHOLD + && getModels().getTurtlebotModel().getActiveComponents().contains("marker_pose_publisher") + && !m_darkBefore) { + log("DarknessAnalyzer reporting TOO_DARK"); + SetModelProblemCmd cmd = getModels().getRainbowStateModel().getCommandFactory() + .setModelProblem(CP3ModelState.TOO_DARK); + m_darkBefore = true; + m_modelUSPort.updateModel(cmd); + } else if (m_darkBefore && (ill >= ILLUMINATION_THRESHOLD + || !getModels().getTurtlebotModel().getActiveComponents().contains("marker_pose_publisher"))) { + log("DarknessAnalyzer removing TOO_DARK"); + RemoveModelProblemCmd cmd = getModels().getRainbowStateModel().getCommandFactory() + .removeModelProblem(CP3ModelState.TOO_DARK); + m_darkBefore = false; + m_modelUSPort.updateModel(cmd); + } + + } catch (IllegalStateException e) { + + } + } + + void processDarkData(double ill, EnvMapArc arc) { + Map ldm = m_lightingData.get(arc); + if (ldm == null) { + ldm = new HashMap(); + m_lightingData.put(arc, ldm); + } + double factor = ill < ILLUMINATION_THRESHOLD ? 0.5 : 0.75; + for (String c : ConfigurationSynthesizer.getLightSensitiveConfigs()) { + LightingData ld = ldm.get(c); + if (ld == null) { + ld = new LightingData(); + ldm.put(c, ld); + } + Double osr = arc.getSuccessRate(c); + + if ((factor == 0.5 && !ld.m_badLightProcessed) || (factor == 0.75 && !ld.m_badLightProcessed)) { + ld.m_litSuccessRate = osr; + ld.m_badLightProcessed = true; + ld.m_darkProcessed = factor == 0.5; + arc.addSuccessRate(c, osr * factor); + } + + else if (factor == 0.5 && !ld.m_darkProcessed) { + ld.m_badLightSuccessRate = osr; + ld.m_darkProcessed = true; + arc.addSuccessRate(c, osr * factor); + } + } + } + + @Override + public RainbowComponentT getComponentType() { + return RainbowComponentT.ANALYSIS; + } + + @Override + public void onEvent(ModelReference reference, IRainbowMessage message) { + // TODO Auto-generated method stub + + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/MissionAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/MissionAnalyzer.java index eb11f3a36..b46f9e889 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/MissionAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/MissionAnalyzer.java @@ -1,56 +1,57 @@ -package org.sa.rainbow.brass.analyses.p2_cp3; - -import org.sa.rainbow.brass.das.BRASSHttpConnector; -import org.sa.rainbow.brass.das.IBRASSConnector.Phases; -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RemoveModelProblemCmd; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.SetModelProblemCmd; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; - -public class MissionAnalyzer extends P2CP3Analyzer { - - private boolean m_reportedReady = false; - private boolean m_wasOK; - - public MissionAnalyzer() { - super("Mission evaluator"); - } - - @Override - protected void runAction() { - InstructionGraphModelInstance ig = getModels().getInstructionGraphModel(); - - MissionState ms = getModels().getMissionStateModel().getModelInstance(); - - if (!m_reportedReady && ms.getInitialPose() != null) { - m_reportedReady = true; - BRASSHttpConnector.instance(Phases.Phase2).setClock(getModels().getMissionStateModel().getModelInstance()); - BRASSHttpConnector.instance(Phases.Phase2).reportReady(true); - m_wasOK = true; - } - - if (ms.isMissionStarted() && ms.getInitialPose() != null) { - - boolean currentOK = ig.getModelInstance().getCurrentOK(); - - if (!currentOK && m_wasOK) { - m_wasOK = false; - log("MissionAnalyser reporting INSTRUCTION_GRAPH_FAILED"); - SetModelProblemCmd cmd = getModels().getRainbowStateModel ().getCommandFactory ().setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); - m_modelUSPort.updateModel(cmd); - } - else if (currentOK && !m_wasOK) { - m_wasOK = true; - log("MissionAnalyzer removing INSTRUCTION_GRAPH_FAILED"); - RemoveModelProblemCmd cmd = getModels().getRainbowStateModel().getCommandFactory ().removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); - m_modelUSPort.updateModel(cmd); - } - else if (ig.getModelInstance().getInstructionGraphState() == IGExecutionStateT.FINISHED_SUCCESS) { - log("Reporting that we are done"); - BRASSHttpConnector.instance(Phases.Phase2).reportDone(false, "Finished the IG"); - } - } - } -} +package org.sa.rainbow.brass.analyses.p2_cp3; + +import org.sa.rainbow.brass.das.BRASSHttpConnector; +import org.sa.rainbow.brass.das.IBRASSConnector.Phases; +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RemoveModelProblemCmd; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.SetModelProblemCmd; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; + +public class MissionAnalyzer extends P2CP3Analyzer { + + private boolean m_reportedReady = false; + private boolean m_wasOK; + + public MissionAnalyzer() { + super("Mission evaluator"); + } + + @Override + protected void runAction() throws RainbowException { + InstructionGraphModelInstance ig = getModels().getInstructionGraphModel(); + + MissionState ms = getModels().getMissionStateModel().getModelInstance(); + + if (!m_reportedReady && ms.getInitialPose() != null) { + m_reportedReady = true; + BRASSHttpConnector.instance(Phases.Phase2).setClock(getModels().getMissionStateModel().getModelInstance()); + BRASSHttpConnector.instance(Phases.Phase2).reportReady(true); + m_wasOK = true; + } + + if (ms.isMissionStarted() && ms.getInitialPose() != null) { + + boolean currentOK = ig.getModelInstance().getCurrentOK(); + + if (!currentOK && m_wasOK) { + m_wasOK = false; + log("MissionAnalyser reporting INSTRUCTION_GRAPH_FAILED"); + SetModelProblemCmd cmd = getModels().getRainbowStateModel ().getCommandFactory ().setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); + m_modelUSPort.updateModel(cmd); + } + else if (currentOK && !m_wasOK) { + m_wasOK = true; + log("MissionAnalyzer removing INSTRUCTION_GRAPH_FAILED"); + RemoveModelProblemCmd cmd = getModels().getRainbowStateModel().getCommandFactory ().removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); + m_modelUSPort.updateModel(cmd); + } + else if (ig.getModelInstance().getInstructionGraphState() == IGExecutionStateT.FINISHED_SUCCESS) { + log("Reporting that we are done"); + BRASSHttpConnector.instance(Phases.Phase2).reportDone(false, "Finished the IG"); + } + } + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/P2CP3Analyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/P2CP3Analyzer.java index 385ad37d4..e399d8e2d 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/P2CP3Analyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/P2CP3Analyzer.java @@ -1,44 +1,44 @@ -package org.sa.rainbow.brass.analyses.p2_cp3; - -import org.sa.rainbow.brass.analyses.P2Analyzer; -import org.sa.rainbow.brass.model.P2ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.CP3ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.ICP3ModelAccessor; -import org.sa.rainbow.core.IRainbowEnvironment; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; -import org.sa.rainbow.core.ports.IModelUSBusPort; -import org.sa.rainbow.core.ports.IModelsManagerPort; - -public abstract class P2CP3Analyzer extends P2Analyzer { - - - private ICP3ModelAccessor m_modelAccessor; - - public P2CP3Analyzer(String name) { - super(name); - - } - - public P2CP3Analyzer(String name, IRainbowEnvironment env) { - super(name, env); - } - - - @Override - public void initializeConnections() throws RainbowConnectionException { - super.initializeConnections(); - m_modelAccessor = new CP3ModelAccessor(m_modelsManagerPort); - } - - protected ICP3ModelAccessor getModels () { - return m_modelAccessor; - } - - - - - - - -} +package org.sa.rainbow.brass.analyses.p2_cp3; + +import org.sa.rainbow.brass.analyses.P2Analyzer; +import org.sa.rainbow.brass.model.P2ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.CP3ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.ICP3ModelAccessor; +import org.sa.rainbow.core.IRainbowEnvironment; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelUSBusPort; +import org.sa.rainbow.core.ports.IModelsManagerPort; + +public abstract class P2CP3Analyzer extends P2Analyzer { + + + private ICP3ModelAccessor m_modelAccessor; + + public P2CP3Analyzer(String name) { + super(name); + + } + + public P2CP3Analyzer(String name, IRainbowEnvironment env) { + super(name, env); + } + + + @Override + public void initializeConnections() throws RainbowConnectionException { + super.initializeConnections(); + m_modelAccessor = new CP3ModelAccessor(m_modelsManagerPort); + } + + protected ICP3ModelAccessor getModels () { + return m_modelAccessor; + } + + + + + + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/UpdateClockModel.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/UpdateClockModel.java index ac8abec7e..e147b9df9 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/UpdateClockModel.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/analyses/p2_cp3/UpdateClockModel.java @@ -1,94 +1,94 @@ -package org.sa.rainbow.brass.analyses.p2_cp3; - -import java.util.Collection; -import java.util.HashSet; - -import org.sa.rainbow.brass.model.p2_cp3.clock.Clock; -import org.sa.rainbow.brass.model.p2_cp3.clock.ClockModelInstance; -import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel; -import org.sa.rainbow.core.AbstractRainbowRunnable; -import org.sa.rainbow.core.IRainbowRunnable; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.RainbowConstants; -import org.sa.rainbow.core.analysis.IRainbowAnalysis; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.ports.IModelsManagerPort; -import org.sa.rainbow.core.ports.IRainbowReportingPort; -import org.sa.rainbow.core.ports.RainbowPortFactory; - -/** This analyzer finds all models in the models manager that are clocked, and adds the - * reference to the clock model. This needs to be run in the same VM as the Rainbow Master - * because it cheats somewhat in setting up the clock (i.e., it doesn't use operations) - * - * @author schmerl - * - */ -public class UpdateClockModel extends AbstractRainbowRunnable implements IRainbowAnalysis { - - private IModelsManagerPort m_modelsManagerPort; - private ClockModelInstance m_clockModel; - private Collection m_clockedModels = new HashSet<> (); - - public UpdateClockModel() { - super("Add Clock to Models"); - String period = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); - if (period != null) { - setSleepTime(Long.parseLong(period)); - } else { - setSleepTime(IRainbowRunnable.LONG_SLEEP_TIME); - } - } - - @Override - public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { - super.initialize(port); - m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort(); - - } - @Override - public void dispose() { - } - - @Override - public void setProperty(String key, String value) { - } - - @Override - public String getProperty(String key) { - return null; - } - - @Override - protected void log(String txt) { - } - - @Override - protected void runAction() { - if (m_clockModel == null) { - m_clockModel = (ClockModelInstance )m_modelsManagerPort.getModelInstance(new ModelReference("Clock","Clock")); - } - if (m_clockModel != null) { - Collection types = Rainbow.instance().getRainbowMaster().modelsManager().getRegisteredModelTypes(); - for (String t : types) { - Collection> modelInstances = Rainbow.instance().getRainbowMaster().modelsManager().getModelsOfType(t); - for (IModelInstance mi : modelInstances) { - if (mi.getModelInstance() instanceof ClockedModel && !m_clockedModels.contains(mi.getModelName() + ":" + mi.getModelType())) { - log("Adding clock to " + mi.getModelName()); - ((ClockedModel )mi.getModelInstance()).setClock(m_clockModel.getModelInstance()); - m_clockedModels.add (mi.getModelInstance() + ":" + mi.getModelType()); - } - } - - } - } - } - - @Override - public RainbowComponentT getComponentType() { - return RainbowComponentT.ANALYSIS; - } - -} +package org.sa.rainbow.brass.analyses.p2_cp3; + +import java.util.Collection; +import java.util.HashSet; + +import org.sa.rainbow.brass.model.p2_cp3.clock.Clock; +import org.sa.rainbow.brass.model.p2_cp3.clock.ClockModelInstance; +import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel; +import org.sa.rainbow.core.AbstractRainbowRunnable; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.analysis.IRainbowAnalysis; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; + +/** This analyzer finds all models in the models manager that are clocked, and adds the + * reference to the clock model. This needs to be run in the same VM as the Rainbow Master + * because it cheats somewhat in setting up the clock (i.e., it doesn't use operations) + * + * @author schmerl + * + */ +public class UpdateClockModel extends AbstractRainbowRunnable implements IRainbowAnalysis { + + private IModelsManagerPort m_modelsManagerPort; + private ClockModelInstance m_clockModel; + private Collection m_clockedModels = new HashSet<> (); + + public UpdateClockModel() { + super("Add Clock to Models"); + String period = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (period != null) { + setSleepTime(Long.parseLong(period)); + } else { + setSleepTime(IRainbowRunnable.LONG_SLEEP_TIME); + } + } + + @Override + public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize(port); + m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort(); + + } + @Override + public void dispose() { + } + + @Override + public void setProperty(String key, String value) { + } + + @Override + public String getProperty(String key) { + return null; + } + + @Override + protected void log(String txt) { + } + + @Override + protected void runAction() { + if (m_clockModel == null) { + m_clockModel = (ClockModelInstance )m_modelsManagerPort.getModelInstance(new ModelReference("Clock","Clock")); + } + if (m_clockModel != null) { + Collection types = Rainbow.instance().getRainbowMaster().modelsManager().getRegisteredModelTypes(); + for (String t : types) { + Collection> modelInstances = Rainbow.instance().getRainbowMaster().modelsManager().getModelsOfType(t); + for (IModelInstance mi : modelInstances) { + if (mi.getModelInstance() instanceof ClockedModel && !m_clockedModels.contains(mi.getModelName() + ":" + mi.getModelType())) { + log("Adding clock to " + mi.getModelName()); + ((ClockedModel )mi.getModelInstance()).setClock(m_clockModel.getModelInstance()); + m_clockedModels.add (mi.getModelInstance() + ":" + mi.getModelType()); + } + } + + } + } + } + + @Override + public RainbowComponentT getComponentType() { + return RainbowComponentT.ANALYSIS; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ConfigurationSynthesizer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ConfigurationSynthesizer.java index 4c5c0d40e..8a657b9e9 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ConfigurationSynthesizer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ConfigurationSynthesizer.java @@ -1,574 +1,574 @@ -package org.sa.rainbow.brass.confsynthesis; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Properties; -import java.util.Set; - -import org.sa.rainbow.brass.adaptation.PrismConnectorAPI; -import org.sa.rainbow.brass.adaptation.PrismPolicy; -import org.sa.rainbow.brass.confsynthesis.AlloySolution.AlloySolutionNode; -import org.sa.rainbow.core.error.RainbowException; - -import edu.mit.csail.sdg.alloy4.Err; - -public class ConfigurationSynthesizer implements ConfigurationProvider { - - public HashMap m_configurationPredicates = new HashMap(); - public HashMap m_configurations = new HashMap(); - public HashMap m_configuration_objects = new HashMap(); - public LinkedList m_allinstances = new LinkedList(); - public HashMap> m_reconfigurations = new HashMap>(); - public HashMap m_reconfiguration_costs = new HashMap(); - public static final HashMap m_component_modes; - public static DetailedConfigurationBatteryModel m_battery_model; - public static final Double RECONF_STEP_TIME_COST = 5.0; - static { - m_component_modes = new HashMap(); - m_component_modes.put("DISABLED", "0"); - m_component_modes.put("ENABLED", "1"); - m_component_modes.put("OFFLINE", "2"); - } - - private static final HashMap m_component_actions; - static { - m_component_actions = new HashMap(); - m_component_actions.put("enable", new String[] { "DISABLED", "ENABLED" }); - m_component_actions.put("disable", new String[] { "ENABLED", "DISABLED" }); -// m_component_actions.put("crash", new String[] { "ENABLED", "OFFLINE" }); - } - - private static final HashMap m_configuration_dictionary; - static { - m_configuration_dictionary = new HashMap(); - restoreAllConfigs(); - } - - private HashMap m_constant_definitions = new HashMap(); - - public String m_res = "result"; - public String m_myConstraintModel; - public String m_myBaseModel; - public String m_myModel; - public String m_myPolicy; - public String m_myProps; - - public static PrismConnectorAPI m_pc; - - public ConfigurationSynthesizer() { - this(PropertiesConfigurationSynthesizer.DEFAULT); - } - - protected static final Set LIGHT_SENSITIVE_CONFIGS = new HashSet<>(Arrays.asList("sol_4", "sol_12", "sol_8")); - - public static void restoreAllConfigs() { - m_configuration_dictionary.put("sol_0", "amcl-kinect-35"); - m_configuration_dictionary.put("sol_1", "aruco-camera-headlamp-24"); - m_configuration_dictionary.put("sol_2", "amcl-kinect-68"); - m_configuration_dictionary.put("sol_3", "mrpt-lidar-35"); - m_configuration_dictionary.put("sol_4", "aruco-camera-35"); - m_configuration_dictionary.put("sol_5", "aruco-camera-headlamp-35"); - m_configuration_dictionary.put("sol_6", "amcl-lidar-35"); - m_configuration_dictionary.put("sol_7", "mrpt-kinect-35"); - m_configuration_dictionary.put("sol_8", "aruco-camera-24"); - m_configuration_dictionary.put("sol_9", "aruco-camera-headlamp-68"); - m_configuration_dictionary.put("sol_10", "mrpt-lidar-68"); - m_configuration_dictionary.put("sol_11", "amcl-lidar-68"); - m_configuration_dictionary.put("sol_12", "aruco-camera-68"); - m_configuration_dictionary.put("sol_13", "mrpt-kinect-68"); - m_configuration_dictionary.put("sol_14", "mrpt-kinect-24"); - m_configuration_dictionary.put("sol_15", "mrpt-lidar-24"); - m_configuration_dictionary.put("sol_16", "amcl-lidar-24"); - m_configuration_dictionary.put("sol_17", "amcl-kinect-24"); - - } - public static void enableOnlyDarkConfigs() { - for (String c : LIGHT_SENSITIVE_CONFIGS) { - m_configuration_dictionary.remove(c); - } - } - - public static Set getLightSensitiveConfigs() { - Set s = new HashSet<> (); - for (String c : LIGHT_SENSITIVE_CONFIGS) { - s.add(m_configuration_dictionary.get(c)); - } - return s; - } - - public String getConfigurationIndex(String confId){ - int c = 0; - for (String k: m_configurations.keySet()){ - if (Objects.equals(k, confId)){ - return String.valueOf(c); - } - c++; - } - return "-1"; // Not found - } - - public ConfigurationSynthesizer(Properties props) { - m_myConstraintModel = props.getProperty(PropertiesConfigurationSynthesizer.CONSTRAINTMODEL_PROPKEY); - m_myBaseModel = props.getProperty(PropertiesConfigurationSynthesizer.BASEMODEL_PROPKEY); - m_myModel = props.getProperty(PropertiesConfigurationSynthesizer.TEMPMODEL_PROPKEY); - m_myPolicy = props.getProperty(PropertiesConfigurationSynthesizer.POLICY_PROPKEY); - m_myProps = props.getProperty(PropertiesConfigurationSynthesizer.PROPS_PROPKEY); - m_battery_model = new DetailedConfigurationBatteryModel(props); - - try { - m_pc = PrismConnectorAPI.instance(); - } catch (Exception e) { - System.out.println("Configuration Synthesizer: Error initializing PRISM connector API."); - } - } - - @SuppressWarnings("unchecked") - public HashMap getConfigurations() { - return (HashMap) (HashMap) m_configuration_objects; - } - - /** - * Translates synthesized configuration identifiers into configuration - * identifiers in map - * - */ - public String translateId(String id) { - if (Objects.equals(null, m_configuration_dictionary.get(id))) - return ""; - return m_configuration_dictionary.get(id); - } - - public String translateConfigToId(String config) { - for (Entry e : m_configuration_dictionary.entrySet()) { - if (e.getValue().equals(config)) - return e.getKey(); - } - return ""; - } - - - public Boolean containsConfiguration(String id) { - return (m_configuration_dictionary.containsKey(id) || m_configuration_dictionary.containsValue(id)); - } - - /** - * Unpacks a string of constant definitions into the dictionary of - * ConstantDefinitions for the solver - * - * @param s - * String in format "const1id=min1:max1:step1;const2id=val2; ..." - */ - public void setConstantDefinitions(String s) { - String[] constantDefStrs = s.split(","); - for (int i = 0; i < constantDefStrs.length; i++) { - String defStr = constantDefStrs[i].trim(); - String def_id = defStr.split("=")[0].trim(); - System.out.println("RECONF HERE: " + defStr); - String def_tail = defStr.split("=")[1].trim(); - String[] defParts = def_tail.split(":"); - if (defParts.length > 1) { // If constant defined over a range min:max:step - m_constant_definitions.put(def_id, - new ConstantDefinition(def_id, defParts[0], defParts[1], defParts[2])); - } else { // simple value - m_constant_definitions.put(def_id, new ConstantDefinition(def_id, defParts[0], defParts[0], "0")); - } - } - System.out.println(m_constant_definitions.toString()); - } - - /** - * Generates set of configurations and their corresponding translations into - * prism predicates - * - * @param modelFile - * Alloy model file - * @return number of solutions generated - * @throws RainbowException - */ - public int generateConfigurations() throws RainbowException { - AlloyConnector ac = new AlloyConnector(); - try { - ac.generateSolutions(m_myConstraintModel); - } catch (Err e) { - throw new RainbowException(e); - } - for (int i = 0; i < ac.getSolutions().size(); i++) { - String strSolId = AlloyConnector.SOLUTION_STRING + String.valueOf(i); - String strSol = ac.getSolution(strSolId); - m_configurations.put(strSolId, strSol); - m_configuration_objects.put(strSolId, new DetailedConfiguration(strSolId, strSol, m_battery_model)); - } - return ac.getSolutions().size(); - } - - public void addConfigurationInstances() { - for (Map.Entry e : m_configurations.entrySet()) { - AlloySolution sol = new AlloySolution(); - sol.loadFromString(e.getValue()); - for (Map.Entry> e2 : sol.getAllInstances().entrySet()) { - for (int i = 0; i < e2.getValue().size(); i++) { - // System.out.println("KEY: "+e2.getValue().get(i)); - if (!m_allinstances.contains(e2.getValue().get(i).replace("$", "")) - && !Objects.equals("", e2.getValue().get(i))) { - m_allinstances.add(e2.getValue().get(i).replace("$", "")); - } - } - } - } - } - - public void generateBaseModel() { - String mode_varname = "status"; - ArrayList rewards = new ArrayList(); - - String code = "mdp\n\n"; - code += "global turn:[0.."+String.valueOf(m_allinstances.size()+1)+"] init 0;\n"; - - for (Map.Entry e : m_component_modes.entrySet()) { - code += "const " + e.getKey() + "=" + e.getValue() + ";\n"; - } - code += "\n"; - for (int i = 0; i < m_allinstances.size(); i++) { - String cid = m_allinstances.get(i); // Component id - code += "const " + cid + "_INIT;\n"; - code += "module " + cid + "\n"; - code += "\t" + cid + "_done : bool init false;\n"; - code += "\t" + cid + "_" + mode_varname + ":[0.." + String.valueOf(m_component_modes.size()) + "] init " - + cid + "_INIT;\n"; - for (Map.Entry e : m_component_actions.entrySet()) { - code += "\t[" + cid + "_" + e.getKey() + "] (turn="+String.valueOf(i)+") & ("+cid+"_done=false) & (" + cid + "_" + mode_varname + "=" + e.getValue()[0] - + ") -> (" + cid + "_" + mode_varname + "'=" + e.getValue()[1] + ") & ("+cid+"_done'=true);\n"; - int reward_quantity = 1; - if (Objects.equals(e.getKey(), "crash")) - reward_quantity = 9999; - rewards.add("\t[" + cid + "_" + e.getKey() + "] true : " + String.valueOf(reward_quantity) + ";\n"); - } - code += "\t[] (turn="+String.valueOf(i)+") -> (turn'="+String.valueOf(i+1)+");\n"; - code += "endmodule\n\n"; - } - - code += "rewards \"steps\"\n"; - for (int i = 0; i < rewards.size(); i++) { - code += rewards.get(i); - } - code += "endrewards\n\n"; // End code generation - // System.out.println(code); - TextFileHandler fBaseModel = new TextFileHandler(m_myBaseModel); // Export to base model file - fBaseModel.exportFile(code); - } - - public String configurationToPrismPred(String label) { // Exports to a prism predicate for reconfiguration - ArrayList inst = new ArrayList(); - AlloySolution sol = new AlloySolution(); - System.out.println(label); - sol.loadFromString(m_configurations.get(label)); - String res = "formula " + label + " = true"; - for (AlloySolutionNode node : sol.getNodes().values()) { - res += " & (" + node.getId().replace("$", "") + "_status=ENABLED)"; - inst.add(node.getId().replace("$", "")); - } - - for (int i = 0; i < m_allinstances.size(); i++) { - if (!inst.contains(m_allinstances.get(i))) { - res += " & (" + m_allinstances.get(i) + "_status=DISABLED | " + m_allinstances.get(i) - + "_status=OFFLINE)"; - } - } - res += ";\n"; - return res; - } - - public String configurationToPrismConstants(String label) { // Exports to a prism init constant strings for reconfiguration - ArrayList inst = new ArrayList(); - AlloySolution sol = new AlloySolution(); - System.out.println(label); - sol.loadFromString(m_configurations.get(label)); - String res = ""; - boolean first=true; - for (AlloySolutionNode node : sol.getNodes().values()) { - if (!first) res +=","; - first=false; - res += node.getId().replace("$", "") + "_INIT=1"; - inst.add(node.getId().replace("$", "")); - } - - for (int i = 0; i < m_allinstances.size(); i++) { - if (!inst.contains(m_allinstances.get(i))) { - res += "," + m_allinstances.get(i) + "_INIT=0"; - } - } - return res; - } - - public void generateConfigurationPreds() { - for (Map.Entry e : m_configurations.entrySet()) { - String prismConfString = configurationToPrismPred(e.getKey()); - m_configurationPredicates.put(e.getKey(), prismConfString); - System.out.println(prismConfString); - } - } - - public String generateTargetConfPredicate() { // For PCTL formula generation - String res = "("; - for (int i = 0; i < m_configurationPredicates.size(); i++) { - if (i > 0) - res += " | "; - res += AlloyConnector.SOLUTION_STRING + String.valueOf(i); - } - res += ")"; - return res; - } - - public void generateReconfigurations() throws RainbowException { - m_reconfigurations.clear(); - String constantdefs = new String(""); - for (int i = 0; i < m_allinstances.size(); i++) { - if (i > 0) - constantdefs += ","; - constantdefs += m_allinstances.get(i) + "_INIT=0:2:1"; - } - setConstantDefinitions(constantdefs); - SpaceIterator si = new SpaceIterator(m_constant_definitions); - - for (String s : si.getCombinations()) { - System.out.println("Init config: " + s); - try { - m_reconfigurations.put(s, generateReconfiguration(s)); - } catch (IOException e) { - throw new RainbowException(e); - } - } - - int empty = 0; - for (String s : si.getCombinations()) { - System.out.println("Init config: " + s); - System.out.println(m_reconfigurations.get(s)); - System.out.println("------------------------"); - if (m_reconfigurations.containsKey(s)) { - if (m_reconfigurations.get(s).size() == 0) { - empty++; - } - } else { - empty++; - } - } - System.out.printf("%d Reconfiguration plans generated (%d empty)", m_reconfigurations.size(), empty); - - } - - public ArrayList generateReconfiguration(String from) throws IOException { - // Gets base model template, appends encoding of configuration formulas, target - // configuration predicate, and writes it to a temp model file - TextFileHandler fBaseModel = new TextFileHandler(m_myBaseModel); - ArrayList baseCode = fBaseModel.readFileLines(); - - // For a given configuration - for (int i = 0; i < m_configurationPredicates.size(); i++) { - String configKey = AlloyConnector.SOLUTION_STRING + String.valueOf(i); - baseCode.add(m_configurationPredicates.get(configKey)); - // System.out.println(cs.m_configurationPredicates.get(configKey)); - } - // baseCode.add(cs.generateTargetConfPredicate()); - - TextFileHandler fTempModel = new TextFileHandler(m_myModel); - fTempModel.exportFile(baseCode); - - // Exports PCTL formula to compute reconfiguration plan to a temp property file - TextFileHandler fTempProps = new TextFileHandler(m_myProps); - fTempProps.exportFile("R{\"steps\"}min=? [ F " + generateTargetConfPredicate() + " ]"); - - PrismPolicy pp = null; - - try { - m_res = m_pc.modelCheckFromFileS(m_myModel, m_myProps, m_myPolicy, 0, from); - - } catch (Exception e) { - System.out.println("Configuration synthesizer: Error model checking reconfiguration from" + from); - } - pp = new PrismPolicy(m_myPolicy + ".adv"); - pp.readPolicy(); - String plan = pp.getPlan().toString(); - System.out.println(plan); - System.out.println("Result is:" + m_res); - return pp.getPlan(); - } - - public ArrayList generateUnorderedReconfiguration(String from, String to) throws RainbowException { - // Gets base model template, appends encoding of configuration formulas, target - // configuration predicate, and writes it to a temp model file - TextFileHandler fBaseModel = new TextFileHandler(m_myBaseModel); - ArrayList baseCode; - try { - baseCode = fBaseModel.readFileLines(); - } catch (IOException e1) { - throw new RainbowException(e1); - } - - // For a given configuration - for (int i = 0; i < m_configurationPredicates.size(); i++) { - String configKey = AlloyConnector.SOLUTION_STRING + String.valueOf(i); - baseCode.add(m_configurationPredicates.get(configKey)); - // System.out.println(cs.m_configurationPredicates.get(configKey)); - } - // baseCode.add(cs.generateTargetConfPredicate()); - - TextFileHandler fTempModel = new TextFileHandler(m_myModel); - fTempModel.exportFile(baseCode); - - // Exports PCTL formula to compute reconfiguration plan to a temp property file - TextFileHandler fTempProps = new TextFileHandler(m_myProps); - fTempProps.exportFile("R{\"steps\"}min=? [ F " + to + " ]"); - - PrismPolicy pp = null; - - try { - m_res = m_pc.modelCheckFromFileS(m_myModel, m_myProps, m_myPolicy, 0, from); - - } catch (Exception e) { - System.out.println("Configuration synthesizer: Error model checking reconfiguration from" + from); - } - try{ - Double reconf_steps = Double.parseDouble(m_res); - m_reconfiguration_costs.put(to, reconf_steps*RECONF_STEP_TIME_COST); - } catch(Exception e){ - System.out.println("Error parsing cost of reconfiguration."); - } - pp = new PrismPolicy(m_myPolicy + ".adv"); - pp.readPolicy(); - String plan = pp.getPlan().toString(); - System.out.println(plan); - System.out.println("Result is:" + m_res); - return pp.getPlan(); - } - - public ArrayList generateReconfiguration(String from, String to) throws RainbowException { - ArrayList reconf = generateUnorderedReconfiguration(from, to); - System.out.println("Checked " + m_configuration_dictionary.get(to) + ". " + (reconf.isEmpty()?"No plan":"Plan")); - ArrayList res = new ArrayList(); - ArrayList node_disablement = new ArrayList(); - ArrayList sensor_disablement = new ArrayList(); - ArrayList node_enablement = new ArrayList(); - ArrayList sensor_enablement = new ArrayList(); - ArrayList speed_enablement = new ArrayList(); - ArrayList map_enablement = new ArrayList (); - - for (int i = 0; i < reconf.size(); i++) { - if (reconf.get(i).endsWith("_disable") - && ReconfSynthTest.COMPONENT_NAMES.containsValue(reconf.get(i).replace("_disable", ""))) { - node_disablement.add(reconf.get(i)); - } - if (reconf.get(i).endsWith("_disable") - && ReconfSynthTest.SENSOR_NAMES.containsValue(reconf.get(i).replace("_disable", ""))) { - sensor_disablement.add(reconf.get(i)); - } - if (reconf.get(i).endsWith("_enable") - && ReconfSynthTest.SENSOR_NAMES.containsValue(reconf.get(i).replace("_enable", ""))) { - sensor_enablement.add(reconf.get(i)); - } - if (reconf.get(i).endsWith("_enable") - && reconf.get(i).contains("mapServer") - && ReconfSynthTest.COMPONENT_NAMES.containsValue(reconf.get(i).replace("_enable", ""))) { - map_enablement.add(reconf.get(i)); - } - else if (reconf.get(i).endsWith("_enable") - && ReconfSynthTest.COMPONENT_NAMES.containsValue(reconf.get(i).replace("_enable", ""))) { - node_enablement.add(reconf.get(i)); - } - if (reconf.get(i).endsWith("SpeedSetting0_enable")) { - speed_enablement.add(reconf.get(i)); - } - } - - res.addAll(node_disablement); - res.addAll(sensor_disablement); - res.addAll(sensor_enablement); - res.addAll(map_enablement); - res.addAll(node_enablement); - res.addAll(speed_enablement); - - return res; - } - - public void generateReconfigurationsFrom(String from) throws RainbowException { - m_reconfigurations.clear(); - for (String toConf : m_configuration_dictionary.keySet()) { - m_reconfigurations.put(toConf, generateReconfiguration(from, toConf)); - } - } - - public int getNumberOfValidReconfigurations() { - int empty = 0; - for (String toConf : m_configuration_dictionary.keySet()) { - if (m_reconfigurations.get(toConf).isEmpty()) empty++; - } - return m_reconfigurations.size() - empty; - } - - public HashMap> getLegalReconfigurationsFrom(String fromConfiguration) { - HashMap> res = new HashMap>(); - for (Map.Entry> e : m_reconfigurations.entrySet()) { - if (e.getValue().size() > 0) - res.put(e.getKey(), e.getValue()); - } - return res; - } - - public HashMap getLegalTargetConfigurations() { - HashMap res = new HashMap(); - for (Map.Entry> e : m_reconfigurations.entrySet()) { - if (m_configuration_objects.containsKey(e.getKey()) && m_reconfigurations.containsKey(e.getKey()) - && m_reconfigurations.get(e.getKey()).size() > 0) { - res.put(e.getKey(), m_configuration_objects.get(e.getKey())); - } - } - return res; - } - - public HashMap getLegalTargetConfigurationsFrom(String fromConfiguration) { - return getLegalTargetConfigurations(); - } - - public void populate() throws RainbowException { - String currentConfStr = "markerLocalization0_INIT=0,markerRecognizer0_INIT=0,amcl0_INIT=1,laserscanNodelet0_INIT=1,mrpt0_INIT=2,camera0_INIT=1,lidar0_INIT=1,headlamp0_INIT=0,kinect0_INIT=2,fullSpeedSetting0_INIT=0,halfSpeedSetting0_INIT=1"; - generateConfigurations(); - addConfigurationInstances(); - generateBaseModel(); - generateConfigurationPreds(); - } - - public Double getReconfigurationTime(String sourceConfiguration, String targetConfiguration) { - return getReconfigurationCost(targetConfiguration); - } - - public List getReconfigurationPath(String sourceConfiguration, String targetConfiguration) { - List res = new LinkedList(); - res.add(targetConfiguration); - return res; - } - - public static void main(String[] args) throws Exception { - - ConfigurationSynthesizer cs = new ConfigurationSynthesizer(); - m_battery_model = new DetailedConfigurationBatteryModel(PropertiesConfigurationSynthesizer.DEFAULT); - cs.generateConfigurations(); - cs.populate(); - // System.out.println("Global instance space: "+cs.m_allinstances.toString()); - // cs.generateReconfigurations(); - System.out.println(cs.getConfigurations().toString()); - } - - public Double getReconfigurationCost(String config){ - return m_reconfiguration_costs.get(config); - } - - - -} +package org.sa.rainbow.brass.confsynthesis; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Properties; +import java.util.Set; + +import org.sa.rainbow.brass.adaptation.PrismConnectorAPI; +import org.sa.rainbow.brass.adaptation.PrismPolicy; +import org.sa.rainbow.brass.confsynthesis.AlloySolution.AlloySolutionNode; +import org.sa.rainbow.core.error.RainbowException; + +import edu.mit.csail.sdg.alloy4.Err; + +public class ConfigurationSynthesizer implements ConfigurationProvider { + + public HashMap m_configurationPredicates = new HashMap(); + public HashMap m_configurations = new HashMap(); + public HashMap m_configuration_objects = new HashMap(); + public LinkedList m_allinstances = new LinkedList(); + public HashMap> m_reconfigurations = new HashMap>(); + public HashMap m_reconfiguration_costs = new HashMap(); + public static final HashMap m_component_modes; + public static DetailedConfigurationBatteryModel m_battery_model; + public static final Double RECONF_STEP_TIME_COST = 5.0; + static { + m_component_modes = new HashMap(); + m_component_modes.put("DISABLED", "0"); + m_component_modes.put("ENABLED", "1"); + m_component_modes.put("OFFLINE", "2"); + } + + private static final HashMap m_component_actions; + static { + m_component_actions = new HashMap(); + m_component_actions.put("enable", new String[] { "DISABLED", "ENABLED" }); + m_component_actions.put("disable", new String[] { "ENABLED", "DISABLED" }); +// m_component_actions.put("crash", new String[] { "ENABLED", "OFFLINE" }); + } + + private static final HashMap m_configuration_dictionary; + static { + m_configuration_dictionary = new HashMap(); + restoreAllConfigs(); + } + + private HashMap m_constant_definitions = new HashMap(); + + public String m_res = "result"; + public String m_myConstraintModel; + public String m_myBaseModel; + public String m_myModel; + public String m_myPolicy; + public String m_myProps; + + public static PrismConnectorAPI m_pc; + + public ConfigurationSynthesizer() { + this(PropertiesConfigurationSynthesizer.DEFAULT); + } + + protected static final Set LIGHT_SENSITIVE_CONFIGS = new HashSet<>(Arrays.asList("sol_4", "sol_12", "sol_8")); + + public static void restoreAllConfigs() { + m_configuration_dictionary.put("sol_0", "amcl-kinect-35"); + m_configuration_dictionary.put("sol_1", "aruco-camera-headlamp-24"); + m_configuration_dictionary.put("sol_2", "amcl-kinect-68"); + m_configuration_dictionary.put("sol_3", "mrpt-lidar-35"); + m_configuration_dictionary.put("sol_4", "aruco-camera-35"); + m_configuration_dictionary.put("sol_5", "aruco-camera-headlamp-35"); + m_configuration_dictionary.put("sol_6", "amcl-lidar-35"); + m_configuration_dictionary.put("sol_7", "mrpt-kinect-35"); + m_configuration_dictionary.put("sol_8", "aruco-camera-24"); + m_configuration_dictionary.put("sol_9", "aruco-camera-headlamp-68"); + m_configuration_dictionary.put("sol_10", "mrpt-lidar-68"); + m_configuration_dictionary.put("sol_11", "amcl-lidar-68"); + m_configuration_dictionary.put("sol_12", "aruco-camera-68"); + m_configuration_dictionary.put("sol_13", "mrpt-kinect-68"); + m_configuration_dictionary.put("sol_14", "mrpt-kinect-24"); + m_configuration_dictionary.put("sol_15", "mrpt-lidar-24"); + m_configuration_dictionary.put("sol_16", "amcl-lidar-24"); + m_configuration_dictionary.put("sol_17", "amcl-kinect-24"); + + } + public static void enableOnlyDarkConfigs() { + for (String c : LIGHT_SENSITIVE_CONFIGS) { + m_configuration_dictionary.remove(c); + } + } + + public static Set getLightSensitiveConfigs() { + Set s = new HashSet<> (); + for (String c : LIGHT_SENSITIVE_CONFIGS) { + s.add(m_configuration_dictionary.get(c)); + } + return s; + } + + public String getConfigurationIndex(String confId){ + int c = 0; + for (String k: m_configurations.keySet()){ + if (Objects.equals(k, confId)){ + return String.valueOf(c); + } + c++; + } + return "-1"; // Not found + } + + public ConfigurationSynthesizer(Properties props) { + m_myConstraintModel = props.getProperty(PropertiesConfigurationSynthesizer.CONSTRAINTMODEL_PROPKEY); + m_myBaseModel = props.getProperty(PropertiesConfigurationSynthesizer.BASEMODEL_PROPKEY); + m_myModel = props.getProperty(PropertiesConfigurationSynthesizer.TEMPMODEL_PROPKEY); + m_myPolicy = props.getProperty(PropertiesConfigurationSynthesizer.POLICY_PROPKEY); + m_myProps = props.getProperty(PropertiesConfigurationSynthesizer.PROPS_PROPKEY); + m_battery_model = new DetailedConfigurationBatteryModel(props); + + try { + m_pc = PrismConnectorAPI.instance(); + } catch (Exception e) { + System.out.println("Configuration Synthesizer: Error initializing PRISM connector API."); + } + } + + @SuppressWarnings("unchecked") + public HashMap getConfigurations() { + return (HashMap) (HashMap) m_configuration_objects; + } + + /** + * Translates synthesized configuration identifiers into configuration + * identifiers in map + * + */ + public String translateId(String id) { + if (Objects.equals(null, m_configuration_dictionary.get(id))) + return ""; + return m_configuration_dictionary.get(id); + } + + public String translateConfigToId(String config) { + for (Entry e : m_configuration_dictionary.entrySet()) { + if (e.getValue().equals(config)) + return e.getKey(); + } + return ""; + } + + + public Boolean containsConfiguration(String id) { + return (m_configuration_dictionary.containsKey(id) || m_configuration_dictionary.containsValue(id)); + } + + /** + * Unpacks a string of constant definitions into the dictionary of + * ConstantDefinitions for the solver + * + * @param s + * String in format "const1id=min1:max1:step1;const2id=val2; ..." + */ + public void setConstantDefinitions(String s) { + String[] constantDefStrs = s.split(","); + for (int i = 0; i < constantDefStrs.length; i++) { + String defStr = constantDefStrs[i].trim(); + String def_id = defStr.split("=")[0].trim(); + System.out.println("RECONF HERE: " + defStr); + String def_tail = defStr.split("=")[1].trim(); + String[] defParts = def_tail.split(":"); + if (defParts.length > 1) { // If constant defined over a range min:max:step + m_constant_definitions.put(def_id, + new ConstantDefinition(def_id, defParts[0], defParts[1], defParts[2])); + } else { // simple value + m_constant_definitions.put(def_id, new ConstantDefinition(def_id, defParts[0], defParts[0], "0")); + } + } + System.out.println(m_constant_definitions.toString()); + } + + /** + * Generates set of configurations and their corresponding translations into + * prism predicates + * + * @param modelFile + * Alloy model file + * @return number of solutions generated + * @throws RainbowException + */ + public int generateConfigurations() throws RainbowException { + AlloyConnector ac = new AlloyConnector(); + try { + ac.generateSolutions(m_myConstraintModel); + } catch (Err e) { + throw new RainbowException(e); + } + for (int i = 0; i < ac.getSolutions().size(); i++) { + String strSolId = AlloyConnector.SOLUTION_STRING + String.valueOf(i); + String strSol = ac.getSolution(strSolId); + m_configurations.put(strSolId, strSol); + m_configuration_objects.put(strSolId, new DetailedConfiguration(strSolId, strSol, m_battery_model)); + } + return ac.getSolutions().size(); + } + + public void addConfigurationInstances() { + for (Map.Entry e : m_configurations.entrySet()) { + AlloySolution sol = new AlloySolution(); + sol.loadFromString(e.getValue()); + for (Map.Entry> e2 : sol.getAllInstances().entrySet()) { + for (int i = 0; i < e2.getValue().size(); i++) { + // System.out.println("KEY: "+e2.getValue().get(i)); + if (!m_allinstances.contains(e2.getValue().get(i).replace("$", "")) + && !Objects.equals("", e2.getValue().get(i))) { + m_allinstances.add(e2.getValue().get(i).replace("$", "")); + } + } + } + } + } + + public void generateBaseModel() { + String mode_varname = "status"; + ArrayList rewards = new ArrayList(); + + String code = "mdp\n\n"; + code += "global turn:[0.."+String.valueOf(m_allinstances.size()+1)+"] init 0;\n"; + + for (Map.Entry e : m_component_modes.entrySet()) { + code += "const " + e.getKey() + "=" + e.getValue() + ";\n"; + } + code += "\n"; + for (int i = 0; i < m_allinstances.size(); i++) { + String cid = m_allinstances.get(i); // Component id + code += "const " + cid + "_INIT;\n"; + code += "module " + cid + "\n"; + code += "\t" + cid + "_done : bool init false;\n"; + code += "\t" + cid + "_" + mode_varname + ":[0.." + String.valueOf(m_component_modes.size()) + "] init " + + cid + "_INIT;\n"; + for (Map.Entry e : m_component_actions.entrySet()) { + code += "\t[" + cid + "_" + e.getKey() + "] (turn="+String.valueOf(i)+") & ("+cid+"_done=false) & (" + cid + "_" + mode_varname + "=" + e.getValue()[0] + + ") -> (" + cid + "_" + mode_varname + "'=" + e.getValue()[1] + ") & ("+cid+"_done'=true);\n"; + int reward_quantity = 1; + if (Objects.equals(e.getKey(), "crash")) + reward_quantity = 9999; + rewards.add("\t[" + cid + "_" + e.getKey() + "] true : " + String.valueOf(reward_quantity) + ";\n"); + } + code += "\t[] (turn="+String.valueOf(i)+") -> (turn'="+String.valueOf(i+1)+");\n"; + code += "endmodule\n\n"; + } + + code += "rewards \"steps\"\n"; + for (int i = 0; i < rewards.size(); i++) { + code += rewards.get(i); + } + code += "endrewards\n\n"; // End code generation + // System.out.println(code); + TextFileHandler fBaseModel = new TextFileHandler(m_myBaseModel); // Export to base model file + fBaseModel.exportFile(code); + } + + public String configurationToPrismPred(String label) { // Exports to a prism predicate for reconfiguration + ArrayList inst = new ArrayList(); + AlloySolution sol = new AlloySolution(); + System.out.println(label); + sol.loadFromString(m_configurations.get(label)); + String res = "formula " + label + " = true"; + for (AlloySolutionNode node : sol.getNodes().values()) { + res += " & (" + node.getId().replace("$", "") + "_status=ENABLED)"; + inst.add(node.getId().replace("$", "")); + } + + for (int i = 0; i < m_allinstances.size(); i++) { + if (!inst.contains(m_allinstances.get(i))) { + res += " & (" + m_allinstances.get(i) + "_status=DISABLED | " + m_allinstances.get(i) + + "_status=OFFLINE)"; + } + } + res += ";\n"; + return res; + } + + public String configurationToPrismConstants(String label) { // Exports to a prism init constant strings for reconfiguration + ArrayList inst = new ArrayList(); + AlloySolution sol = new AlloySolution(); + System.out.println(label); + sol.loadFromString(m_configurations.get(label)); + String res = ""; + boolean first=true; + for (AlloySolutionNode node : sol.getNodes().values()) { + if (!first) res +=","; + first=false; + res += node.getId().replace("$", "") + "_INIT=1"; + inst.add(node.getId().replace("$", "")); + } + + for (int i = 0; i < m_allinstances.size(); i++) { + if (!inst.contains(m_allinstances.get(i))) { + res += "," + m_allinstances.get(i) + "_INIT=0"; + } + } + return res; + } + + public void generateConfigurationPreds() { + for (Map.Entry e : m_configurations.entrySet()) { + String prismConfString = configurationToPrismPred(e.getKey()); + m_configurationPredicates.put(e.getKey(), prismConfString); + System.out.println(prismConfString); + } + } + + public String generateTargetConfPredicate() { // For PCTL formula generation + String res = "("; + for (int i = 0; i < m_configurationPredicates.size(); i++) { + if (i > 0) + res += " | "; + res += AlloyConnector.SOLUTION_STRING + String.valueOf(i); + } + res += ")"; + return res; + } + + public void generateReconfigurations() throws RainbowException { + m_reconfigurations.clear(); + String constantdefs = new String(""); + for (int i = 0; i < m_allinstances.size(); i++) { + if (i > 0) + constantdefs += ","; + constantdefs += m_allinstances.get(i) + "_INIT=0:2:1"; + } + setConstantDefinitions(constantdefs); + SpaceIterator si = new SpaceIterator(m_constant_definitions); + + for (String s : si.getCombinations()) { + System.out.println("Init config: " + s); + try { + m_reconfigurations.put(s, generateReconfiguration(s)); + } catch (IOException e) { + throw new RainbowException(e); + } + } + + int empty = 0; + for (String s : si.getCombinations()) { + System.out.println("Init config: " + s); + System.out.println(m_reconfigurations.get(s)); + System.out.println("------------------------"); + if (m_reconfigurations.containsKey(s)) { + if (m_reconfigurations.get(s).size() == 0) { + empty++; + } + } else { + empty++; + } + } + System.out.printf("%d Reconfiguration plans generated (%d empty)", m_reconfigurations.size(), empty); + + } + + public ArrayList generateReconfiguration(String from) throws IOException { + // Gets base model template, appends encoding of configuration formulas, target + // configuration predicate, and writes it to a temp model file + TextFileHandler fBaseModel = new TextFileHandler(m_myBaseModel); + ArrayList baseCode = fBaseModel.readFileLines(); + + // For a given configuration + for (int i = 0; i < m_configurationPredicates.size(); i++) { + String configKey = AlloyConnector.SOLUTION_STRING + String.valueOf(i); + baseCode.add(m_configurationPredicates.get(configKey)); + // System.out.println(cs.m_configurationPredicates.get(configKey)); + } + // baseCode.add(cs.generateTargetConfPredicate()); + + TextFileHandler fTempModel = new TextFileHandler(m_myModel); + fTempModel.exportFile(baseCode); + + // Exports PCTL formula to compute reconfiguration plan to a temp property file + TextFileHandler fTempProps = new TextFileHandler(m_myProps); + fTempProps.exportFile("R{\"steps\"}min=? [ F " + generateTargetConfPredicate() + " ]"); + + PrismPolicy pp = null; + + try { + m_res = m_pc.modelCheckFromFileS(m_myModel, m_myProps, m_myPolicy, 0, from); + + } catch (Exception e) { + System.out.println("Configuration synthesizer: Error model checking reconfiguration from" + from); + } + pp = new PrismPolicy(m_myPolicy + ".adv"); + pp.readPolicy(); + String plan = pp.getPlan().toString(); + System.out.println(plan); + System.out.println("Result is:" + m_res); + return pp.getPlan(); + } + + public ArrayList generateUnorderedReconfiguration(String from, String to) throws RainbowException { + // Gets base model template, appends encoding of configuration formulas, target + // configuration predicate, and writes it to a temp model file + TextFileHandler fBaseModel = new TextFileHandler(m_myBaseModel); + ArrayList baseCode; + try { + baseCode = fBaseModel.readFileLines(); + } catch (IOException e1) { + throw new RainbowException(e1); + } + + // For a given configuration + for (int i = 0; i < m_configurationPredicates.size(); i++) { + String configKey = AlloyConnector.SOLUTION_STRING + String.valueOf(i); + baseCode.add(m_configurationPredicates.get(configKey)); + // System.out.println(cs.m_configurationPredicates.get(configKey)); + } + // baseCode.add(cs.generateTargetConfPredicate()); + + TextFileHandler fTempModel = new TextFileHandler(m_myModel); + fTempModel.exportFile(baseCode); + + // Exports PCTL formula to compute reconfiguration plan to a temp property file + TextFileHandler fTempProps = new TextFileHandler(m_myProps); + fTempProps.exportFile("R{\"steps\"}min=? [ F " + to + " ]"); + + PrismPolicy pp = null; + + try { + m_res = m_pc.modelCheckFromFileS(m_myModel, m_myProps, m_myPolicy, 0, from); + + } catch (Exception e) { + System.out.println("Configuration synthesizer: Error model checking reconfiguration from" + from); + } + try{ + Double reconf_steps = Double.parseDouble(m_res); + m_reconfiguration_costs.put(to, reconf_steps*RECONF_STEP_TIME_COST); + } catch(Exception e){ + System.out.println("Error parsing cost of reconfiguration."); + } + pp = new PrismPolicy(m_myPolicy + ".adv"); + pp.readPolicy(); + String plan = pp.getPlan().toString(); + System.out.println(plan); + System.out.println("Result is:" + m_res); + return pp.getPlan(); + } + + public ArrayList generateReconfiguration(String from, String to) throws RainbowException { + ArrayList reconf = generateUnorderedReconfiguration(from, to); + System.out.println("Checked " + m_configuration_dictionary.get(to) + ". " + (reconf.isEmpty()?"No plan":"Plan")); + ArrayList res = new ArrayList(); + ArrayList node_disablement = new ArrayList(); + ArrayList sensor_disablement = new ArrayList(); + ArrayList node_enablement = new ArrayList(); + ArrayList sensor_enablement = new ArrayList(); + ArrayList speed_enablement = new ArrayList(); + ArrayList map_enablement = new ArrayList (); + + for (int i = 0; i < reconf.size(); i++) { + if (reconf.get(i).endsWith("_disable") + && ReconfSynthTest.COMPONENT_NAMES.containsValue(reconf.get(i).replace("_disable", ""))) { + node_disablement.add(reconf.get(i)); + } + if (reconf.get(i).endsWith("_disable") + && ReconfSynthTest.SENSOR_NAMES.containsValue(reconf.get(i).replace("_disable", ""))) { + sensor_disablement.add(reconf.get(i)); + } + if (reconf.get(i).endsWith("_enable") + && ReconfSynthTest.SENSOR_NAMES.containsValue(reconf.get(i).replace("_enable", ""))) { + sensor_enablement.add(reconf.get(i)); + } + if (reconf.get(i).endsWith("_enable") + && reconf.get(i).contains("mapServer") + && ReconfSynthTest.COMPONENT_NAMES.containsValue(reconf.get(i).replace("_enable", ""))) { + map_enablement.add(reconf.get(i)); + } + else if (reconf.get(i).endsWith("_enable") + && ReconfSynthTest.COMPONENT_NAMES.containsValue(reconf.get(i).replace("_enable", ""))) { + node_enablement.add(reconf.get(i)); + } + if (reconf.get(i).endsWith("SpeedSetting0_enable")) { + speed_enablement.add(reconf.get(i)); + } + } + + res.addAll(node_disablement); + res.addAll(sensor_disablement); + res.addAll(sensor_enablement); + res.addAll(map_enablement); + res.addAll(node_enablement); + res.addAll(speed_enablement); + + return res; + } + + public void generateReconfigurationsFrom(String from) throws RainbowException { + m_reconfigurations.clear(); + for (String toConf : m_configuration_dictionary.keySet()) { + m_reconfigurations.put(toConf, generateReconfiguration(from, toConf)); + } + } + + public int getNumberOfValidReconfigurations() { + int empty = 0; + for (String toConf : m_configuration_dictionary.keySet()) { + if (m_reconfigurations.get(toConf).isEmpty()) empty++; + } + return m_reconfigurations.size() - empty; + } + + public HashMap> getLegalReconfigurationsFrom(String fromConfiguration) { + HashMap> res = new HashMap>(); + for (Map.Entry> e : m_reconfigurations.entrySet()) { + if (e.getValue().size() > 0) + res.put(e.getKey(), e.getValue()); + } + return res; + } + + public HashMap getLegalTargetConfigurations() { + HashMap res = new HashMap(); + for (Map.Entry> e : m_reconfigurations.entrySet()) { + if (m_configuration_objects.containsKey(e.getKey()) && m_reconfigurations.containsKey(e.getKey()) + && m_reconfigurations.get(e.getKey()).size() > 0) { + res.put(e.getKey(), m_configuration_objects.get(e.getKey())); + } + } + return res; + } + + public HashMap getLegalTargetConfigurationsFrom(String fromConfiguration) { + return getLegalTargetConfigurations(); + } + + public void populate() throws RainbowException { + String currentConfStr = "markerLocalization0_INIT=0,markerRecognizer0_INIT=0,amcl0_INIT=1,laserscanNodelet0_INIT=1,mrpt0_INIT=2,camera0_INIT=1,lidar0_INIT=1,headlamp0_INIT=0,kinect0_INIT=2,fullSpeedSetting0_INIT=0,halfSpeedSetting0_INIT=1"; + generateConfigurations(); + addConfigurationInstances(); + generateBaseModel(); + generateConfigurationPreds(); + } + + public Double getReconfigurationTime(String sourceConfiguration, String targetConfiguration) { + return getReconfigurationCost(targetConfiguration); + } + + public List getReconfigurationPath(String sourceConfiguration, String targetConfiguration) { + List res = new LinkedList(); + res.add(targetConfiguration); + return res; + } + + public static void main(String[] args) throws Exception { + + ConfigurationSynthesizer cs = new ConfigurationSynthesizer(); + m_battery_model = new DetailedConfigurationBatteryModel(PropertiesConfigurationSynthesizer.DEFAULT); + cs.generateConfigurations(); + cs.populate(); + // System.out.println("Global instance space: "+cs.m_allinstances.toString()); + // cs.generateReconfigurations(); + System.out.println(cs.getConfigurations().toString()); + } + + public Double getReconfigurationCost(String config){ + return m_reconfiguration_costs.get(config); + } + + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ReconfSynth.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ReconfSynth.java index 51f2be48a..c63de0726 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ReconfSynth.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ReconfSynth.java @@ -1,48 +1,48 @@ -package org.sa.rainbow.brass.confsynthesis; - -import java.util.HashMap; - -import org.apache.log4j.Logger; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; - -public abstract class ReconfSynth { - public static final HashMap SENSOR_NAMES; - public static Logger LOGGER; - static{ - SENSOR_NAMES = new HashMap(); - SENSOR_NAMES.put(Sensors.KINECT, "kinect0"); - SENSOR_NAMES.put(Sensors.CAMERA, "camera0"); - SENSOR_NAMES.put(Sensors.LIDAR, "lidar0"); - SENSOR_NAMES.put(Sensors.HEADLAMP, "headlamp0"); - } - - public static final HashMap COMPONENT_NAMES; - static{ - COMPONENT_NAMES = new HashMap(); - COMPONENT_NAMES.put("amcl", "amcl0"); - COMPONENT_NAMES.put("mrpt", "mrpt0"); - COMPONENT_NAMES.put("laserScan_nodelet", "laserscanNodelet0"); - COMPONENT_NAMES.put("marker_pose_publisher", "markerLocalization0"); - COMPONENT_NAMES.put("aruco_marker_publisher_front", "markerRecognizer0"); - COMPONENT_NAMES.put("map_server", "mapServerStd0"); - COMPONENT_NAMES.put("map_server_obs", "mapServerObs0"); - } - - abstract public String getCurrentConfigurationInitConstants(); - - public static final void logInfo(String msg) { - if (LOGGER == null) { - System.out.println(msg); - } - else - LOGGER.info(msg); - } - - public static final void logError(String err) { - if (LOGGER == null) { - System.out.println(err); - } - else - LOGGER.error(err); - } -} +package org.sa.rainbow.brass.confsynthesis; + +import java.util.HashMap; + +import org.apache.log4j.Logger; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; + +public abstract class ReconfSynth { + public static final HashMap SENSOR_NAMES; + public static Logger LOGGER; + static{ + SENSOR_NAMES = new HashMap(); + SENSOR_NAMES.put(Sensors.KINECT, "kinect0"); + SENSOR_NAMES.put(Sensors.CAMERA, "camera0"); + SENSOR_NAMES.put(Sensors.LIDAR, "lidar0"); + SENSOR_NAMES.put(Sensors.HEADLAMP, "headlamp0"); + } + + public static final HashMap COMPONENT_NAMES; + static{ + COMPONENT_NAMES = new HashMap(); + COMPONENT_NAMES.put("amcl", "amcl0"); + COMPONENT_NAMES.put("mrpt", "mrpt0"); + COMPONENT_NAMES.put("laserScan_nodelet", "laserscanNodelet0"); + COMPONENT_NAMES.put("marker_pose_publisher", "markerLocalization0"); + COMPONENT_NAMES.put("aruco_marker_publisher_front", "markerRecognizer0"); + COMPONENT_NAMES.put("map_server", "mapServerStd0"); + COMPONENT_NAMES.put("map_server_obs", "mapServerObs0"); + } + + abstract public String getCurrentConfigurationInitConstants(); + + public static final void logInfo(String msg) { + if (LOGGER == null) { + System.out.println(msg); + } + else + LOGGER.info(msg); + } + + public static final void logError(String err) { + if (LOGGER == null) { + System.out.println(err); + } + else + LOGGER.error(err); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ReconfSynthReal.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ReconfSynthReal.java index dac6c02d4..2f04c2bd6 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ReconfSynthReal.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/confsynthesis/ReconfSynthReal.java @@ -1,118 +1,118 @@ -package org.sa.rainbow.brass.confsynthesis; - -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Set; - -import org.sa.rainbow.brass.model.p2_cp3.ICP3ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.acme.TurtlebotModelInstance; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; - -import com.google.common.base.Objects; - -public class ReconfSynthReal extends ReconfSynth { - - private TurtlebotModelInstance m_tb; - private CP3RobotState m_rb; - - - public ReconfSynthReal(ICP3ModelAccessor models) { - m_tb = models.getTurtlebotModel(); - m_rb = models.getRobotStateModel().getModelInstance(); - } - - public String getCurrentConfigurationInitConstants() { - return getCurrentConfigurationInitConstants(Collections.emptySet(), Collections.emptySet()); - } - - public String getCurrentConfigurationInitConstants(Set forcedFailedComps, Set forcedFailedSensors){ - String res=""; - - int i=0; - for(String c : m_tb.getInactiveComponents()){ - if (!forcedFailedComps.contains(c) && !Objects.equal(null, COMPONENT_NAMES.get(c))){ - if (i>0) - res+=","; - res+=COMPONENT_NAMES.get(c)+"_INIT="+ConfigurationSynthesizer.m_component_modes.get("DISABLED"); - i++; - } - } - - for(String c : m_tb.getActiveComponents()){ - if (!forcedFailedComps.contains(c) && !Objects.equal(null, COMPONENT_NAMES.get(c))){ - res+=","; - res+=COMPONENT_NAMES.get(c)+"_INIT="+ConfigurationSynthesizer.m_component_modes.get("ENABLED"); - } - } - - Collection failedComponents = (Set )m_tb.getFailedComponents(); - failedComponents.addAll(forcedFailedComps); - for(String c : failedComponents){ - if (!Objects.equal(null, COMPONENT_NAMES.get(c))){ - res+=","; - res+=COMPONENT_NAMES.get(c)+"_INIT="+ConfigurationSynthesizer.m_component_modes.get("OFFLINE"); - } - } - - for (Sensors s: m_rb.getAvailableSensors()){ - if (!forcedFailedSensors.contains(s) && !Objects.equal(null, SENSOR_NAMES.get(s))){ - boolean sensorOn = false; - switch (s){ - case KINECT: - try{ - sensorOn = m_rb.isKinectOn(); - } catch(Exception e){ - logError("Illegal state exception determining if Sensor is On."); - } - break; - case CAMERA: - try{ - sensorOn = m_rb.isCameraOn(); - } catch(Exception e){ - logError("Illegal state exception determining if Sensor is On."); - } - break; - case LIDAR: - try{ - sensorOn = m_rb.isLidarOn(); - } catch(Exception e){ - logError("Illegal state exception determining if Sensor is On."); - } - break; - case HEADLAMP: - try{ - sensorOn = m_rb.isHeadlampOn(); - } catch(Exception e){ - System.out.println("Illegal state exception determining if Sensor is On."); - } - break; - - } - String compModeStr = ConfigurationSynthesizer.m_component_modes.get("DISABLED"); - if (sensorOn) - compModeStr = ConfigurationSynthesizer.m_component_modes.get("ENABLED"); - res+=","; - res+=SENSOR_NAMES.get(s)+"_INIT="+compModeStr; - } - } - - EnumSet failedSensors = m_rb.getFailedSensors(); - failedSensors.addAll(forcedFailedSensors); - for (Sensors s: failedSensors){ - res+=","; - res+=SENSOR_NAMES.get(s)+"_INIT="+ConfigurationSynthesizer.m_component_modes.get("OFFLINE"); - } - - res+=",fullSpeedSetting0_INIT="+ConfigurationSynthesizer.m_component_modes.get("DISABLED"); // This has to be changed!! Hardwired for the time being. - res+=",halfSpeedSetting0_INIT="+ConfigurationSynthesizer.m_component_modes.get("ENABLED"); - res+=",safeSpeedSetting0_INIT="+ConfigurationSynthesizer.m_component_modes.get("DISABLED"); - - // Rework to this: - // STOPPED = speed < 0.05ms, SAFE = 0.05 <= speed <= 0.25ms, SLOW = 0.25 < speed < 0.35, FULL otherwise. - - return res; - } - -} +package org.sa.rainbow.brass.confsynthesis; + +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.Set; + +import org.sa.rainbow.brass.model.p2_cp3.ICP3ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.acme.TurtlebotModelInstance; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; + +import com.google.common.base.Objects; + +public class ReconfSynthReal extends ReconfSynth { + + private TurtlebotModelInstance m_tb; + private CP3RobotState m_rb; + + + public ReconfSynthReal(ICP3ModelAccessor models) { + m_tb = models.getTurtlebotModel(); + m_rb = models.getRobotStateModel().getModelInstance(); + } + + public String getCurrentConfigurationInitConstants() { + return getCurrentConfigurationInitConstants(Collections.emptySet(), Collections.emptySet()); + } + + public String getCurrentConfigurationInitConstants(Set forcedFailedComps, Set forcedFailedSensors){ + String res=""; + + int i=0; + for(String c : m_tb.getInactiveComponents()){ + if (!forcedFailedComps.contains(c) && !Objects.equal(null, COMPONENT_NAMES.get(c))){ + if (i>0) + res+=","; + res+=COMPONENT_NAMES.get(c)+"_INIT="+ConfigurationSynthesizer.m_component_modes.get("DISABLED"); + i++; + } + } + + for(String c : m_tb.getActiveComponents()){ + if (!forcedFailedComps.contains(c) && !Objects.equal(null, COMPONENT_NAMES.get(c))){ + res+=","; + res+=COMPONENT_NAMES.get(c)+"_INIT="+ConfigurationSynthesizer.m_component_modes.get("ENABLED"); + } + } + + Collection failedComponents = (Set )m_tb.getFailedComponents(); + failedComponents.addAll(forcedFailedComps); + for(String c : failedComponents){ + if (!Objects.equal(null, COMPONENT_NAMES.get(c))){ + res+=","; + res+=COMPONENT_NAMES.get(c)+"_INIT="+ConfigurationSynthesizer.m_component_modes.get("OFFLINE"); + } + } + + for (Sensors s: m_rb.getAvailableSensors()){ + if (!forcedFailedSensors.contains(s) && !Objects.equal(null, SENSOR_NAMES.get(s))){ + boolean sensorOn = false; + switch (s){ + case KINECT: + try{ + sensorOn = m_rb.isKinectOn(); + } catch(Exception e){ + logError("Illegal state exception determining if Sensor is On."); + } + break; + case CAMERA: + try{ + sensorOn = m_rb.isCameraOn(); + } catch(Exception e){ + logError("Illegal state exception determining if Sensor is On."); + } + break; + case LIDAR: + try{ + sensorOn = m_rb.isLidarOn(); + } catch(Exception e){ + logError("Illegal state exception determining if Sensor is On."); + } + break; + case HEADLAMP: + try{ + sensorOn = m_rb.isHeadlampOn(); + } catch(Exception e){ + System.out.println("Illegal state exception determining if Sensor is On."); + } + break; + + } + String compModeStr = ConfigurationSynthesizer.m_component_modes.get("DISABLED"); + if (sensorOn) + compModeStr = ConfigurationSynthesizer.m_component_modes.get("ENABLED"); + res+=","; + res+=SENSOR_NAMES.get(s)+"_INIT="+compModeStr; + } + } + + EnumSet failedSensors = m_rb.getFailedSensors(); + failedSensors.addAll(forcedFailedSensors); + for (Sensors s: failedSensors){ + res+=","; + res+=SENSOR_NAMES.get(s)+"_INIT="+ConfigurationSynthesizer.m_component_modes.get("OFFLINE"); + } + + res+=",fullSpeedSetting0_INIT="+ConfigurationSynthesizer.m_component_modes.get("DISABLED"); // This has to be changed!! Hardwired for the time being. + res+=",halfSpeedSetting0_INIT="+ConfigurationSynthesizer.m_component_modes.get("ENABLED"); + res+=",safeSpeedSetting0_INIT="+ConfigurationSynthesizer.m_component_modes.get("DISABLED"); + + // Rework to this: + // STOPPED = speed < 0.05ms, SAFE = 0.05 <= speed <= 0.25ms, SLOW = 0.25 < speed < 0.35, FULL otherwise. + + return res; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/das/BRASSHttpConnector.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/das/BRASSHttpConnector.java index beef9050a..661935d9b 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/das/BRASSHttpConnector.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/das/BRASSHttpConnector.java @@ -14,6 +14,8 @@ import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; import okhttp3.Call; import okhttp3.Callback; @@ -30,6 +32,7 @@ public class BRASSHttpConnector /*extends AbstractRainbowRunnable*/ implements I public static final MediaType JSON = MediaType.parse ("application/json"); public static final OkHttpClient CLIENT = new OkHttpClient (); public static final String STATUS_SERVER = "http://localhost:5000"; + public static final String LEARN_ENDPOINT = "/internal-status"; private static BRASSHttpConnector s_instance; public Queue m_requestQ = new SynchronousQueue<> (); private Callback m_responseCallback = new Callback () { @@ -167,6 +170,54 @@ public void reportDone (boolean failed, String message) { // } // catch (IOException e) { // } + } + + boolean m_onlineLearning = false; + + public boolean requestOnlineLearning() { + final Object lock = new Object(); + JsonObject json = getTimeJSON(); + addFieldsToStatus("learning-requested", "requesting online learning", json); + RequestBody body = RequestBody.create(JSON, m_gsonPP.toJson(json)); + Request request = new Request.Builder().url(STATUS_SERVER + LEARN_ENDPOINT).post(body).build(); + + + CLIENT.newCall(request).enqueue(new Callback() { + + @Override + public void onResponse(Call call, Response response) throws IOException { + String responseString = response.body().string(); + System.out.println("Received response from shim: " + responseString); + boolean wait = false; + try { + JsonObject j = new JsonParser().parse(responseString).getAsJsonObject(); + wait = j.get("success").getAsBoolean(); + } catch (JsonSyntaxException e) { + e.printStackTrace(); + } + m_onlineLearning = wait; + synchronized (lock) { + lock.notifyAll(); + } + + } + + @Override + public void onFailure(Call call, IOException e) { + synchronized (lock) { + lock.notifyAll(); + } + } + }); + + // Wait for result + synchronized (lock) { + try { + lock.wait(); + } catch (InterruptedException e1) { + } + } + return m_onlineLearning; } private String missionSucceeded() { diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/effectors/BRASSEffectorManager.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/effectors/BRASSEffectorManager.java index 2f77aa9fc..01a4f4d6a 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/effectors/BRASSEffectorManager.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/effectors/BRASSEffectorManager.java @@ -1,85 +1,85 @@ -package org.sa.rainbow.brass.effectors; - -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.Iterator; -import java.util.Set; - -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.models.EffectorDescription.EffectorAttributes; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.translator.effectors.EffectorManager; -import org.sa.rainbow.translator.effectors.IEffectorExecutionPort.Outcome; - -/** - * Created by schmerl on 12/27/2016. - */ -public class BRASSEffectorManager extends EffectorManager { - public BRASSEffectorManager () { - super ("BRASS Effector Manager"); - } - - @Override - public OperationResult publishOperation (IRainbowOperation cmd) { - OperationResult badResult = new OperationResult (); - badResult.result = Result.UNKNOWN; - - OperationResult actualResult = badResult; - Set effectors = getEffectorsAtLocation ( - Rainbow.instance ().getProperty ("rainbow.master.location.host")); - filterEffectorsForCommand (cmd, effectors); - if (!effectors.isEmpty ()) { - OperationResult result = new OperationResult (); - result.result = Result.SUCCESS; - StringBuilder errMsg = new StringBuilder (); - for (EffectorAttributes ea : effectors) { - Outcome outcome = executeEffector (ea.name, ea.getLocation (), cmd.getParameters ()); - if (outcome != Outcome.SUCCESS) { - errMsg.append (MessageFormat.format ("E[{0}@{1}]: Failed to execute command {2} - ", ea.name, - ea.getLocation (), Arrays.toString (cmd.getParameters ()))); - switch (outcome) { - case CONFOUNDED: - errMsg.append ("CONFOUNDED"); - result.result = Result.FAILURE; - break; - case TIMEOUT: - errMsg.append ("TIMED OUT"); - result.result = Result.FAILURE; - break; - case UNKNOWN: - errMsg.append ("UNKNOWN"); - if (result.result != Result.FAILURE) { - result.result = Result.UNKNOWN; - } - break; - } - errMsg.append ("\n"); - } - } - if (result.result == Result.FAILURE) { - result.reply = errMsg.toString (); - } - else { - result.reply = cmd.toString (); - } - actualResult = result; - } - else { - badResult.reply = "Could not find an effector for " + cmd.toString (); - } - - return actualResult; - - } - - private void filterEffectorsForCommand (IRainbowOperation cmd, Set effectors) { - for (Iterator i = effectors.iterator (); i.hasNext ();) { - EffectorAttributes ea = (EffectorAttributes )i.next (); - if (ea.getCommandPattern () == null || !ea.getCommandPattern ().getName ().equals (cmd.getName ())) { - i.remove (); - } - - } - } - -} +package org.sa.rainbow.brass.effectors; + +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.Iterator; +import java.util.Set; + +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.models.EffectorDescription.EffectorAttributes; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.translator.effectors.EffectorManager; +import org.sa.rainbow.translator.effectors.IEffectorExecutionPort.Outcome; + +/** + * Created by schmerl on 12/27/2016. + */ +public class BRASSEffectorManager extends EffectorManager { + public BRASSEffectorManager () { + super ("BRASS Effector Manager"); + } + + @Override + public OperationResult publishOperation (IRainbowOperation cmd) { + OperationResult badResult = new OperationResult (); + badResult.result = Result.UNKNOWN; + + OperationResult actualResult = badResult; + Set effectors = getEffectorsAtLocation ( + Rainbow.instance ().getProperty ("rainbow.master.location.host")); + filterEffectorsForCommand (cmd, effectors); + if (!effectors.isEmpty ()) { + OperationResult result = new OperationResult (); + result.result = Result.SUCCESS; + StringBuilder errMsg = new StringBuilder (); + for (EffectorAttributes ea : effectors) { + Outcome outcome = executeEffector (ea.name, ea.getLocation (), cmd.getParameters ()); + if (outcome != Outcome.SUCCESS) { + errMsg.append (MessageFormat.format ("E[{0}@{1}]: Failed to execute command {2} - ", ea.name, + ea.getLocation (), Arrays.toString (cmd.getParameters ()))); + switch (outcome) { + case CONFOUNDED: + errMsg.append ("CONFOUNDED"); + result.result = Result.FAILURE; + break; + case TIMEOUT: + errMsg.append ("TIMED OUT"); + result.result = Result.FAILURE; + break; + case UNKNOWN: + errMsg.append ("UNKNOWN"); + if (result.result != Result.FAILURE) { + result.result = Result.UNKNOWN; + } + break; + } + errMsg.append ("\n"); + } + } + if (result.result == Result.FAILURE) { + result.reply = errMsg.toString (); + } + else { + result.reply = cmd.toString (); + } + actualResult = result; + } + else { + badResult.reply = "Could not find an effector for " + cmd.toString (); + } + + return actualResult; + + } + + private void filterEffectorsForCommand (IRainbowOperation cmd, Set effectors) { + for (Iterator i = effectors.iterator (); i.hasNext ();) { + EffectorAttributes ea = (EffectorAttributes )i.next (); + if (ea.getCommandPattern () == null || !ea.getCommandPattern ().getName ().equals (cmd.getName ())) { + i.remove (); + } + + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/InstructionGraphGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/InstructionGraphGauge.java index 29ec84ea4..214d2c1ba 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/InstructionGraphGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/InstructionGraphGauge.java @@ -1,101 +1,101 @@ -package org.sa.rainbow.brass.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Created by schmerl on 12/27/2016. - */ -public class InstructionGraphGauge extends RegularPatternGauge { - public static final String NAME = "Task Progress Gauge"; - protected static final String IG = "IGProgress"; - protected static final String NEWIG = "NewIG"; - private static final String FINISHEDIG = "IGFinished"; - - protected static final String INSTRUCTION_PATTERN = "topic: /ig_action_server/feedback/feedback/sequence[^\\d]*(\\d+)\\.\\d+:([^:]*):(.*)\\\".*"; - protected static final String NEWIG_PATTERN = "topic: /ig_action_server/feedback/feedback/sequence.*Received new " + - "valid IG: (.*)"; - protected static final String FINISHIG_PATTERN = "topic: /ig_action_server/feedback/feedback/sequence.*Finished!.*"; - - - /** - * Main Constructor the Gauge that is hardwired to the Probe. - * - * @param id the unique ID of the Gauge - * @param beaconPeriod the liveness beacon period of the Gauge - * @param gaugeDesc the type-name description of the Gauge - * @param modelDesc the type-name description of the Model the Gauge updates - * @param setupParams the list of setup parameters with their values - * @param mappings the list of Gauge Value to Model Property mappings - */ - public InstructionGraphGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern (IG, Pattern.compile (INSTRUCTION_PATTERN, Pattern.DOTALL)); - addPattern (NEWIG, Pattern.compile (NEWIG_PATTERN, Pattern.DOTALL)); -// addPattern (FINISHEDIG, Pattern.compile (FINISHIG_PATTERN, Pattern.DOTALL)); - } - - @Override - protected void doMatch (String matchName, Matcher m) { - if (IG.equals (matchName)) { - String node = m.group (1).split ("\\.")[0]; - String status = m.group (3).trim(); - System.out.println("Reporting " + m.group(2) + ": " + status); - - if ("START".equals (status)) { - IRainbowOperation operation = m_commands.get ("current-instruction"); - Map pap = new HashMap<> (); - pap.put (operation.getParameters ()[0], node); - pap.put (operation.getParameters ()[1], "START"); - issueCommand (operation, pap); - } - else if ("SUCCESS".equals (status)) { - IRainbowOperation operation = m_commands.get ("current-instruction"); - Map pap = new HashMap<> (); - pap.put (operation.getParameters ()[0], node); - pap.put (operation.getParameters ()[1], "SUCCESS"); - issueCommand (operation, pap); - } - else if (status.startsWith ("FAILED")) { - IRainbowOperation operation = m_commands.get ("current-failed"); - Map pap = new HashMap<> (); - pap.put (operation.getParameters ()[0], node); - issueCommand (operation, pap); -// IRainbowOperation failedOp = m_commands.get ("finished-ig"); -// Map finishP = new HashMap<> (); -// finishP.put (failedOp.getParameters ()[0], "false"); -// ArrayList> ps = new ArrayList> (2); -// ps.add (pap); -// ps.add (finishP); -// issueCommands (Arrays.asList (new IRainbowOperation[] { operation, failedOp }), ps); - - } - } - else if (NEWIG.equals (matchName)) { - System.out.println("Reporting new IG " + m.group(1).trim()); - String ig = m.group(1).trim (); - IRainbowOperation op = m_commands.get ("new-ig"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0],ig); - issueCommand(op, pMap); - } - else if (FINISHEDIG.equals (matchName)) { - System.out.println("Reporting finisehd instruction graph"); - IRainbowOperation op = m_commands.get ("finished-ig"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], "true"); - issueCommand (op, pMap); - } - } -} +package org.sa.rainbow.brass.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Created by schmerl on 12/27/2016. + */ +public class InstructionGraphGauge extends RegularPatternGauge { + public static final String NAME = "Task Progress Gauge"; + protected static final String IG = "IGProgress"; + protected static final String NEWIG = "NewIG"; + private static final String FINISHEDIG = "IGFinished"; + + protected static final String INSTRUCTION_PATTERN = "topic: /ig_action_server/feedback/feedback/sequence[^\\d]*(\\d+)\\.\\d+:([^:]*):(.*)\\\".*"; + protected static final String NEWIG_PATTERN = "topic: /ig_action_server/feedback/feedback/sequence.*Received new " + + "valid IG: (.*)"; + protected static final String FINISHIG_PATTERN = "topic: /ig_action_server/feedback/feedback/sequence.*Finished!.*"; + + + /** + * Main Constructor the Gauge that is hardwired to the Probe. + * + * @param id the unique ID of the Gauge + * @param beaconPeriod the liveness beacon period of the Gauge + * @param gaugeDesc the type-name description of the Gauge + * @param modelDesc the type-name description of the Model the Gauge updates + * @param setupParams the list of setup parameters with their values + * @param mappings the list of Gauge Value to Model Property mappings + */ + public InstructionGraphGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern (IG, Pattern.compile (INSTRUCTION_PATTERN, Pattern.DOTALL)); + addPattern (NEWIG, Pattern.compile (NEWIG_PATTERN, Pattern.DOTALL)); +// addPattern (FINISHEDIG, Pattern.compile (FINISHIG_PATTERN, Pattern.DOTALL)); + } + + @Override + protected void doMatch (String matchName, Matcher m) { + if (IG.equals (matchName)) { + String node = m.group (1).split ("\\.")[0]; + String status = m.group (3).trim(); + System.out.println("Reporting " + m.group(2) + ": " + status); + + if ("START".equals (status)) { + IRainbowOperation operation = m_commands.get ("current-instruction"); + Map pap = new HashMap<> (); + pap.put (operation.getParameters ()[0], node); + pap.put (operation.getParameters ()[1], "START"); + issueCommand (operation, pap); + } + else if ("SUCCESS".equals (status)) { + IRainbowOperation operation = m_commands.get ("current-instruction"); + Map pap = new HashMap<> (); + pap.put (operation.getParameters ()[0], node); + pap.put (operation.getParameters ()[1], "SUCCESS"); + issueCommand (operation, pap); + } + else if (status.startsWith ("FAILED")) { + IRainbowOperation operation = m_commands.get ("current-failed"); + Map pap = new HashMap<> (); + pap.put (operation.getParameters ()[0], node); + issueCommand (operation, pap); +// IRainbowOperation failedOp = m_commands.get ("finished-ig"); +// Map finishP = new HashMap<> (); +// finishP.put (failedOp.getParameters ()[0], "false"); +// ArrayList> ps = new ArrayList> (2); +// ps.add (pap); +// ps.add (finishP); +// issueCommands (Arrays.asList (new IRainbowOperation[] { operation, failedOp }), ps); + + } + } + else if (NEWIG.equals (matchName)) { + System.out.println("Reporting new IG " + m.group(1).trim()); + String ig = m.group(1).trim (); + IRainbowOperation op = m_commands.get ("new-ig"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0],ig); + issueCommand(op, pMap); + } + else if (FINISHEDIG.equals (matchName)) { + System.out.println("Reporting finisehd instruction graph"); + IRainbowOperation op = m_commands.get ("finished-ig"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], "true"); + issueCommand (op, pMap); + } + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/MissionStateGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/MissionStateGauge.java index a4d8f0858..b75cc7545 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/MissionStateGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/MissionStateGauge.java @@ -1,232 +1,232 @@ -package org.sa.rainbow.brass.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.brass.model.map.BatteryPredictor; -import org.sa.rainbow.brass.model.map.MapTranslator; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Created by schmerl on 12/28/2016. - */ -public class MissionStateGauge extends RegularPatternGauge { - private static final String NAME = "Mission State Gauge"; - protected static final String LOC = "LocationRecording"; - protected static final String CHARGE = "BatteryCharge"; - protected static final String DEADLINE = "Deadline"; - protected static final String CLOCK = "Clock"; - protected static final String GROUNDPLANE = "GroundPlane"; - protected static final String CALIBRATION_ERROR = "Calibration"; - - protected static final String LOC_PATTERN = "topic: /amcl_pose/pose/pose.*position.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z.*\\norientation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z: (.*)\\n.*w: (.*)(.*)"; - protected static final String CHARGE_PATTERN = "topic: /energy_monitor/voltage.*\\n.*data: (.*)\\n(.*)"; - protected static final String DEADLINE_PATTERN = "topic: /notify_user.*\\n.*new_deadline: (.*)\\n.*user(.*)"; - protected static final String CLOCK_PATTERN = "topic: /clock.*\\n.*secs: ([0-9]*).*nsecs: ([0-9]*)(.*)"; - private static final String GROUND_PATTERN = "topic: /calibration/ground_plane_error.*\\n.*data: \\[(.*)\\](.*)"; - private static final String CALIBRATION_PATTERN = "topic: /calibration/calibration_error.*\n.*data: \\[(.*)\\](.*)"; - protected String last_x; - protected String last_y; - private String last_w; - private int last_voltage = 0; - private double m_currentTime; - private double last_voltage_time; - private double last_charge = 0; - - /** - * Main Constructor the Gauge that is hardwired to the Probe. - * - * @param id - * the unique ID of the Gauge - * @param beaconPeriod - * the liveness beacon period of the Gauge - * @param gaugeDesc - * the type-name description of the Gauge - * @param modelDesc - * the type-name description of the Model the Gauge updates - * @param setupParams - * the list of setup parameters with their values - * @param mappings - * the list of Gauge Value to Model Property mappings - */ - public MissionStateGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern (LOC, Pattern.compile (LOC_PATTERN, Pattern.DOTALL)); - addPattern (CHARGE, Pattern.compile (CHARGE_PATTERN, Pattern.DOTALL)); - addPattern (DEADLINE, Pattern.compile (DEADLINE_PATTERN, Pattern.DOTALL)); - addPattern (CLOCK, Pattern.compile (CLOCK_PATTERN, Pattern.DOTALL)); - addPattern (GROUNDPLANE, Pattern.compile (GROUND_PATTERN, Pattern.DOTALL)); - addPattern (CALIBRATION_ERROR, Pattern.compile (CALIBRATION_PATTERN, Pattern.DOTALL)); - } - - @Override - protected void doMatch (String matchName, Matcher m) { - String group = m.group (1); - int restGroup = 0; - if (LOC.equals (matchName)) { - String x = group.trim (); - String y = m.group (2).trim (); - - String a = m.group (3).trim (); - String b = m.group (4).trim (); - String c = m.group (5).trim (); - String d = m.group (6).trim (); - restGroup = 7; - - String w = yawFromQuarternion (a, b, c, d); - log("Setting location to " + x + ", " + y); - if (locationDifferent (x, y, w)) { - IRainbowOperation op = m_commands.get ("location"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], x); - pMap.put (op.getParameters ()[1], y); - pMap.put (op.getParameters ()[2], w); - issueCommand (op, pMap); - } - } - else if (CHARGE.equals (matchName)) { - int voltage = Integer.parseInt (group); - - double charge = voltageToChargeConsiderTime (voltage); - - if (chargeDifferent (charge)) { -// double charge = voltage2Charge (voltage); - IRainbowOperation op = m_commands.get ("charge"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], Double.toString (charge)); - issueCommand (op, pMap); - } - restGroup = 2; - } - else if (DEADLINE.equals (matchName)) { - String date = m.group (1).trim (); - IRainbowOperation op = m_commands.get ("deadline"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], date); - issueCommand (op, pMap); - restGroup = 2; - } - else if (CLOCK.equals (matchName)) { - long secs = Long.parseLong (m.group (1).trim ()); - long nsecs = 0; - if (!"".equals (m.group (2).trim ())) { - nsecs = Long.parseLong (m.group (2).trim ()); - } - double realSecs = secs + TimeUnit.MILLISECONDS.convert (nsecs, TimeUnit.NANOSECONDS) / 1000.0; - m_currentTime = realSecs; - IRainbowOperation op = m_commands.get ("clock"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], Double.toString (realSecs)); - issueCommand (op, pMap); - restGroup = 3; - } - else if (GROUNDPLANE.equals (matchName)) { - String[] vals = m.group (1).split (","); - if (!numberCheck (vals)) { - log ("Got things that aren't numbers for ground plane " + vals.toString ()); - return; - } - IRainbowOperation op = m_commands.get ("ground-plane"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], vals[0]); - pMap.put (op.getParameters ()[1], vals[1]); - issueCommand (op, pMap); - restGroup = 2; - } - else if (CALIBRATION_ERROR.equals (matchName)) { - String[] vals = m.group (1).split (","); - if (!numberCheck (vals)) { - log ("Got things that aren't numbers for calibration " + vals.toString ()); - return; - } - IRainbowOperation op = m_commands.get ("calibration"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], vals[0]); - pMap.put (op.getParameters ()[1], vals[1]); - pMap.put (op.getParameters ()[2], vals[2]); - pMap.put (op.getParameters ()[3], vals[3]); - pMap.put (op.getParameters ()[4], vals[4]); - pMap.put (op.getParameters ()[5], vals[5]); - issueCommand (op, pMap); - restGroup = 4; - } - if (m.groupCount () == restGroup) { - String rest = m.group (restGroup); - if (!rest.isEmpty () && rest.indexOf ("topic:") != -1) { - log ("Gauge had more: " + rest.substring (rest.indexOf ("topic:"))); - } - } - } - - private boolean numberCheck (String[] vals) { - for (String s : vals) { - try { - Double.parseDouble (s); - } - catch (NumberFormatException e) { - return false; - } - } - return true; - } - - // Converstino to yaw from http://www.chrobotics.com/library/understanding-quaternions - private String yawFromQuarternion (String a, String b, String c, String d) { - double A = Double.parseDouble (a); - double B = Double.parseDouble (b); - double C = Double.parseDouble (c); - double D = Double.parseDouble (d); - - double w = Math.atan ((2 * (A * B + C * D)) / (A * A - B * B - C * C + D * D)); - return Double.toString (w); - - } - - private boolean chargeDifferent (double charge) { - if (Math.round (last_charge) != Math.round (charge)) { - last_charge = charge; - return true; - } - return false; - } - - private boolean voltageDifferent (int voltage) { - if (last_voltage != voltage) { - last_voltage_time = m_currentTime; - last_voltage = voltage; - return true; - } - return false; - } - - private double voltageToChargeConsiderTime (int voltage) { - voltageDifferent (voltage); - double estimatedCharge = PowerConverter.voltage2ChargeOpt (voltage) - - BatteryPredictor.batteryConsumption (MapTranslator.ROBOT_HALF_SPEED_CONST, - MapTranslator.ROBOT_LOC_MODE_MED_CONST, m_currentTime - last_voltage_time); - if (estimatedCharge < PowerConverter.voltage2ChargePess (voltage)) - return PowerConverter.voltage2ChargePess (voltage); - return estimatedCharge; - - } - - private boolean locationDifferent (String x, String y, String w) { - boolean different = !x.equals (last_x) || !y.equals (last_y) || !w.equals (last_w); - if (different) { - last_x = x; - last_y = y; - last_w = w; - } - return different; - } -} +package org.sa.rainbow.brass.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.brass.model.map.BatteryPredictor; +import org.sa.rainbow.brass.model.map.MapTranslator; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Created by schmerl on 12/28/2016. + */ +public class MissionStateGauge extends RegularPatternGauge { + private static final String NAME = "Mission State Gauge"; + protected static final String LOC = "LocationRecording"; + protected static final String CHARGE = "BatteryCharge"; + protected static final String DEADLINE = "Deadline"; + protected static final String CLOCK = "Clock"; + protected static final String GROUNDPLANE = "GroundPlane"; + protected static final String CALIBRATION_ERROR = "Calibration"; + + protected static final String LOC_PATTERN = "topic: /amcl_pose/pose/pose.*position.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z.*\\norientation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z: (.*)\\n.*w: (.*)(.*)"; + protected static final String CHARGE_PATTERN = "topic: /energy_monitor/voltage.*\\n.*data: (.*)\\n(.*)"; + protected static final String DEADLINE_PATTERN = "topic: /notify_user.*\\n.*new_deadline: (.*)\\n.*user(.*)"; + protected static final String CLOCK_PATTERN = "topic: /clock.*\\n.*secs: ([0-9]*).*nsecs: ([0-9]*)(.*)"; + private static final String GROUND_PATTERN = "topic: /calibration/ground_plane_error.*\\n.*data: \\[(.*)\\](.*)"; + private static final String CALIBRATION_PATTERN = "topic: /calibration/calibration_error.*\n.*data: \\[(.*)\\](.*)"; + protected String last_x; + protected String last_y; + private String last_w; + private int last_voltage = 0; + private double m_currentTime; + private double last_voltage_time; + private double last_charge = 0; + + /** + * Main Constructor the Gauge that is hardwired to the Probe. + * + * @param id + * the unique ID of the Gauge + * @param beaconPeriod + * the liveness beacon period of the Gauge + * @param gaugeDesc + * the type-name description of the Gauge + * @param modelDesc + * the type-name description of the Model the Gauge updates + * @param setupParams + * the list of setup parameters with their values + * @param mappings + * the list of Gauge Value to Model Property mappings + */ + public MissionStateGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern (LOC, Pattern.compile (LOC_PATTERN, Pattern.DOTALL)); + addPattern (CHARGE, Pattern.compile (CHARGE_PATTERN, Pattern.DOTALL)); + addPattern (DEADLINE, Pattern.compile (DEADLINE_PATTERN, Pattern.DOTALL)); + addPattern (CLOCK, Pattern.compile (CLOCK_PATTERN, Pattern.DOTALL)); + addPattern (GROUNDPLANE, Pattern.compile (GROUND_PATTERN, Pattern.DOTALL)); + addPattern (CALIBRATION_ERROR, Pattern.compile (CALIBRATION_PATTERN, Pattern.DOTALL)); + } + + @Override + protected void doMatch (String matchName, Matcher m) { + String group = m.group (1); + int restGroup = 0; + if (LOC.equals (matchName)) { + String x = group.trim (); + String y = m.group (2).trim (); + + String a = m.group (3).trim (); + String b = m.group (4).trim (); + String c = m.group (5).trim (); + String d = m.group (6).trim (); + restGroup = 7; + + String w = yawFromQuarternion (a, b, c, d); + log("Setting location to " + x + ", " + y); + if (locationDifferent (x, y, w)) { + IRainbowOperation op = m_commands.get ("location"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], x); + pMap.put (op.getParameters ()[1], y); + pMap.put (op.getParameters ()[2], w); + issueCommand (op, pMap); + } + } + else if (CHARGE.equals (matchName)) { + int voltage = Integer.parseInt (group); + + double charge = voltageToChargeConsiderTime (voltage); + + if (chargeDifferent (charge)) { +// double charge = voltage2Charge (voltage); + IRainbowOperation op = m_commands.get ("charge"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], Double.toString (charge)); + issueCommand (op, pMap); + } + restGroup = 2; + } + else if (DEADLINE.equals (matchName)) { + String date = m.group (1).trim (); + IRainbowOperation op = m_commands.get ("deadline"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], date); + issueCommand (op, pMap); + restGroup = 2; + } + else if (CLOCK.equals (matchName)) { + long secs = Long.parseLong (m.group (1).trim ()); + long nsecs = 0; + if (!"".equals (m.group (2).trim ())) { + nsecs = Long.parseLong (m.group (2).trim ()); + } + double realSecs = secs + TimeUnit.MILLISECONDS.convert (nsecs, TimeUnit.NANOSECONDS) / 1000.0; + m_currentTime = realSecs; + IRainbowOperation op = m_commands.get ("clock"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], Double.toString (realSecs)); + issueCommand (op, pMap); + restGroup = 3; + } + else if (GROUNDPLANE.equals (matchName)) { + String[] vals = m.group (1).split (","); + if (!numberCheck (vals)) { + log ("Got things that aren't numbers for ground plane " + vals.toString ()); + return; + } + IRainbowOperation op = m_commands.get ("ground-plane"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], vals[0]); + pMap.put (op.getParameters ()[1], vals[1]); + issueCommand (op, pMap); + restGroup = 2; + } + else if (CALIBRATION_ERROR.equals (matchName)) { + String[] vals = m.group (1).split (","); + if (!numberCheck (vals)) { + log ("Got things that aren't numbers for calibration " + vals.toString ()); + return; + } + IRainbowOperation op = m_commands.get ("calibration"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], vals[0]); + pMap.put (op.getParameters ()[1], vals[1]); + pMap.put (op.getParameters ()[2], vals[2]); + pMap.put (op.getParameters ()[3], vals[3]); + pMap.put (op.getParameters ()[4], vals[4]); + pMap.put (op.getParameters ()[5], vals[5]); + issueCommand (op, pMap); + restGroup = 4; + } + if (m.groupCount () == restGroup) { + String rest = m.group (restGroup); + if (!rest.isEmpty () && rest.indexOf ("topic:") != -1) { + log ("Gauge had more: " + rest.substring (rest.indexOf ("topic:"))); + } + } + } + + private boolean numberCheck (String[] vals) { + for (String s : vals) { + try { + Double.parseDouble (s); + } + catch (NumberFormatException e) { + return false; + } + } + return true; + } + + // Converstino to yaw from http://www.chrobotics.com/library/understanding-quaternions + private String yawFromQuarternion (String a, String b, String c, String d) { + double A = Double.parseDouble (a); + double B = Double.parseDouble (b); + double C = Double.parseDouble (c); + double D = Double.parseDouble (d); + + double w = Math.atan ((2 * (A * B + C * D)) / (A * A - B * B - C * C + D * D)); + return Double.toString (w); + + } + + private boolean chargeDifferent (double charge) { + if (Math.round (last_charge) != Math.round (charge)) { + last_charge = charge; + return true; + } + return false; + } + + private boolean voltageDifferent (int voltage) { + if (last_voltage != voltage) { + last_voltage_time = m_currentTime; + last_voltage = voltage; + return true; + } + return false; + } + + private double voltageToChargeConsiderTime (int voltage) { + voltageDifferent (voltage); + double estimatedCharge = PowerConverter.voltage2ChargeOpt (voltage) + - BatteryPredictor.batteryConsumption (MapTranslator.ROBOT_HALF_SPEED_CONST, + MapTranslator.ROBOT_LOC_MODE_MED_CONST, m_currentTime - last_voltage_time); + if (estimatedCharge < PowerConverter.voltage2ChargePess (voltage)) + return PowerConverter.voltage2ChargePess (voltage); + return estimatedCharge; + + } + + private boolean locationDifferent (String x, String y, String w) { + boolean different = !x.equals (last_x) || !y.equals (last_y) || !w.equals (last_w); + if (different) { + last_x = x; + last_y = y; + last_w = w; + } + return different; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/acme/ROS2Acme.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/acme/ROS2Acme.java index e5c14f210..84cd6b2b6 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/acme/ROS2Acme.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/acme/ROS2Acme.java @@ -1,247 +1,247 @@ -package org.sa.rainbow.brass.gauges.acme; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Writer; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.acmestudio.acme.model.util.UMSystem; -import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; -import org.ho.yaml.Yaml; - -import net.sourceforge.argparse4j.ArgumentParsers; -import net.sourceforge.argparse4j.impl.Arguments; -import net.sourceforge.argparse4j.inf.ArgumentParser; -import net.sourceforge.argparse4j.inf.ArgumentParserException; -import net.sourceforge.argparse4j.inf.Namespace; - -public class ROS2Acme { - - private Integer m_rate; - private Integer m_keep; - private String m_outputFileName; - private Boolean m_once; - private String m_dataFileName; - private Set m_ignoreNodes; - private Set m_ignoreTopics; - private Set m_ignoreServices; - private Set m_ignoreActions; - private Path m_shellScript; - - public static void main(String[] a) { - ArgumentParser parser = ArgumentParsers.newFor("ROS2Acme").build() - .description("Process ROS data into Acme instance"); - parser.addArgument("-n", "--ignore-nodes").type(String.class).nargs("+").help("Ignore the following ROS nodes"); - parser.addArgument("-t", "--ignore-topics").type(String.class).nargs("+").help("Ignore these topics"); - parser.addArgument("-s", "--ignore-services").type(String.class).nargs("+").help("Ignore these services"); - parser.addArgument("-a", "--ignore-actions").type(String.class).nargs("+").help("Ignore these actions"); - parser.addArgument("-i", "--ignore").type(String.class) - .help("The YAML file containing sections of things to ignore"); - parser.addArgument("-r", "--rate").type(Integer.class).setDefault(10) - .help("NOT IMPLEMENTED - The loop rate (in seconds)"); - parser.addArgument("-1", "--once").action(Arguments.storeTrue()).help("Only do this once"); - parser.addArgument("-d", "--data").type(String.class).help("Take the ROS information from this file"); - parser.addArgument("-k", "--keep").type(Integer.class).setDefault(10) - .help("NOT IMPLEMENTED - The number of versions of the Acme file to keep"); - parser.addArgument("output").help( - "The Acme file to produce (this file will hold the most recent description; if -1 is not specified then the files will be numbered 0..keep, where 0 is the oldest)"); - - try { - Namespace args = parser.parseArgs(a); - - ROS2Acme r2a = new ROS2Acme(); - r2a.processSeperateIgnores(args); - String ini = args.getString("ignore"); - if (ini != null) { - File ignoreFile = new File(ini); - Map configData = (Map) Yaml.load(ignoreFile); - Map ignores = (Map) configData.get("ignorance"); - r2a.processIgnores(ignores); - } - r2a.setRate(args.getInt("rate")); - r2a.setKeep(args.getInt("keep")); - r2a.setOutputFileName(args.getString("output")); - r2a.setOnlyOnce(args.getBoolean("once")); - r2a.setInputFileName(args.getString("data")); - - r2a.produceArch(); - - } catch (ArgumentParserException e) { - parser.handleError(e); - System.exit(1); - } catch (FileNotFoundException e) { - System.err.println("The specified ignore file does not exist"); - System.err.println(e.getMessage()); - System.exit(1); - } catch (IOException e) { - System.err.println("There was an error reading the data file"); - System.err.println(e.getMessage()); - System.exit(1); - } - } - - private void produceArch() throws IOException { - ROSToAcmeTranslator r2a = new ROSToAcmeTranslator(); - r2a.setIgnorance(m_ignoreNodes, m_ignoreTopics, m_ignoreServices, m_ignoreActions); - boolean stop = false; - - if (m_once) { - generateToAcmeFile(r2a, m_outputFileName); - } else { - long startTime = new Date().getTime(); - - generateToAcmeFile(r2a, m_outputFileName); - sleepForRate(stop, startTime); - - Path path = Paths.get(m_outputFileName); - int dot = path.getFileName().toString().lastIndexOf("."); - String stem = path.getFileName().toString(); - String ext = ""; - if (dot > 0) { - stem = stem.substring(0, dot - 1); - ext = stem.substring(dot, stem.length()); - } - while (!stop) { - startTime = new Date().getTime(); - for (int i = m_keep - 1; i > 0; i--) { - Path kp = Paths.get(Paths.get(m_outputFileName).getParent().toString(), stem + i + ext); - if (Files.exists(kp)) { - Files.move(kp, - Paths.get(Paths.get(m_outputFileName).getParent().toString(), stem + (i + 1) + ext)); - } - } - generateToAcmeFile(r2a, m_outputFileName); - sleepForRate(stop, startTime); - } - } - } - - private void sleepForRate(boolean stop, long startTime) { - long endTime = new Date().getTime(); - long sleep = m_rate * 1000 - (endTime - startTime); - if (sleep > 0 && !stop) - try { - Thread.sleep(sleep); - } catch (InterruptedException e) { - } - } - - private void generateToAcmeFile(ROSToAcmeTranslator r2a, String outputFileName) throws IOException { - if (m_dataFileName != null) { - StringBuffer data = new StringBuffer(); - Files.readAllLines(Paths.get(m_dataFileName)).forEach(l -> { - data.append(l).append("\n"); - }); - UMSystem system = r2a.processROSDataToNewSystem(data.toString()); - String acme = StandaloneLanguagePackHelper.defaultLanguageHelper().elementToString(system, null); - Files.write(Paths.get(outputFileName), acme.getBytes()); - } else { - if (m_shellScript == null || !Files.exists(m_shellScript.toAbsolutePath())) - createROSShellScript(); - try { - ProcessBuilder pb = new ProcessBuilder("bash", m_shellScript.toString()); - pb.inheritIO(); - Process process = pb.start(); - process.waitFor(); - StringBuffer b = new StringBuffer(); - BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream())); - String s; - while ((s = r.readLine()) != null) { - b.append(s); - b.append("\n"); - } - UMSystem system = r2a.processROSDataToNewSystem(b.toString()); - String acme = StandaloneLanguagePackHelper.defaultLanguageHelper().elementToString(system, null); - Files.write(Paths.get(outputFileName), acme.getBytes()); - } catch (InterruptedException e) { - } - - } - } - - private void createROSShellScript() throws IOException { - m_shellScript = Files.createTempFile("script", ".sh"); - Writer streamWriter = new OutputStreamWriter(new FileOutputStream(m_shellScript.toFile())); - PrintWriter printWriter = new PrintWriter(streamWriter); - - printWriter.println("#!/bin/bash"); - printWriter.println("nodes=$(rosnode list)"); - printWriter.println("for n in $nodes; do rosnode info $n; done"); - printWriter.close(); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private void processIgnores(Map ignores) { - List nodes = (List) ignores.get("nodes"); - if (nodes != null) { - this.m_ignoreNodes.addAll(nodes); - nodes.forEach(a -> m_ignoreNodes.add("/" + a)); - } - - List topics = (List) ignores.get("topics"); - if (topics != null) { - this.m_ignoreTopics.addAll(topics); - } - - List services = (List) ignores.get("services"); - if (services != null) - this.m_ignoreServices.addAll(services); - - List actions = (List) ignores.get("actions"); - if (actions != null) - this.m_ignoreActions.addAll(actions); - } - - private void processSeperateIgnores(Namespace args) { - m_ignoreNodes = new HashSet(); - m_ignoreTopics = new HashSet(); - m_ignoreServices = new HashSet(); - m_ignoreActions = new HashSet(); - - List n = args.getList("ignore-nodes"); - if (n != null) - m_ignoreNodes.addAll(n); - List t = args.getList("ignore-topics"); - if (t != null) - m_ignoreTopics.addAll(t); - List s = args.getList("ignore-services"); - if (s != null) - m_ignoreServices.addAll(s); - List a = args.getList("ignore-actions"); - if (a != null) - m_ignoreActions.addAll(a); - } - - private void setInputFileName(String dataFileName) { - m_dataFileName = dataFileName; - } - - private void setOnlyOnce(Boolean once) { - m_once = once; - } - - private void setOutputFileName(String outputFileName) { - m_outputFileName = outputFileName; - } - - private void setKeep(Integer keep) { - m_keep = keep; - } - - private void setRate(Integer rate) { - this.m_rate = rate; - } -} +package org.sa.rainbow.brass.gauges.acme; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.acmestudio.acme.model.util.UMSystem; +import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; +import org.ho.yaml.Yaml; + +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.impl.Arguments; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; + +public class ROS2Acme { + + private Integer m_rate; + private Integer m_keep; + private String m_outputFileName; + private Boolean m_once; + private String m_dataFileName; + private Set m_ignoreNodes; + private Set m_ignoreTopics; + private Set m_ignoreServices; + private Set m_ignoreActions; + private Path m_shellScript; + + public static void main(String[] a) { + ArgumentParser parser = ArgumentParsers.newFor("ROS2Acme").build() + .description("Process ROS data into Acme instance"); + parser.addArgument("-n", "--ignore-nodes").type(String.class).nargs("+").help("Ignore the following ROS nodes"); + parser.addArgument("-t", "--ignore-topics").type(String.class).nargs("+").help("Ignore these topics"); + parser.addArgument("-s", "--ignore-services").type(String.class).nargs("+").help("Ignore these services"); + parser.addArgument("-a", "--ignore-actions").type(String.class).nargs("+").help("Ignore these actions"); + parser.addArgument("-i", "--ignore").type(String.class) + .help("The YAML file containing sections of things to ignore"); + parser.addArgument("-r", "--rate").type(Integer.class).setDefault(10) + .help("NOT IMPLEMENTED - The loop rate (in seconds)"); + parser.addArgument("-1", "--once").action(Arguments.storeTrue()).help("Only do this once"); + parser.addArgument("-d", "--data").type(String.class).help("Take the ROS information from this file"); + parser.addArgument("-k", "--keep").type(Integer.class).setDefault(10) + .help("NOT IMPLEMENTED - The number of versions of the Acme file to keep"); + parser.addArgument("output").help( + "The Acme file to produce (this file will hold the most recent description; if -1 is not specified then the files will be numbered 0..keep, where 0 is the oldest)"); + + try { + Namespace args = parser.parseArgs(a); + + ROS2Acme r2a = new ROS2Acme(); + r2a.processSeperateIgnores(args); + String ini = args.getString("ignore"); + if (ini != null) { + File ignoreFile = new File(ini); + Map configData = (Map) Yaml.load(ignoreFile); + Map ignores = (Map) configData.get("ignorance"); + r2a.processIgnores(ignores); + } + r2a.setRate(args.getInt("rate")); + r2a.setKeep(args.getInt("keep")); + r2a.setOutputFileName(args.getString("output")); + r2a.setOnlyOnce(args.getBoolean("once")); + r2a.setInputFileName(args.getString("data")); + + r2a.produceArch(); + + } catch (ArgumentParserException e) { + parser.handleError(e); + System.exit(1); + } catch (FileNotFoundException e) { + System.err.println("The specified ignore file does not exist"); + System.err.println(e.getMessage()); + System.exit(1); + } catch (IOException e) { + System.err.println("There was an error reading the data file"); + System.err.println(e.getMessage()); + System.exit(1); + } + } + + private void produceArch() throws IOException { + ROSToAcmeTranslator r2a = new ROSToAcmeTranslator(); + r2a.setIgnorance(m_ignoreNodes, m_ignoreTopics, m_ignoreServices, m_ignoreActions); + boolean stop = false; + + if (m_once) { + generateToAcmeFile(r2a, m_outputFileName); + } else { + long startTime = new Date().getTime(); + + generateToAcmeFile(r2a, m_outputFileName); + sleepForRate(stop, startTime); + + Path path = Paths.get(m_outputFileName); + int dot = path.getFileName().toString().lastIndexOf("."); + String stem = path.getFileName().toString(); + String ext = ""; + if (dot > 0) { + stem = stem.substring(0, dot - 1); + ext = stem.substring(dot, stem.length()); + } + while (!stop) { + startTime = new Date().getTime(); + for (int i = m_keep - 1; i > 0; i--) { + Path kp = Paths.get(Paths.get(m_outputFileName).getParent().toString(), stem + i + ext); + if (Files.exists(kp)) { + Files.move(kp, + Paths.get(Paths.get(m_outputFileName).getParent().toString(), stem + (i + 1) + ext)); + } + } + generateToAcmeFile(r2a, m_outputFileName); + sleepForRate(stop, startTime); + } + } + } + + private void sleepForRate(boolean stop, long startTime) { + long endTime = new Date().getTime(); + long sleep = m_rate * 1000 - (endTime - startTime); + if (sleep > 0 && !stop) + try { + Thread.sleep(sleep); + } catch (InterruptedException e) { + } + } + + private void generateToAcmeFile(ROSToAcmeTranslator r2a, String outputFileName) throws IOException { + if (m_dataFileName != null) { + StringBuffer data = new StringBuffer(); + Files.readAllLines(Paths.get(m_dataFileName)).forEach(l -> { + data.append(l).append("\n"); + }); + UMSystem system = r2a.processROSDataToNewSystem(data.toString()); + String acme = StandaloneLanguagePackHelper.defaultLanguageHelper().elementToString(system, null); + Files.write(Paths.get(outputFileName), acme.getBytes()); + } else { + if (m_shellScript == null || !Files.exists(m_shellScript.toAbsolutePath())) + createROSShellScript(); + try { + ProcessBuilder pb = new ProcessBuilder("bash", m_shellScript.toString()); + pb.inheritIO(); + Process process = pb.start(); + process.waitFor(); + StringBuffer b = new StringBuffer(); + BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream())); + String s; + while ((s = r.readLine()) != null) { + b.append(s); + b.append("\n"); + } + UMSystem system = r2a.processROSDataToNewSystem(b.toString()); + String acme = StandaloneLanguagePackHelper.defaultLanguageHelper().elementToString(system, null); + Files.write(Paths.get(outputFileName), acme.getBytes()); + } catch (InterruptedException e) { + } + + } + } + + private void createROSShellScript() throws IOException { + m_shellScript = Files.createTempFile("script", ".sh"); + Writer streamWriter = new OutputStreamWriter(new FileOutputStream(m_shellScript.toFile())); + PrintWriter printWriter = new PrintWriter(streamWriter); + + printWriter.println("#!/bin/bash"); + printWriter.println("nodes=$(rosnode list)"); + printWriter.println("for n in $nodes; do rosnode info $n; done"); + printWriter.close(); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void processIgnores(Map ignores) { + List nodes = (List) ignores.get("nodes"); + if (nodes != null) { + this.m_ignoreNodes.addAll(nodes); + nodes.forEach(a -> m_ignoreNodes.add("/" + a)); + } + + List topics = (List) ignores.get("topics"); + if (topics != null) { + this.m_ignoreTopics.addAll(topics); + } + + List services = (List) ignores.get("services"); + if (services != null) + this.m_ignoreServices.addAll(services); + + List actions = (List) ignores.get("actions"); + if (actions != null) + this.m_ignoreActions.addAll(actions); + } + + private void processSeperateIgnores(Namespace args) { + m_ignoreNodes = new HashSet(); + m_ignoreTopics = new HashSet(); + m_ignoreServices = new HashSet(); + m_ignoreActions = new HashSet(); + + List n = args.getList("ignore-nodes"); + if (n != null) + m_ignoreNodes.addAll(n); + List t = args.getList("ignore-topics"); + if (t != null) + m_ignoreTopics.addAll(t); + List s = args.getList("ignore-services"); + if (s != null) + m_ignoreServices.addAll(s); + List a = args.getList("ignore-actions"); + if (a != null) + m_ignoreActions.addAll(a); + } + + private void setInputFileName(String dataFileName) { + m_dataFileName = dataFileName; + } + + private void setOnlyOnce(Boolean once) { + m_once = once; + } + + private void setOutputFileName(String outputFileName) { + m_outputFileName = outputFileName; + } + + private void setKeep(Integer keep) { + m_keep = keep; + } + + private void setRate(Integer rate) { + this.m_rate = rate; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp1/MissionStateGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp1/MissionStateGauge.java index c2fc58d95..ef3f8693a 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp1/MissionStateGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp1/MissionStateGauge.java @@ -1,126 +1,126 @@ -package org.sa.rainbow.brass.gauges.p2_cp1; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.brass.model.map.BatteryPredictor; -import org.sa.rainbow.brass.model.map.MapTranslator; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.translator.probes.IProbeIdentifier; - -/** - * Created by schmerl on 12/28/2016. - */ -public class MissionStateGauge extends RegularPatternGauge { - private static final String NAME = "Mission State Gauge"; - protected static final String LOC = "LocationRecording"; - - protected static final String LOC_PATTERN = "topic: /amcl_pose/pose/pose.*position.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z.*\\norientation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z: (.*)\\n.*w: (.*)(.*)"; - protected String last_x; - protected String last_y; - private String last_w; - - /** - * Main Constructor the Gauge that is hardwired to the Probe. - * - * @param id - * the unique ID of the Gauge - * @param beaconPeriod - * the liveness beacon period of the Gauge - * @param gaugeDesc - * the type-name description of the Gauge - * @param modelDesc - * the type-name description of the Model the Gauge updates - * @param setupParams - * the list of setup parameters with their values - * @param mappings - * the list of Gauge Value to Model Property mappings - */ - public MissionStateGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern (LOC, Pattern.compile (LOC_PATTERN, Pattern.DOTALL)); - } - - @Override - protected void doMatch (String matchName, Matcher m) { - String group = m.group (1); - int restGroup = 0; - if (LOC.equals (matchName)) { - String x = group.trim (); - String y = m.group (2).trim (); - - String a = m.group (3).trim (); - String b = m.group (4).trim (); - String c = m.group (5).trim (); - String d = m.group (6).trim (); - restGroup = 7; - - String w = yawFromQuarternion (a, b, c, d); - - if (locationDifferent (x, y, w)) { - IRainbowOperation op = m_commands.get ("location"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], x); - pMap.put (op.getParameters ()[1], y); - pMap.put (op.getParameters ()[2], w); - issueCommand (op, pMap); - } - } - if (m.groupCount () == restGroup) { - String rest = m.group (restGroup); - if (!rest.isEmpty () && rest.indexOf ("topic:") != -1) { - log ("Gauge had more: " + rest.substring (rest.indexOf ("topic:"))); - } - } - } - - @Override - public void reportFromProbe(IProbeIdentifier probe, String data) { - // TODO Auto-generated method stub - super.reportFromProbe(probe, data); - } - - private boolean numberCheck (String[] vals) { - for (String s : vals) { - try { - Double.parseDouble (s); - } - catch (NumberFormatException e) { - return false; - } - } - return true; - } - - // Converstino to yaw from http://www.chrobotics.com/library/understanding-quaternions - private String yawFromQuarternion (String a, String b, String c, String d) { - double A = Double.parseDouble (a); - double B = Double.parseDouble (b); - double C = Double.parseDouble (c); - double D = Double.parseDouble (d); - - double w = Math.atan ((2 * (A * B + C * D)) / (A * A - B * B - C * C + D * D)); - return Double.toString (w); - - } - - private boolean locationDifferent (String x, String y, String w) { - boolean different = !x.equals (last_x) || !y.equals (last_y) || !w.equals (last_w); - if (different) { - last_x = x; - last_y = y; - last_w = w; - } - return different; - } -} +package org.sa.rainbow.brass.gauges.p2_cp1; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.brass.model.map.BatteryPredictor; +import org.sa.rainbow.brass.model.map.MapTranslator; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.translator.probes.IProbeIdentifier; + +/** + * Created by schmerl on 12/28/2016. + */ +public class MissionStateGauge extends RegularPatternGauge { + private static final String NAME = "Mission State Gauge"; + protected static final String LOC = "LocationRecording"; + + protected static final String LOC_PATTERN = "topic: /amcl_pose/pose/pose.*position.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z.*\\norientation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z: (.*)\\n.*w: (.*)(.*)"; + protected String last_x; + protected String last_y; + private String last_w; + + /** + * Main Constructor the Gauge that is hardwired to the Probe. + * + * @param id + * the unique ID of the Gauge + * @param beaconPeriod + * the liveness beacon period of the Gauge + * @param gaugeDesc + * the type-name description of the Gauge + * @param modelDesc + * the type-name description of the Model the Gauge updates + * @param setupParams + * the list of setup parameters with their values + * @param mappings + * the list of Gauge Value to Model Property mappings + */ + public MissionStateGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern (LOC, Pattern.compile (LOC_PATTERN, Pattern.DOTALL)); + } + + @Override + protected void doMatch (String matchName, Matcher m) { + String group = m.group (1); + int restGroup = 0; + if (LOC.equals (matchName)) { + String x = group.trim (); + String y = m.group (2).trim (); + + String a = m.group (3).trim (); + String b = m.group (4).trim (); + String c = m.group (5).trim (); + String d = m.group (6).trim (); + restGroup = 7; + + String w = yawFromQuarternion (a, b, c, d); + + if (locationDifferent (x, y, w)) { + IRainbowOperation op = m_commands.get ("location"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], x); + pMap.put (op.getParameters ()[1], y); + pMap.put (op.getParameters ()[2], w); + issueCommand (op, pMap); + } + } + if (m.groupCount () == restGroup) { + String rest = m.group (restGroup); + if (!rest.isEmpty () && rest.indexOf ("topic:") != -1) { + log ("Gauge had more: " + rest.substring (rest.indexOf ("topic:"))); + } + } + } + + @Override + public void reportFromProbe(IProbeIdentifier probe, String data) { + // TODO Auto-generated method stub + super.reportFromProbe(probe, data); + } + + private boolean numberCheck (String[] vals) { + for (String s : vals) { + try { + Double.parseDouble (s); + } + catch (NumberFormatException e) { + return false; + } + } + return true; + } + + // Converstino to yaw from http://www.chrobotics.com/library/understanding-quaternions + private String yawFromQuarternion (String a, String b, String c, String d) { + double A = Double.parseDouble (a); + double B = Double.parseDouble (b); + double C = Double.parseDouble (c); + double D = Double.parseDouble (d); + + double w = Math.atan ((2 * (A * B + C * D)) / (A * A - B * B - C * C + D * D)); + return Double.toString (w); + + } + + private boolean locationDifferent (String x, String y, String w) { + boolean different = !x.equals (last_x) || !y.equals (last_y) || !w.equals (last_w); + if (different) { + last_x = x; + last_y = y; + last_w = w; + } + return different; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp1/RobotStateGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp1/RobotStateGauge.java index e21930bff..c5ce9c0a8 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp1/RobotStateGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp1/RobotStateGauge.java @@ -1,70 +1,70 @@ -package org.sa.rainbow.brass.gauges.p2_cp1; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -public class RobotStateGauge extends RegularPatternGauge { - private static final String NAME = "Robot State Gauge"; - protected static final String CHARGE = "BatteryCharge"; - protected static final String SPEED = "Speed"; - protected static final String CONFIG = "Config"; - - protected static final String CHARGE_PATTERN = "topic: /mobile_base/commands/charge_level.*\\n.*data: (.*)"; - protected static final String CONFIG_PATTERN = "cp1 configuration: (.*)"; - private double last_charge = 0; - private String last_config = ""; - - public RobotStateGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern(CHARGE, Pattern.compile(CHARGE_PATTERN, Pattern.DOTALL)); - addPattern(CONFIG, Pattern.compile(CONFIG_PATTERN)); - } - - @Override - protected void doMatch(String matchName, Matcher m) { - if (CHARGE.equals (matchName)) { - double charge = Double.parseDouble(m.group(1).trim()); - - if (chargeDifferent (charge)) { - IRainbowOperation op = m_commands.get ("charge"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], Double.toString (charge)); - issueCommand (op, pMap); - } - } - else if (CONFIG.equals(matchName)) { - String config = m.group(1).trim(); - - if (!last_config.equals(config)) { - last_config = config; - IRainbowOperation op = m_commands.get("config"); - Map pMap = new HashMap<>(); - pMap.put(op.getParameters()[0], config); - issueCommand(op, pMap); - } - } - } - - private boolean chargeDifferent (double charge) { - if (Math.round (last_charge) != Math.round (charge)) { - last_charge = charge; - return true; - } - return false; - } - - protected boolean shouldProcess() { - return !isRainbowAdapting(); - }; -} +package org.sa.rainbow.brass.gauges.p2_cp1; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +public class RobotStateGauge extends RegularPatternGauge { + private static final String NAME = "Robot State Gauge"; + protected static final String CHARGE = "BatteryCharge"; + protected static final String SPEED = "Speed"; + protected static final String CONFIG = "Config"; + + protected static final String CHARGE_PATTERN = "topic: /mobile_base/commands/charge_level.*\\n.*data: (.*)"; + protected static final String CONFIG_PATTERN = "cp1 configuration: (.*)"; + private double last_charge = 0; + private String last_config = ""; + + public RobotStateGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern(CHARGE, Pattern.compile(CHARGE_PATTERN, Pattern.DOTALL)); + addPattern(CONFIG, Pattern.compile(CONFIG_PATTERN)); + } + + @Override + protected void doMatch(String matchName, Matcher m) { + if (CHARGE.equals (matchName)) { + double charge = Double.parseDouble(m.group(1).trim()); + + if (chargeDifferent (charge)) { + IRainbowOperation op = m_commands.get ("charge"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], Double.toString (charge)); + issueCommand (op, pMap); + } + } + else if (CONFIG.equals(matchName)) { + String config = m.group(1).trim(); + + if (!last_config.equals(config)) { + last_config = config; + IRainbowOperation op = m_commands.get("config"); + Map pMap = new HashMap<>(); + pMap.put(op.getParameters()[0], config); + issueCommand(op, pMap); + } + } + } + + private boolean chargeDifferent (double charge) { + if (Math.round (last_charge) != Math.round (charge)) { + last_charge = charge; + return true; + } + return false; + } + + protected boolean shouldProcess() { + return !isRainbowAdapting(); + }; +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/ArchitectureGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/ArchitectureGauge.java index f232ffdf5..3f77e397e 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/ArchitectureGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/ArchitectureGauge.java @@ -1,132 +1,132 @@ -package org.sa.rainbow.brass.gauges.p2_cp3; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.sa.rainbow.brass.model.p2_cp3.CP3ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.ICP3ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.acme.TurtlebotModelInstance.ActiveT; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.AbstractGaugeWithProbes; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IModelsManagerPort; -import org.sa.rainbow.core.ports.RainbowPortFactory; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.translator.probes.IProbeIdentifier; - -public class ArchitectureGauge extends AbstractGaugeWithProbes { - - Set m_nodesFromProbes = new HashSet<> (); - - Set m_currentlyActiveNodes = new HashSet<> (); - - boolean m_reconfiguring = false; - - private Map m_nodeToArch; - private boolean m_newReport = false; - - private Boolean m_adapting = false; - - private IModelsManagerPort m_modelsPort; - - private ICP3ModelAccessor m_models; - - public ArchitectureGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, - TypedAttribute modelDesc, List setupParams, - Map mappings) throws RainbowException { - super("Architecture Gauge", id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - } - - @Override - public void reportFromProbe(IProbeIdentifier probe, String data) { - super.reportFromProbe(probe, data); -// if (isRainbowAdapting()) return; - synchronized (m_nodesFromProbes) { - m_nodesFromProbes.clear(); - String[] nodes = data.split("\\s+"); - m_nodesFromProbes.addAll(Arrays.asList(nodes)); - m_newReport = true; - } - } - - @Override - protected void handleConfigParam(TypedAttributeWithValue tav) { - super.handleConfigParam(tav); - - } - - @Override - protected void runAction() { - if (m_models == null) { - try { - m_modelsPort = RainbowPortFactory.createModelsManagerRequirerPort(); - m_models = new CP3ModelAccessor(m_modelsPort); - } catch (RainbowConnectionException e) { - e.printStackTrace(); - } - } - super.runAction(); - - if (/*isRainbowAdapting() || */!m_newReport) return; - if (m_nodeToArch == null) { - m_nodeToArch = new HashMap<> (); - String mapping = getSetupValue("mapping", String.class); - String[] mappings = mapping.split(","); - for (String m : mappings) { - String[] map = m.split("="); - m_nodeToArch.put(map[0].trim(), map[1].trim()); - } - } - HashSet newNodes = new HashSet (); - HashSet goneNodes = new HashSet (); - synchronized (m_nodesFromProbes) { - newNodes.addAll(m_nodesFromProbes); - newNodes.removeAll(m_currentlyActiveNodes); - - goneNodes.addAll(m_currentlyActiveNodes); - goneNodes.removeAll(m_nodesFromProbes); - - m_currentlyActiveNodes.clear(); - m_currentlyActiveNodes.addAll(m_nodesFromProbes); - m_newReport = false; - } - - List ops = new LinkedList<> (); - List> params = new LinkedList<>(); - - for (String n : newNodes) { - IRainbowOperation op = getCommand("set-active"); - Map p = new HashMap<> (); - String comp = m_nodeToArch.get(n); - if (comp != null) { - p.put(op.getTarget(), comp); - p.put(op.getParameters()[0], ActiveT.ACTIVE.name()); - ops.add(op); - params.add(p); - } - } - String active = m_models.getMissionStateModel().getModelInstance().isReconfiguring()?ActiveT.INACTIVE.name():ActiveT.FAILED.name(); - - for (String n : goneNodes) { - IRainbowOperation op = getCommand("set-active"); - Map p = new HashMap<>(); - String comp = m_nodeToArch.get(n); - if (comp != null) { - p.put(op.getTarget(), comp); - p.put(op.getParameters()[0], active); - ops.add(op); - params.add(p); - } - } - if (!ops.isEmpty()) - issueCommands(ops, params); - } - -} +package org.sa.rainbow.brass.gauges.p2_cp3; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.sa.rainbow.brass.model.p2_cp3.CP3ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.ICP3ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.acme.TurtlebotModelInstance.ActiveT; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.AbstractGaugeWithProbes; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.translator.probes.IProbeIdentifier; + +public class ArchitectureGauge extends AbstractGaugeWithProbes { + + Set m_nodesFromProbes = new HashSet<> (); + + Set m_currentlyActiveNodes = new HashSet<> (); + + boolean m_reconfiguring = false; + + private Map m_nodeToArch; + private boolean m_newReport = false; + + private Boolean m_adapting = false; + + private IModelsManagerPort m_modelsPort; + + private ICP3ModelAccessor m_models; + + public ArchitectureGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, + TypedAttribute modelDesc, List setupParams, + Map mappings) throws RainbowException { + super("Architecture Gauge", id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + } + + @Override + public void reportFromProbe(IProbeIdentifier probe, String data) { + super.reportFromProbe(probe, data); +// if (isRainbowAdapting()) return; + synchronized (m_nodesFromProbes) { + m_nodesFromProbes.clear(); + String[] nodes = data.split("\\s+"); + m_nodesFromProbes.addAll(Arrays.asList(nodes)); + m_newReport = true; + } + } + + @Override + protected void handleConfigParam(TypedAttributeWithValue tav) { + super.handleConfigParam(tav); + + } + + @Override + protected void runAction() { + if (m_models == null) { + try { + m_modelsPort = RainbowPortFactory.createModelsManagerRequirerPort(); + m_models = new CP3ModelAccessor(m_modelsPort); + } catch (RainbowConnectionException e) { + e.printStackTrace(); + } + } + super.runAction(); + + if (/*isRainbowAdapting() || */!m_newReport) return; + if (m_nodeToArch == null) { + m_nodeToArch = new HashMap<> (); + String mapping = getSetupValue("mapping", String.class); + String[] mappings = mapping.split(","); + for (String m : mappings) { + String[] map = m.split("="); + m_nodeToArch.put(map[0].trim(), map[1].trim()); + } + } + HashSet newNodes = new HashSet (); + HashSet goneNodes = new HashSet (); + synchronized (m_nodesFromProbes) { + newNodes.addAll(m_nodesFromProbes); + newNodes.removeAll(m_currentlyActiveNodes); + + goneNodes.addAll(m_currentlyActiveNodes); + goneNodes.removeAll(m_nodesFromProbes); + + m_currentlyActiveNodes.clear(); + m_currentlyActiveNodes.addAll(m_nodesFromProbes); + m_newReport = false; + } + + List ops = new LinkedList<> (); + List> params = new LinkedList<>(); + + for (String n : newNodes) { + IRainbowOperation op = getCommand("set-active"); + Map p = new HashMap<> (); + String comp = m_nodeToArch.get(n); + if (comp != null) { + p.put(op.getTarget(), comp); + p.put(op.getParameters()[0], ActiveT.ACTIVE.name()); + ops.add(op); + params.add(p); + } + } + String active = m_models.getMissionStateModel().getModelInstance().isReconfiguring()?ActiveT.INACTIVE.name():ActiveT.FAILED.name(); + + for (String n : goneNodes) { + IRainbowOperation op = getCommand("set-active"); + Map p = new HashMap<>(); + String comp = m_nodeToArch.get(n); + if (comp != null) { + p.put(op.getTarget(), comp); + p.put(op.getParameters()[0], active); + ops.add(op); + params.add(p); + } + } + if (!ops.isEmpty()) + issueCommands(ops, params); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/ClockGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/ClockGauge.java index 891f17411..fea97e557 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/ClockGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/ClockGauge.java @@ -1,60 +1,60 @@ -package org.sa.rainbow.brass.gauges.p2_cp3; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -public class ClockGauge extends RegularPatternGauge { - - - private static final String NAME = "Clock Gauge"; - protected static final String CLOCK = "Clock"; - protected static final String CLOCK_PATTERN = "topic: /clock.*\\n.*secs: ([0-9]*).*nsecs: ([0-9]*)(.*)"; - - private double m_currentTime; - - - public ClockGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, - TypedAttribute modelDesc, List setupParams, - Map mappings) throws RainbowException { - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern(CLOCK, Pattern.compile(CLOCK_PATTERN, Pattern.DOTALL)); - } - - @Override - protected void doMatch(String matchName, Matcher m) { - int restGroup = 0; - - if (CLOCK.equals(matchName)) { - long secs = Long.parseLong (m.group (1).trim ()); - long nsecs = 0; - if (!"".equals (m.group (2).trim ())) { - nsecs = Long.parseLong (m.group (2).trim ()); - } - double realSecs = secs + TimeUnit.MILLISECONDS.convert (nsecs, TimeUnit.NANOSECONDS) / 1000.0; - m_currentTime = realSecs; - IRainbowOperation op = m_commands.get ("clock"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], Double.toString (realSecs)); - issueCommand (op, pMap); - restGroup = 3; - } - - if (m.groupCount () == restGroup) { - String rest = m.group (restGroup); - if (!rest.isEmpty () && rest.indexOf ("topic:") != -1) { - log ("Gauge had more: " + rest.substring (rest.indexOf ("topic:"))); - } - } - } - -} +package org.sa.rainbow.brass.gauges.p2_cp3; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +public class ClockGauge extends RegularPatternGauge { + + + private static final String NAME = "Clock Gauge"; + protected static final String CLOCK = "Clock"; + protected static final String CLOCK_PATTERN = "topic: /clock.*\\n.*secs: ([0-9]*).*nsecs: ([0-9]*)(.*)"; + + private double m_currentTime; + + + public ClockGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, + TypedAttribute modelDesc, List setupParams, + Map mappings) throws RainbowException { + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern(CLOCK, Pattern.compile(CLOCK_PATTERN, Pattern.DOTALL)); + } + + @Override + protected void doMatch(String matchName, Matcher m) { + int restGroup = 0; + + if (CLOCK.equals(matchName)) { + long secs = Long.parseLong (m.group (1).trim ()); + long nsecs = 0; + if (!"".equals (m.group (2).trim ())) { + nsecs = Long.parseLong (m.group (2).trim ()); + } + double realSecs = secs + TimeUnit.MILLISECONDS.convert (nsecs, TimeUnit.NANOSECONDS) / 1000.0; + m_currentTime = realSecs; + IRainbowOperation op = m_commands.get ("clock"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], Double.toString (realSecs)); + issueCommand (op, pMap); + restGroup = 3; + } + + if (m.groupCount () == restGroup) { + String rest = m.group (restGroup); + if (!rest.isEmpty () && rest.indexOf ("topic:") != -1) { + log ("Gauge had more: " + rest.substring (rest.indexOf ("topic:"))); + } + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/MissionStateGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/MissionStateGauge.java index b52b99919..a3656fa44 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/MissionStateGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/MissionStateGauge.java @@ -1,160 +1,160 @@ -package org.sa.rainbow.brass.gauges.p2_cp3; - -import java.text.DecimalFormat; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.brass.model.map.BatteryPredictor; -import org.sa.rainbow.brass.model.map.MapTranslator; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Created by schmerl on 12/28/2016. - */ -public class MissionStateGauge extends RegularPatternGauge { - private static final String NAME = "Mission State Gauge"; - protected static final String LOC = "LocationRecording"; - protected static final String LOC_TF = "LocationFromTF"; - protected static final String DEADLINE = "Deadline"; - protected static final String RECONFIGURING = "Reconfig"; - - protected static final String LOC_PATTERN = "topic: /gazebo/model_states/pose.*position.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z.*\\norientation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z: (.*)\\n.*w: (.*)(.*)"; //"topic: /o/pose/pose.*position.*\\\\n.*x: (.*)\\\\n.*y: (.*)\\\\n.*z.*\\\\norientation.*\\\\n.*x: (.*)\\\\n.*y: (.*)\\\\n.*z: (.*)\\\\n.*w: (.*)(.*)"; //"topic: /tf/transforms\\[0\\]/transform.*\\ntranslation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z.*\\nrotation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z: (.*)\\n.*w: (.*)(.*)"; - protected static final String DEADLINE_PATTERN = "topic: /notify_user.*\\n.*new_deadline: (.*)\\n.*user(.*)"; - protected static final String RECONFIG_PATTERN = "topic: /ig_interpreter/reconfiguring.*\n.*data:(.*)"; - protected static final String TF_LOCATION_PATTERN = ".*At time.*- Translation: \\[(.*), (.*), .*\\].*Quater.*\\(radian\\) \\[.*,.*, (.*)\\].*"; - protected String last_x; - protected String last_y; - private String last_w; - protected static final DecimalFormat DF = new DecimalFormat("#.##"); - - /** - * Main Constructor the Gauge that is hardwired to the Probe. - * - * @param id - * the unique ID of the Gauge - * @param beaconPeriod - * the liveness beacon period of the Gauge - * @param gaugeDesc - * the type-name description of the Gauge - * @param modelDesc - * the type-name description of the Model the Gauge updates - * @param setupParams - * the list of setup parameters with their values - * @param mappings - * the list of Gauge Value to Model Property mappings - */ - public MissionStateGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern (LOC, Pattern.compile (LOC_PATTERN, Pattern.DOTALL)); - addPattern (DEADLINE, Pattern.compile (DEADLINE_PATTERN, Pattern.DOTALL)); - addPattern (RECONFIGURING, Pattern.compile(RECONFIG_PATTERN, Pattern.DOTALL)); - // addPattern (LOC_TF, Pattern.compile(TF_LOCATION_PATTERN, Pattern.DOTALL)); - } - - @Override - protected void doMatch (String matchName, Matcher m) { - String group = m.group (1); - int restGroup = 0; - if (LOC.equals (matchName)) { - String x = DF.format(Double.parseDouble(group.trim ())); - String y =DF.format(Double.parseDouble( m.group (2).trim ())); - - String a = m.group (3).trim (); - String b = m.group (4).trim (); - String c = m.group (5).trim (); - String d = m.group (6).trim (); - restGroup = 7; - - String w = DF.format(yawFromQuarternion (a, b, c, d)); - - if (locationDifferent (x, y, w)) { - IRainbowOperation op = m_commands.get ("location"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], x); - pMap.put (op.getParameters ()[1], y); - pMap.put (op.getParameters ()[2], w); - issueCommand (op, pMap); - } - } - else if (LOC_TF.equals(matchName)) { - String x = DF.format(Double.parseDouble(m.group(1).trim())); - String y = DF.format(Double.parseDouble(m.group(2).trim())); - String w = DF.format(Double.parseDouble(m.group(3).trim())); - - if (locationDifferent(x,y,w)) { - IRainbowOperation op = m_commands.get ("location"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], x); - pMap.put (op.getParameters ()[1], y); - pMap.put (op.getParameters ()[2], w); - issueCommand (op, pMap); - } - } - else if (DEADLINE.equals (matchName)) { - String date = m.group (1).trim (); - IRainbowOperation op = m_commands.get ("deadline"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], date); - issueCommand (op, pMap); - restGroup = 2; - } - else if (RECONFIGURING.equals(matchName)) { - String mode = m.group(1).trim().toLowerCase(); - IRainbowOperation op = m_commands.get ("reconfiguring"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], mode); - issueCommand (op, pMap); - restGroup = 2; - - } - if (m.groupCount () == restGroup) { - String rest = m.group (restGroup); - if (!rest.isEmpty () && rest.indexOf ("topic:") != -1) { - log ("Gauge had more: " + rest.substring (rest.indexOf ("topic:"))); - } - } - } - - private boolean numberCheck (String[] vals) { - for (String s : vals) { - try { - Double.parseDouble (s); - } - catch (NumberFormatException e) { - return false; - } - } - return true; - } - - // Converstino to yaw from http://www.chrobotics.com/library/understanding-quaternions - private double yawFromQuarternion (String a, String b, String c, String d) { - double A = Double.parseDouble (a); - double B = Double.parseDouble (b); - double C = Double.parseDouble (c); - double D = Double.parseDouble (d); - - double w = Math.atan ((2 * (A * B + C * D)) / (A * A - B * B - C * C + D * D)); - return w; - } - - private boolean locationDifferent (String x, String y, String w) { - boolean different = !x.equals (last_x) || !y.equals (last_y) || !w.equals (last_w); - if (different) { - last_x = x; - last_y = y; - last_w = w; - } - return different; - } -} +package org.sa.rainbow.brass.gauges.p2_cp3; + +import java.text.DecimalFormat; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.brass.model.map.BatteryPredictor; +import org.sa.rainbow.brass.model.map.MapTranslator; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Created by schmerl on 12/28/2016. + */ +public class MissionStateGauge extends RegularPatternGauge { + private static final String NAME = "Mission State Gauge"; + protected static final String LOC = "LocationRecording"; + protected static final String LOC_TF = "LocationFromTF"; + protected static final String DEADLINE = "Deadline"; + protected static final String RECONFIGURING = "Reconfig"; + + protected static final String LOC_PATTERN = "topic: /gazebo/model_states/pose.*position.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z.*\\norientation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z: (.*)\\n.*w: (.*)(.*)"; //"topic: /o/pose/pose.*position.*\\\\n.*x: (.*)\\\\n.*y: (.*)\\\\n.*z.*\\\\norientation.*\\\\n.*x: (.*)\\\\n.*y: (.*)\\\\n.*z: (.*)\\\\n.*w: (.*)(.*)"; //"topic: /tf/transforms\\[0\\]/transform.*\\ntranslation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z.*\\nrotation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z: (.*)\\n.*w: (.*)(.*)"; + protected static final String DEADLINE_PATTERN = "topic: /notify_user.*\\n.*new_deadline: (.*)\\n.*user(.*)"; + protected static final String RECONFIG_PATTERN = "topic: /ig_interpreter/reconfiguring.*\n.*data:(.*)"; + protected static final String TF_LOCATION_PATTERN = ".*At time.*- Translation: \\[(.*), (.*), .*\\].*Quater.*\\(radian\\) \\[.*,.*, (.*)\\].*"; + protected String last_x; + protected String last_y; + private String last_w; + protected static final DecimalFormat DF = new DecimalFormat("#.##"); + + /** + * Main Constructor the Gauge that is hardwired to the Probe. + * + * @param id + * the unique ID of the Gauge + * @param beaconPeriod + * the liveness beacon period of the Gauge + * @param gaugeDesc + * the type-name description of the Gauge + * @param modelDesc + * the type-name description of the Model the Gauge updates + * @param setupParams + * the list of setup parameters with their values + * @param mappings + * the list of Gauge Value to Model Property mappings + */ + public MissionStateGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern (LOC, Pattern.compile (LOC_PATTERN, Pattern.DOTALL)); + addPattern (DEADLINE, Pattern.compile (DEADLINE_PATTERN, Pattern.DOTALL)); + addPattern (RECONFIGURING, Pattern.compile(RECONFIG_PATTERN, Pattern.DOTALL)); + // addPattern (LOC_TF, Pattern.compile(TF_LOCATION_PATTERN, Pattern.DOTALL)); + } + + @Override + protected void doMatch (String matchName, Matcher m) { + String group = m.group (1); + int restGroup = 0; + if (LOC.equals (matchName)) { + String x = DF.format(Double.parseDouble(group.trim ())); + String y =DF.format(Double.parseDouble( m.group (2).trim ())); + + String a = m.group (3).trim (); + String b = m.group (4).trim (); + String c = m.group (5).trim (); + String d = m.group (6).trim (); + restGroup = 7; + + String w = DF.format(yawFromQuarternion (a, b, c, d)); + + if (locationDifferent (x, y, w)) { + IRainbowOperation op = m_commands.get ("location"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], x); + pMap.put (op.getParameters ()[1], y); + pMap.put (op.getParameters ()[2], w); + issueCommand (op, pMap); + } + } + else if (LOC_TF.equals(matchName)) { + String x = DF.format(Double.parseDouble(m.group(1).trim())); + String y = DF.format(Double.parseDouble(m.group(2).trim())); + String w = DF.format(Double.parseDouble(m.group(3).trim())); + + if (locationDifferent(x,y,w)) { + IRainbowOperation op = m_commands.get ("location"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], x); + pMap.put (op.getParameters ()[1], y); + pMap.put (op.getParameters ()[2], w); + issueCommand (op, pMap); + } + } + else if (DEADLINE.equals (matchName)) { + String date = m.group (1).trim (); + IRainbowOperation op = m_commands.get ("deadline"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], date); + issueCommand (op, pMap); + restGroup = 2; + } + else if (RECONFIGURING.equals(matchName)) { + String mode = m.group(1).trim().toLowerCase(); + IRainbowOperation op = m_commands.get ("reconfiguring"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], mode); + issueCommand (op, pMap); + restGroup = 2; + + } + if (m.groupCount () == restGroup) { + String rest = m.group (restGroup); + if (!rest.isEmpty () && rest.indexOf ("topic:") != -1) { + log ("Gauge had more: " + rest.substring (rest.indexOf ("topic:"))); + } + } + } + + private boolean numberCheck (String[] vals) { + for (String s : vals) { + try { + Double.parseDouble (s); + } + catch (NumberFormatException e) { + return false; + } + } + return true; + } + + // Converstino to yaw from http://www.chrobotics.com/library/understanding-quaternions + private double yawFromQuarternion (String a, String b, String c, String d) { + double A = Double.parseDouble (a); + double B = Double.parseDouble (b); + double C = Double.parseDouble (c); + double D = Double.parseDouble (d); + + double w = Math.atan ((2 * (A * B + C * D)) / (A * A - B * B - C * C + D * D)); + return w; + } + + private boolean locationDifferent (String x, String y, String w) { + boolean different = !x.equals (last_x) || !y.equals (last_y) || !w.equals (last_w); + if (different) { + last_x = x; + last_y = y; + last_w = w; + } + return different; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/RobotStateGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/RobotStateGauge.java index fbff31246..7d84e3de8 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/RobotStateGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/gauges/p2_cp3/RobotStateGauge.java @@ -1,266 +1,266 @@ -package org.sa.rainbow.brass.gauges.p2_cp3; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.brass.model.p2_cp3.CP3ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.ICP3ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.OperationRepresentation; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IModelsManagerPort; -import org.sa.rainbow.core.ports.RainbowPortFactory; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.translator.probes.IProbeIdentifier; - -public class RobotStateGauge extends RegularPatternGauge { - - public static class MovingAverage { - private double[] window; - private int n, insert; - private double sum; - - public MovingAverage(int size) { - window = new double[size]; - insert = 0; - sum = 0; - } - - public double next(double val) { - if (n < window.length) - n++; - sum -= window[insert]; - sum += val; - window[insert] = val; - insert = (insert + 1) % window.length; - return (double) sum / n; - } - } - - private static final String NAME = "Robot State Gauge"; - - protected static final String CHARGE = "BatteryCharge"; - protected static final String KINECT = "KinectStatus"; - protected static final String LIDAR = "LidarStatus"; - protected static final String HEADLAMP = "HeadlampStatus"; - protected static final String BUMP = "BumpStatus"; - protected static final String SPEED = "Speed"; - protected static final String LIGHTING = "Lighting"; - - protected static final String CHARGE_PATTERN = "topic: /energy_monitor/energy_level.*\\n.*data: (.*)"; - protected static final String KINECT_PATTERN = "topic: /mobile_base/kinect/status.*\\n.*data: (.*)"; - protected static final String LIDAR_PATTERN = "topic: /mobile_base/lidar/status.*\\n.*data: (.*)"; - protected static final String HEADLAMP_PATTERN = "topic: /mobile_base/headlamp/status.*\\n.*data: (.*)"; - protected static final String LIGHTING_PATTERN = "topic: /mobile_base/sensors/light_sensor.*\\n.*illuminance: (.*)v.*"; - protected static final String SPEED_PATTERN = "topic: /odom/twist/twist/linear.*\\nx: (.*)\\ny: (.*)\\nz:.*"; - protected static final String BUMP_PATTERN = "topic: /mobile_base/events/bumper.*\\nstate: (.*)\\n"; - - private double last_charge = 0; - - private int reported_kinect_mode = -1; - - private boolean reported_lidar_mode; - - private boolean reported_headlamp_mode; - - private double last_lighting = -1; - private MovingAverage lightingTracker = new MovingAverage(3); - - private double reported_speed; - - private boolean reported_bump; - - private ICP3ModelAccessor m_models; - - private IModelsManagerPort m_modelsPort; - - public RobotStateGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern(CHARGE, Pattern.compile(CHARGE_PATTERN, Pattern.DOTALL)); - addPattern(KINECT, Pattern.compile(KINECT_PATTERN, Pattern.DOTALL)); - addPattern(LIDAR, Pattern.compile(LIDAR_PATTERN, Pattern.DOTALL)); - addPattern(HEADLAMP, Pattern.compile(HEADLAMP_PATTERN, Pattern.DOTALL)); - addPattern(LIGHTING, Pattern.compile(LIGHTING_PATTERN, Pattern.DOTALL)); - addPattern(SPEED, Pattern.compile(SPEED_PATTERN, Pattern.DOTALL)); - addPattern(BUMP, Pattern.compile(BUMP_PATTERN, Pattern.DOTALL)); - } - - @Override - protected void doMatch(String matchName, Matcher m) { - if (m_models == null) { - try { - m_modelsPort = RainbowPortFactory.createModelsManagerRequirerPort(); - m_models = new CP3ModelAccessor(m_modelsPort); - } catch (RainbowConnectionException e) { - e.printStackTrace(); - } - } - if (CHARGE.equals(matchName)) { - double charge = Double.parseDouble(m.group(1).trim()); - - if (chargeDifferent(charge)) { - IRainbowOperation op = m_commands.get("charge"); - Map pMap = new HashMap<>(); - pMap.put(op.getParameters()[0], Double.toString(charge)); - issueCommand(op, pMap); - } - } else if (LIGHTING.equals(matchName)) { - double lighting = lightingTracker.next(Double.parseDouble(m.group(1).trim())); - if (lightingDifferent(lighting)) { - IRainbowOperation op = m_commands.get("lighting"); - Map pMap = new HashMap<>(); - pMap.put(op.getParameters()[0], Double.toString(lighting)); - issueCommand(op, pMap); - } - } else if (KINECT.equals(matchName)) { - int mode = Integer.parseInt(m.group(1).trim()); - - if (reported_kinect_mode != mode) { - reported_kinect_mode = mode; - if (mode == 2) { - IRainbowOperation cameraOp = m_commands.get("sensor"); - Map cameraMap = new HashMap<>(); - cameraMap.put(cameraOp.getParameters()[0], Sensors.CAMERA.name()); - cameraMap.put(cameraOp.getParameters()[1], Boolean.toString(true)); - - OperationRepresentation kinectOp = new OperationRepresentation(cameraOp); - Map kinectMap = new HashMap<>(); - kinectMap.put(kinectOp.getParameters()[0], Sensors.KINECT.name()); - kinectMap.put(kinectOp.getParameters()[1], Boolean.toString(false)); - - List ops = Arrays.asList(new IRainbowOperation[] { cameraOp, kinectOp }); - List> params = Arrays.asList(new Map[] { cameraMap, kinectMap }); - issueCommands(ops, params); - } else if (mode == 1) { - IRainbowOperation cameraOp = m_commands.get("sensor"); - Map cameraMap = new HashMap<>(); - cameraMap.put(cameraOp.getParameters()[0], Sensors.CAMERA.name()); - cameraMap.put(cameraOp.getParameters()[1], Boolean.toString(false)); - - OperationRepresentation kinectOp = new OperationRepresentation(cameraOp); - Map kinectMap = new HashMap<>(); - kinectMap.put(kinectOp.getParameters()[0], Sensors.KINECT.name()); - kinectMap.put(kinectOp.getParameters()[1], Boolean.toString(true)); - - List ops = Arrays.asList(new IRainbowOperation[] { cameraOp, kinectOp }); - List> params = Arrays.asList(new Map[] { cameraMap, kinectMap }); - issueCommands(ops, params); - } else if (mode == 0) { - if (!m_models.getMissionStateModel().getModelInstance().isReconfiguring()) { - IRainbowOperation fop = m_commands.get("sensor-failed"); - Map fom = new HashMap<>(); - if (m_models.getRobotStateModel().getModelInstance().getSensors().contains(Sensors.KINECT)) { - fom.put(fop.getParameters()[0], Sensors.KINECT.name()); - } else if (m_models.getRobotStateModel().getModelInstance().getSensors().contains(Sensors.CAMERA)) { - fom.put(fop.getParameters()[0], Sensors.CAMERA.name()); - } - if (!fom.isEmpty()) issueCommand(fop, fom); - } else { - IRainbowOperation cameraOp = m_commands.get("sensor"); - Map cameraMap = new HashMap<>(); - cameraMap.put(cameraOp.getParameters()[0], Sensors.CAMERA.name()); - cameraMap.put(cameraOp.getParameters()[1], Boolean.toString(false)); - - OperationRepresentation kinectOp = new OperationRepresentation(cameraOp); - Map kinectMap = new HashMap<>(); - kinectMap.put(kinectOp.getParameters()[0], Sensors.KINECT.name()); - kinectMap.put(kinectOp.getParameters()[1], Boolean.toString(false)); - - List ops = Arrays.asList(new IRainbowOperation[] { cameraOp, kinectOp }); - List> params = Arrays.asList(new Map[] { cameraMap, kinectMap }); - issueCommands(ops, params); - } - } - } - } else if (LIDAR.equals(matchName)) { - boolean lMode = Boolean.parseBoolean(m.group(1).trim().toLowerCase()); - if (lMode != reported_lidar_mode) { - if (!lMode && !m_models.getMissionStateModel().getModelInstance().isReconfiguring()) { - reported_lidar_mode = lMode; - IRainbowOperation lidarOp = m_commands.get("sensor-failed"); - Map lidarParams = new HashMap<>(); - lidarParams.put(lidarOp.getParameters()[0], Sensors.LIDAR.name()); -// lidarParams.put(lidarOp.getParameters()[1], Boolean.toString(lMode)); - issueCommand(lidarOp, lidarParams); - } else { - reported_lidar_mode = lMode; - IRainbowOperation lidarOp = m_commands.get("sensor"); - Map lidarParams = new HashMap<>(); - lidarParams.put(lidarOp.getParameters()[0], Sensors.LIDAR.name()); - lidarParams.put(lidarOp.getParameters()[1], Boolean.toString(lMode)); - issueCommand(lidarOp, lidarParams); - } - } - } else if (HEADLAMP.equals(matchName)) { - boolean hMode = Boolean.parseBoolean(m.group(1).trim().toLowerCase()); - if (hMode != reported_headlamp_mode) { - reported_headlamp_mode = hMode; - IRainbowOperation lidarOp = m_commands.get("sensor"); - Map lidarParams = new HashMap<>(); - lidarParams.put(lidarOp.getParameters()[0], Sensors.HEADLAMP.name()); - lidarParams.put(lidarOp.getParameters()[1], Boolean.toString(hMode)); - issueCommand(lidarOp, lidarParams); - } - } else if (SPEED.equals(matchName)) { - double x = Double.parseDouble(m.group(1).trim()); - double y = Double.parseDouble(m.group(2).trim()); - - double speed = Math.round(Math.sqrt(x * x + y * y) * 100) / 100d; - if (speed != reported_speed) { - reported_speed = speed; - IRainbowOperation speedOp = m_commands.get("speed"); - Map params = new HashMap<>(); - params.put(speedOp.getParameters()[0], Double.toString(speed)); - issueCommand(speedOp, params); - } - } else if (BUMP.equals(matchName)) { - int status = Integer.parseInt(m.group(1).trim()); - boolean bump = status == 1; - if (bump != reported_bump) { - reported_bump = bump; - IRainbowOperation bumpOp = m_commands.get("bump"); - Map params = new HashMap<>(); - params.put(bumpOp.getParameters()[0], Boolean.toString(bump)); - issueCommand(bumpOp, params); - } - } - - } - - private boolean lightingDifferent(double lighting2) { - if (Math.round(last_lighting) != Math.round(lighting2)) { - last_lighting = lighting2; - return true; - } - return false; - } - - private boolean chargeDifferent(double charge) { - if (Math.round(last_charge / 10) != Math.round(charge / 10)) { - last_charge = charge; - return true; - } - return false; - } - - @Override - public void reportFromProbe(IProbeIdentifier probe, String data) { - // TODO Auto-generated method stub - super.reportFromProbe(probe, data); - } - - @Override - protected boolean shouldProcess() { - return !isRainbowAdapting(); - } -} +package org.sa.rainbow.brass.gauges.p2_cp3; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.brass.model.p2_cp3.CP3ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.ICP3ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.OperationRepresentation; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.translator.probes.IProbeIdentifier; + +public class RobotStateGauge extends RegularPatternGauge { + + public static class MovingAverage { + private double[] window; + private int n, insert; + private double sum; + + public MovingAverage(int size) { + window = new double[size]; + insert = 0; + sum = 0; + } + + public double next(double val) { + if (n < window.length) + n++; + sum -= window[insert]; + sum += val; + window[insert] = val; + insert = (insert + 1) % window.length; + return (double) sum / n; + } + } + + private static final String NAME = "Robot State Gauge"; + + protected static final String CHARGE = "BatteryCharge"; + protected static final String KINECT = "KinectStatus"; + protected static final String LIDAR = "LidarStatus"; + protected static final String HEADLAMP = "HeadlampStatus"; + protected static final String BUMP = "BumpStatus"; + protected static final String SPEED = "Speed"; + protected static final String LIGHTING = "Lighting"; + + protected static final String CHARGE_PATTERN = "topic: /energy_monitor/energy_level.*\\n.*data: (.*)"; + protected static final String KINECT_PATTERN = "topic: /mobile_base/kinect/status.*\\n.*data: (.*)"; + protected static final String LIDAR_PATTERN = "topic: /mobile_base/lidar/status.*\\n.*data: (.*)"; + protected static final String HEADLAMP_PATTERN = "topic: /mobile_base/headlamp/status.*\\n.*data: (.*)"; + protected static final String LIGHTING_PATTERN = "topic: /mobile_base/sensors/light_sensor.*\\n.*illuminance: (.*)v.*"; + protected static final String SPEED_PATTERN = "topic: /odom/twist/twist/linear.*\\nx: (.*)\\ny: (.*)\\nz:.*"; + protected static final String BUMP_PATTERN = "topic: /mobile_base/events/bumper.*\\nstate: (.*)\\n"; + + private double last_charge = 0; + + private int reported_kinect_mode = -1; + + private boolean reported_lidar_mode; + + private boolean reported_headlamp_mode; + + private double last_lighting = -1; + private MovingAverage lightingTracker = new MovingAverage(3); + + private double reported_speed; + + private boolean reported_bump; + + private ICP3ModelAccessor m_models; + + private IModelsManagerPort m_modelsPort; + + public RobotStateGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern(CHARGE, Pattern.compile(CHARGE_PATTERN, Pattern.DOTALL)); + addPattern(KINECT, Pattern.compile(KINECT_PATTERN, Pattern.DOTALL)); + addPattern(LIDAR, Pattern.compile(LIDAR_PATTERN, Pattern.DOTALL)); + addPattern(HEADLAMP, Pattern.compile(HEADLAMP_PATTERN, Pattern.DOTALL)); + addPattern(LIGHTING, Pattern.compile(LIGHTING_PATTERN, Pattern.DOTALL)); + addPattern(SPEED, Pattern.compile(SPEED_PATTERN, Pattern.DOTALL)); + addPattern(BUMP, Pattern.compile(BUMP_PATTERN, Pattern.DOTALL)); + } + + @Override + protected void doMatch(String matchName, Matcher m) { + if (m_models == null) { + try { + m_modelsPort = RainbowPortFactory.createModelsManagerRequirerPort(); + m_models = new CP3ModelAccessor(m_modelsPort); + } catch (RainbowConnectionException e) { + e.printStackTrace(); + } + } + if (CHARGE.equals(matchName)) { + double charge = Double.parseDouble(m.group(1).trim()); + + if (chargeDifferent(charge)) { + IRainbowOperation op = m_commands.get("charge"); + Map pMap = new HashMap<>(); + pMap.put(op.getParameters()[0], Double.toString(charge)); + issueCommand(op, pMap); + } + } else if (LIGHTING.equals(matchName)) { + double lighting = lightingTracker.next(Double.parseDouble(m.group(1).trim())); + if (lightingDifferent(lighting)) { + IRainbowOperation op = m_commands.get("lighting"); + Map pMap = new HashMap<>(); + pMap.put(op.getParameters()[0], Double.toString(lighting)); + issueCommand(op, pMap); + } + } else if (KINECT.equals(matchName)) { + int mode = Integer.parseInt(m.group(1).trim()); + + if (reported_kinect_mode != mode) { + reported_kinect_mode = mode; + if (mode == 2) { + IRainbowOperation cameraOp = m_commands.get("sensor"); + Map cameraMap = new HashMap<>(); + cameraMap.put(cameraOp.getParameters()[0], Sensors.CAMERA.name()); + cameraMap.put(cameraOp.getParameters()[1], Boolean.toString(true)); + + OperationRepresentation kinectOp = new OperationRepresentation(cameraOp); + Map kinectMap = new HashMap<>(); + kinectMap.put(kinectOp.getParameters()[0], Sensors.KINECT.name()); + kinectMap.put(kinectOp.getParameters()[1], Boolean.toString(false)); + + List ops = Arrays.asList(new IRainbowOperation[] { cameraOp, kinectOp }); + List> params = Arrays.asList(new Map[] { cameraMap, kinectMap }); + issueCommands(ops, params); + } else if (mode == 1) { + IRainbowOperation cameraOp = m_commands.get("sensor"); + Map cameraMap = new HashMap<>(); + cameraMap.put(cameraOp.getParameters()[0], Sensors.CAMERA.name()); + cameraMap.put(cameraOp.getParameters()[1], Boolean.toString(false)); + + OperationRepresentation kinectOp = new OperationRepresentation(cameraOp); + Map kinectMap = new HashMap<>(); + kinectMap.put(kinectOp.getParameters()[0], Sensors.KINECT.name()); + kinectMap.put(kinectOp.getParameters()[1], Boolean.toString(true)); + + List ops = Arrays.asList(new IRainbowOperation[] { cameraOp, kinectOp }); + List> params = Arrays.asList(new Map[] { cameraMap, kinectMap }); + issueCommands(ops, params); + } else if (mode == 0) { + if (!m_models.getMissionStateModel().getModelInstance().isReconfiguring()) { + IRainbowOperation fop = m_commands.get("sensor-failed"); + Map fom = new HashMap<>(); + if (m_models.getRobotStateModel().getModelInstance().getSensors().contains(Sensors.KINECT)) { + fom.put(fop.getParameters()[0], Sensors.KINECT.name()); + } else if (m_models.getRobotStateModel().getModelInstance().getSensors().contains(Sensors.CAMERA)) { + fom.put(fop.getParameters()[0], Sensors.CAMERA.name()); + } + if (!fom.isEmpty()) issueCommand(fop, fom); + } else { + IRainbowOperation cameraOp = m_commands.get("sensor"); + Map cameraMap = new HashMap<>(); + cameraMap.put(cameraOp.getParameters()[0], Sensors.CAMERA.name()); + cameraMap.put(cameraOp.getParameters()[1], Boolean.toString(false)); + + OperationRepresentation kinectOp = new OperationRepresentation(cameraOp); + Map kinectMap = new HashMap<>(); + kinectMap.put(kinectOp.getParameters()[0], Sensors.KINECT.name()); + kinectMap.put(kinectOp.getParameters()[1], Boolean.toString(false)); + + List ops = Arrays.asList(new IRainbowOperation[] { cameraOp, kinectOp }); + List> params = Arrays.asList(new Map[] { cameraMap, kinectMap }); + issueCommands(ops, params); + } + } + } + } else if (LIDAR.equals(matchName)) { + boolean lMode = Boolean.parseBoolean(m.group(1).trim().toLowerCase()); + if (lMode != reported_lidar_mode) { + if (!lMode && !m_models.getMissionStateModel().getModelInstance().isReconfiguring()) { + reported_lidar_mode = lMode; + IRainbowOperation lidarOp = m_commands.get("sensor-failed"); + Map lidarParams = new HashMap<>(); + lidarParams.put(lidarOp.getParameters()[0], Sensors.LIDAR.name()); +// lidarParams.put(lidarOp.getParameters()[1], Boolean.toString(lMode)); + issueCommand(lidarOp, lidarParams); + } else { + reported_lidar_mode = lMode; + IRainbowOperation lidarOp = m_commands.get("sensor"); + Map lidarParams = new HashMap<>(); + lidarParams.put(lidarOp.getParameters()[0], Sensors.LIDAR.name()); + lidarParams.put(lidarOp.getParameters()[1], Boolean.toString(lMode)); + issueCommand(lidarOp, lidarParams); + } + } + } else if (HEADLAMP.equals(matchName)) { + boolean hMode = Boolean.parseBoolean(m.group(1).trim().toLowerCase()); + if (hMode != reported_headlamp_mode) { + reported_headlamp_mode = hMode; + IRainbowOperation lidarOp = m_commands.get("sensor"); + Map lidarParams = new HashMap<>(); + lidarParams.put(lidarOp.getParameters()[0], Sensors.HEADLAMP.name()); + lidarParams.put(lidarOp.getParameters()[1], Boolean.toString(hMode)); + issueCommand(lidarOp, lidarParams); + } + } else if (SPEED.equals(matchName)) { + double x = Double.parseDouble(m.group(1).trim()); + double y = Double.parseDouble(m.group(2).trim()); + + double speed = Math.round(Math.sqrt(x * x + y * y) * 100) / 100d; + if (speed != reported_speed) { + reported_speed = speed; + IRainbowOperation speedOp = m_commands.get("speed"); + Map params = new HashMap<>(); + params.put(speedOp.getParameters()[0], Double.toString(speed)); + issueCommand(speedOp, params); + } + } else if (BUMP.equals(matchName)) { + int status = Integer.parseInt(m.group(1).trim()); + boolean bump = status == 1; + if (bump != reported_bump) { + reported_bump = bump; + IRainbowOperation bumpOp = m_commands.get("bump"); + Map params = new HashMap<>(); + params.put(bumpOp.getParameters()[0], Boolean.toString(bump)); + issueCommand(bumpOp, params); + } + } + + } + + private boolean lightingDifferent(double lighting2) { + if (Math.round(last_lighting) != Math.round(lighting2)) { + last_lighting = lighting2; + return true; + } + return false; + } + + private boolean chargeDifferent(double charge) { + if (Math.round(last_charge / 10) != Math.round(charge / 10)) { + last_charge = charge; + return true; + } + return false; + } + + @Override + public void reportFromProbe(IProbeIdentifier probe, String data) { + // TODO Auto-generated method stub + super.reportFromProbe(probe, data); + } + + @Override + protected boolean shouldProcess() { + return !isRainbowAdapting(); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/AbstractSimpleRainbowModelOperation.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/AbstractSimpleRainbowModelOperation.java index 21a70b2ec..42fbd575e 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/AbstractSimpleRainbowModelOperation.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/AbstractSimpleRainbowModelOperation.java @@ -1,59 +1,59 @@ -package org.sa.rainbow.brass.model; - -import java.util.List; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public abstract class AbstractSimpleRainbowModelOperation extends AbstractRainbowModelOperation { - - - private String m_event; - private R m_result; - - public AbstractSimpleRainbowModelOperation(String commandName, String eventName, IModelInstance model, String target, - String... parameters) { - super(commandName, model, target, parameters); - m_event = eventName; - } - - protected void setResult(R r) { - m_result = r; - } - - @Override - public R getResult() throws IllegalStateException { - return m_result; - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, m_event); - - } - - - - @Override - protected void subRedo() throws RainbowException { - - } - - @Override - protected void subUndo() throws RainbowException { - - } - - @Override - protected boolean checkModelValidForCommand(M model) { - return true; - } - - - - - -} +package org.sa.rainbow.brass.model; + +import java.util.List; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public abstract class AbstractSimpleRainbowModelOperation extends AbstractRainbowModelOperation { + + + private String m_event; + private R m_result; + + public AbstractSimpleRainbowModelOperation(String commandName, String eventName, IModelInstance model, String target, + String... parameters) { + super(commandName, model, target, parameters); + m_event = eventName; + } + + protected void setResult(R r) { + m_result = r; + } + + @Override + public R getResult() throws IllegalStateException { + return m_result; + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents(messageFactory, m_event); + + } + + + + @Override + protected void subRedo() throws RainbowException { + + } + + @Override + protected void subUndo() throws RainbowException { + + } + + @Override + protected boolean checkModelValidForCommand(M model) { + return true; + } + + + + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/P2ModelAccessor.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/P2ModelAccessor.java index 9b756f164..d5aadcca4 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/P2ModelAccessor.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/P2ModelAccessor.java @@ -1,58 +1,58 @@ -package org.sa.rainbow.brass.model; - -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.EnvMapModelInstance; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionStateModelInstance; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowStateModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.ports.IModelsManagerPort; - -public class P2ModelAccessor implements IP2ModelAccessor { - - protected IModelsManagerPort m_modelsManagerPort; - private RainbowStateModelInstance m_rainbowStateModel; - private MissionStateModelInstance m_missionStateModel; - private InstructionGraphModelInstance m_instructionGraphModel; - private EnvMapModelInstance m_envMapModel; - - public P2ModelAccessor(IModelsManagerPort mmp) { - m_modelsManagerPort = mmp; - } - - @Override - public RainbowStateModelInstance getRainbowStateModel() { - if (m_rainbowStateModel == null) - m_rainbowStateModel = (RainbowStateModelInstance) m_modelsManagerPort - .getModelInstance(new ModelReference("RainbowState", RainbowStateModelInstance.TYPE)); - return m_rainbowStateModel; - } - - @Override - public MissionStateModelInstance getMissionStateModel() { - if (m_missionStateModel == null) { - m_missionStateModel = (MissionStateModelInstance )m_modelsManagerPort.getModelInstance(new ModelReference("MissionState", MissionStateModelInstance.MISSION_STATE_TYPE)); - } - return m_missionStateModel; - } - - @Override - public InstructionGraphModelInstance getInstructionGraphModel() { - if (m_instructionGraphModel == null) { - m_instructionGraphModel = (InstructionGraphModelInstance )m_modelsManagerPort.getModelInstance(new ModelReference("ExecutingInstructionGraph", InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE)); - } - return m_instructionGraphModel; - } - - @Override - public EnvMapModelInstance getEnvMapModel() { - if (m_envMapModel == null) { - m_envMapModel = (EnvMapModelInstance )m_modelsManagerPort.getModelInstance(new ModelReference("Map", EnvMapModelInstance.ENV_MAP_TYPE)); - } - return m_envMapModel; - } - -} +package org.sa.rainbow.brass.model; + +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.EnvMapModelInstance; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionStateModelInstance; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowStateModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.IModelsManagerPort; + +public class P2ModelAccessor implements IP2ModelAccessor { + + protected IModelsManagerPort m_modelsManagerPort; + private RainbowStateModelInstance m_rainbowStateModel; + private MissionStateModelInstance m_missionStateModel; + private InstructionGraphModelInstance m_instructionGraphModel; + private EnvMapModelInstance m_envMapModel; + + public P2ModelAccessor(IModelsManagerPort mmp) { + m_modelsManagerPort = mmp; + } + + @Override + public RainbowStateModelInstance getRainbowStateModel() { + if (m_rainbowStateModel == null) + m_rainbowStateModel = (RainbowStateModelInstance) m_modelsManagerPort + .getModelInstance(new ModelReference("RainbowState", RainbowStateModelInstance.TYPE)); + return m_rainbowStateModel; + } + + @Override + public MissionStateModelInstance getMissionStateModel() { + if (m_missionStateModel == null) { + m_missionStateModel = (MissionStateModelInstance )m_modelsManagerPort.getModelInstance(new ModelReference("MissionState", MissionStateModelInstance.MISSION_STATE_TYPE)); + } + return m_missionStateModel; + } + + @Override + public InstructionGraphModelInstance getInstructionGraphModel() { + if (m_instructionGraphModel == null) { + m_instructionGraphModel = (InstructionGraphModelInstance )m_modelsManagerPort.getModelInstance(new ModelReference("ExecutingInstructionGraph", InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE)); + } + return m_instructionGraphModel; + } + + @Override + public EnvMapModelInstance getEnvMapModel() { + if (m_envMapModel == null) { + m_envMapModel = (EnvMapModelInstance )m_modelsManagerPort.getModelInstance(new ModelReference("Map", EnvMapModelInstance.ENV_MAP_TYPE)); + } + return m_envMapModel; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/AttachCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/AttachCmd.java index dc95ebd42..092578788 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/AttachCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/AttachCmd.java @@ -19,8 +19,8 @@ public class AttachCmd extends AcmeModelOperation { private String m_role; private IAcmeAttachmentCommand m_attachCmd; - public AttachCmd (AcmeModelInstance model, String system, String port, String role) { - super ("attach", model, system, port, role); + public AttachCmd (String commandName, AcmeModelInstance model, String system, String port, String role) { + super (commandName, model, system, port, role); // TODO Auto-generated constructor stub m_port = port; m_role = role; diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateActionConnectorCommand.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateActionConnectorCommand.java index e369cb25c..848dc8603 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateActionConnectorCommand.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateActionConnectorCommand.java @@ -14,8 +14,8 @@ public class CreateActionConnectorCommand extends RosAcmeModelCommand { private String m_portType; private IAcmePortCreateCommand m_portCreateCommand; - public CreateActionPortCommand (AcmeModelInstance model, String comp, String portName, String portType) { - super ("createActionPort", model, comp, portName, portType); + public CreateActionPortCommand (String commandName, AcmeModelInstance model, String comp, String portName, String portType) { + super (commandName, model, comp, portName, portType); m_comp = comp; m_portName = portName; m_portType = portType; diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateActionRoleCommand.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateActionRoleCommand.java index b2103fc20..18bd9e91d 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateActionRoleCommand.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateActionRoleCommand.java @@ -17,8 +17,8 @@ public class CreateActionRoleCommand extends RosAcmeModelCommand { private String m_roleType; private IAcmeRoleCreateCommand m_roleCreateCommand; - public CreateActionRoleCommand (AcmeModelInstance model, String comp, String roleName, String roleType) { - super ("createActionRole", model, comp, roleName, roleType); + public CreateActionRoleCommand (String commandName, AcmeModelInstance model, String comp, String roleName, String roleType) { + super (commandName, model, comp, roleName, roleType); m_comp = comp; m_roleName = roleName; m_roleType = roleType; diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateRosNodeCommand.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateRosNodeCommand.java index d5b7d4569..3c44331f1 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateRosNodeCommand.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateRosNodeCommand.java @@ -15,8 +15,8 @@ public class CreateRosNodeCommand extends RosAcmeModelCommand { private IAcmeComponentCreateCommand m_rosNodeCmd; private String m_nodeType; - public CreateRosNodeCommand (AcmeModelInstance model, String system, String nodeName) { - super ("createNode", model, system, nodeName); + public CreateRosNodeCommand (String commandName, AcmeModelInstance model, String system, String nodeName) { + super (commandName, model, system, nodeName); m_nodeName = nodeName; } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateRosNodeManagerCommand.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateRosNodeManagerCommand.java index fcc246ee8..073ec2ee0 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateRosNodeManagerCommand.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateRosNodeManagerCommand.java @@ -14,8 +14,8 @@ public class CreateRosNodeManagerCommand extends RosAcmeModelCommand { private String m_portType; private IAcmePortCreateCommand m_portCreateCommand; - public CreateServicePortCommand (AcmeModelInstance model, String comp, String portName, String portType) { - super ("createServicePort", model, comp, portName, portType); + public CreateServicePortCommand (String commandName, AcmeModelInstance model, String comp, String portName, String portType) { + super (commandName, model, comp, portName, portType); m_comp = comp; m_portName = portName; m_portType = portType; diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateTopicConnectorCommand.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateTopicConnectorCommand.java index f0e216120..f89aeea6e 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateTopicConnectorCommand.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateTopicConnectorCommand.java @@ -18,9 +18,9 @@ public class CreateTopicConnectorCommand extends RosAcmeModelCommand { private String m_portType; private IAcmePortCreateCommand m_portCreateCommand; - public CreateTopicPortCommand (AcmeModelInstance model, String comp, String portName, String portType) { - super ("createTopicPort", model, comp, portName, portType); + public CreateTopicPortCommand (String commandName, AcmeModelInstance model, String comp, String portName, String portType) { + super (commandName, model, comp, portName, portType); m_comp = comp; m_portName = portName; m_portType = portType; diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateTopicRoleCommand.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateTopicRoleCommand.java index 4642c06fb..e4604b842 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateTopicRoleCommand.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/CreateTopicRoleCommand.java @@ -17,8 +17,8 @@ public class CreateTopicRoleCommand extends RosAcmeModelCommand { private String m_roleType; private IAcmeRoleCreateCommand m_roleCreateCommand; - public CreateTopicRoleCommand (AcmeModelInstance model, String comp, String roleName, String roleType) { - super ("createTopicRole", model, comp, roleName, roleType); + public CreateTopicRoleCommand (String commandName, AcmeModelInstance model, String comp, String roleName, String roleType) { + super (commandName, model, comp, roleName, roleType); m_comp = comp; m_roleName = roleName; m_roleType = roleType; diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteComponentCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteComponentCmd.java index b88574a7c..5a331ddde 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteComponentCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteComponentCmd.java @@ -16,8 +16,8 @@ public class DeleteComponentCmd extends AcmeModelOperation { private String m_component; private IAcmeComponentDeleteCommand m_deleteComponentCmd; - public DeleteComponentCmd (AcmeModelInstance model, String system, String component) { - super ("deleteComponent", model, system, component); + public DeleteComponentCmd (String commandName, AcmeModelInstance model, String system, String component) { + super (commandName, model, system, component); m_component = component; } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteConnectorCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteConnectorCmd.java index 01c56a8a4..4519b6af3 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteConnectorCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteConnectorCmd.java @@ -16,8 +16,8 @@ public class DeleteConnectorCmd extends AcmeModelOperation { private String m_connector; private IAcmeConnectorDeleteCommand m_deleteConnectorCmd; - public DeleteConnectorCmd (AcmeModelInstance model, String system, String connector) { - super ("deleteConnector", model, system, connector); + public DeleteConnectorCmd (String commandName, AcmeModelInstance model, String system, String connector) { + super (commandName, model, system, connector); m_connector = connector; } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeletePortCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeletePortCmd.java index 541290d12..346cf4fc4 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeletePortCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeletePortCmd.java @@ -17,8 +17,8 @@ public class DeletePortCmd extends RosAcmeModelCommand { private String m_port; private IAcmePortDeleteCommand m_deleteCommand; - public DeletePortCmd (AcmeModelInstance model, String component, String port) { - super ("deletePort", model, component, port); + public DeletePortCmd (String commandName, AcmeModelInstance model, String component, String port) { + super (commandName, model, component, port); m_component = component; m_port = port; diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteRoleCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteRoleCmd.java index 2272b197c..f0181f8e2 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteRoleCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/DeleteRoleCmd.java @@ -17,8 +17,8 @@ public class DeleteRoleCmd extends RosAcmeModelCommand { private String m_role; private IAcmeRoleDeleteCommand m_deleteCommand; - public DeleteRoleCmd (AcmeModelInstance model, String connector, String role) { - super ("deleteRole", model, connector, role); + public DeleteRoleCmd (String commandName, AcmeModelInstance model, String connector, String role) { + super (commandName, model, connector, role); m_connector = connector; m_role = role; diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/RosModelCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/RosModelCommandFactory.java index 1ad3d522c..0aad836f9 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/RosModelCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/RosModelCommandFactory.java @@ -12,93 +12,99 @@ import org.acmestudio.acme.element.IAcmeRole; import org.acmestudio.acme.element.IAcmeRoleType; import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.core.error.RainbowException; import org.sa.rainbow.core.models.ModelsManager; import org.sa.rainbow.model.acme.AcmeModelCommandFactory; import org.sa.rainbow.model.acme.AcmeModelInstance; public class RosModelCommandFactory extends AcmeModelCommandFactory { - public static RosLoadModelCommand + private static final String CREATE_TOPIC_CONNECTOR_CMD = "createTopicConnector"; + private static final String CREATE_TOPIC_ROLE_CMD = "createTopicRole"; + private static final String CREATE_ACTION_CONNECTOR_CMD = "createActionConnector"; + private static final String CREATE_ACTION_ROLE_CMD = "createActionRole"; + private static final String CREATE_SERVICE_PORT_CMD = "createServicePort"; + private static final String CREATE_TOPIC_PORT_CMD = "createTopicPort"; + private static final String CREATE_ACTION_PORT_CMD = "createActionPort"; + private static final String DELETE_CONNECTOR_CMD = "deleteConnector"; + private static final String DELETE_COMPONENT_CMD = "deleteComponent"; + private static final String ATTACH_CMD = "attach"; + private static final String DELETE_ROLE_CMD = "deleteRole"; + private static final String DELETE_PORT_CMD = "deletePort"; + private static final String CREATE_NODE_MANAGER_CMD = "createNodeManager"; + private static final String CREATE_NODE_CMD = "createNode"; + private static final String SET_SYSTEM_CMD = "setSystem"; + + public static RosLoadModelCommand loadCommand (ModelsManager modelsManager, String modelName, InputStream stream, String source) { return new RosLoadModelCommand (modelName, modelsManager, stream, source); } - public RosModelCommandFactory (AcmeModelInstance model) { + public RosModelCommandFactory (AcmeModelInstance model) throws RainbowException { super (model); } - @Override - protected void fillInCommandMap () { - super.fillInCommandMap (); - m_commandMap.put ("setSystem".toLowerCase (), SetSystemCommand.class); - m_commandMap.put ("createNode".toLowerCase (), CreateRosNodeCommand.class); - m_commandMap.put ("createNodeManager".toLowerCase (), CreateRosNodeCommand.class); - m_commandMap.put ("deletePort".toLowerCase (), DeletePortCmd.class); - m_commandMap.put ("deleteRole".toLowerCase (), DeleteRoleCmd.class); - m_commandMap.put ("attach".toLowerCase (), AttachCmd.class); - m_commandMap.put ("deleteComponent".toLowerCase (), DeleteComponentCmd.class); - m_commandMap.put ("deleteConnector".toLowerCase (), DeleteConnectorCmd.class); - m_commandMap.put ("createActionPort".toLowerCase (), CreateActionPortCommand.class); - m_commandMap.put ("createTopicPort".toLowerCase (), CreateTopicPortCommand.class); - m_commandMap.put ("createServicePort".toLowerCase (), CreateServicePortCommand.class); - m_commandMap.put ("createActionRole".toLowerCase (), CreateActionRoleCommand.class); - m_commandMap.put ("createActionConnector".toLowerCase (), CreateActionConnectorCommand.class); - m_commandMap.put ("createTopicRole".toLowerCase (), CreateTopicRoleCommand.class); - m_commandMap.put ("createTopicConnector".toLowerCase (), CreateTopicConnectorCommand.class); - - } - + + @Operation(name=SET_SYSTEM_CMD) public SetSystemCommand setSystem (IAcmeSystem system, String systemSource) { - return new SetSystemCommand ((AcmeModelInstance )m_modelInstance, "", systemSource); + return new SetSystemCommand (SET_SYSTEM_CMD, (AcmeModelInstance )m_modelInstance, "", systemSource); } + @Operation(name=CREATE_NODE_CMD) public CreateRosNodeCommand createNode (IAcmeSystem system, String nodeName) { if (ModelHelper.getAcmeSystem (system) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); - return new CreateRosNodeCommand ((AcmeModelInstance )m_modelInstance, system.getQualifiedName (), nodeName); + return new CreateRosNodeCommand (CREATE_NODE_CMD, (AcmeModelInstance )m_modelInstance, system.getQualifiedName (), nodeName); } + @Operation(name=CREATE_NODE_MANAGER_CMD) public CreateRosNodeManagerCommand createNodeManager (IAcmeSystem system, String nodeName) { if (ModelHelper.getAcmeSystem (system) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); - return new CreateRosNodeManagerCommand ((AcmeModelInstance )m_modelInstance, system.getQualifiedName (), + return new CreateRosNodeManagerCommand (CREATE_NODE_MANAGER_CMD, (AcmeModelInstance )m_modelInstance, system.getQualifiedName (), nodeName); } - + + @Operation(name=DELETE_PORT_CMD) public DeletePortCmd deletePort (IAcmeComponent comp, String port) { if (ModelHelper.getAcmeSystem (comp) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); - return new DeletePortCmd ((AcmeModelInstance )m_modelInstance, comp.getQualifiedName (), port); + return new DeletePortCmd (DELETE_PORT_CMD, (AcmeModelInstance )m_modelInstance, comp.getQualifiedName (), port); } + @Operation(name=DELETE_ROLE_CMD) public DeleteRoleCmd deleteRole (IAcmeComponent comp, String Role) { if (ModelHelper.getAcmeSystem (comp) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); - return new DeleteRoleCmd ((AcmeModelInstance )m_modelInstance, comp.getQualifiedName (), Role); + return new DeleteRoleCmd (DELETE_ROLE_CMD, (AcmeModelInstance )m_modelInstance, comp.getQualifiedName (), Role); } + @Operation(name=ATTACH_CMD) public AttachCmd attach (IAcmePort port, IAcmeRole role) { IAcmeSystem sys = ModelHelper.getAcmeSystem (port); if (sys != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); - return new AttachCmd ((AcmeModelInstance )m_modelInstance, "", port.getQualifiedName (), + return new AttachCmd (ATTACH_CMD, (AcmeModelInstance )m_modelInstance, "", port.getQualifiedName (), role.getQualifiedName ()); } + @Operation(name=DELETE_COMPONENT_CMD) public DeleteComponentCmd deleteComponent (IAcmeSystem sys, IAcmeComponent comp) { if (ModelHelper.getAcmeSystem (comp) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); - return new DeleteComponentCmd ((AcmeModelInstance )m_modelInstance, sys.getQualifiedName (), + return new DeleteComponentCmd (DELETE_COMPONENT_CMD, (AcmeModelInstance )m_modelInstance, sys.getQualifiedName (), comp.getQualifiedName ()); } + @Operation(name=DELETE_CONNECTOR_CMD) public DeleteConnectorCmd deleteConnector (IAcmeSystem sys, IAcmeConnector comp) { if (ModelHelper.getAcmeSystem (comp) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); - return new DeleteConnectorCmd ((AcmeModelInstance )m_modelInstance, sys.getQualifiedName (), + return new DeleteConnectorCmd (DELETE_CONNECTOR_CMD, (AcmeModelInstance )m_modelInstance, sys.getQualifiedName (), comp.getQualifiedName ()); } + @Operation(name=CREATE_ACTION_PORT_CMD) public CreateActionPortCommand createActionPort (IAcmeComponent comp, String portName, IAcmeElementType portType) { if (ModelHelper.getAcmeSystem (comp) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); @@ -106,10 +112,11 @@ public CreateActionPortCommand createActionPort (IAcmeComponent comp, String por throw new IllegalArgumentException ("Cannot create a port with something that is not a port type"); if (comp.getPort (portName) != null) throw new IllegalArgumentException ("Port already exists in " + comp.getQualifiedName ()); - return new CreateActionPortCommand ((AcmeModelInstance )m_modelInstance, comp.getQualifiedName (), portName, + return new CreateActionPortCommand (CREATE_ACTION_PORT_CMD, (AcmeModelInstance )m_modelInstance, comp.getQualifiedName (), portName, portType.getName ()); } + @Operation(name=CREATE_TOPIC_PORT_CMD) public CreateTopicPortCommand createTopicPort (IAcmeComponent comp, String portName, IAcmeElementType portType) { if (ModelHelper.getAcmeSystem (comp) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); @@ -117,10 +124,11 @@ public CreateTopicPortCommand createTopicPort (IAcmeComponent comp, String portN throw new IllegalArgumentException ("Cannot create a port with something that is not a port type"); if (comp.getPort (portName) != null) throw new IllegalArgumentException ("Port already exists in " + comp.getQualifiedName ()); - return new CreateTopicPortCommand ((AcmeModelInstance )m_modelInstance, comp.getQualifiedName (), portName, + return new CreateTopicPortCommand (CREATE_TOPIC_PORT_CMD, (AcmeModelInstance )m_modelInstance, comp.getQualifiedName (), portName, portType.getName ()); } + @Operation(name=CREATE_SERVICE_PORT_CMD) public CreateServicePortCommand createServicePort (IAcmeComponent comp, String portName, IAcmeElementType portType) { if (ModelHelper.getAcmeSystem (comp) != m_modelInstance.getModelInstance ()) @@ -129,10 +137,11 @@ public CreateTopicPortCommand createTopicPort (IAcmeComponent comp, String portN throw new IllegalArgumentException ("Cannot create a port with something that is not a port type"); if (comp.getPort (portName) != null) throw new IllegalArgumentException ("Port already exists in " + comp.getQualifiedName ()); - return new CreateServicePortCommand ((AcmeModelInstance )m_modelInstance, comp.getQualifiedName (), portName, + return new CreateServicePortCommand (CREATE_SERVICE_PORT_CMD, (AcmeModelInstance )m_modelInstance, comp.getQualifiedName (), portName, portType.getName ()); } + @Operation(name=CREATE_ACTION_ROLE_CMD) public CreateActionRoleCommand createActionRole (IAcmeConnector conn, String roleName, IAcmeElementType roleType) { if (ModelHelper.getAcmeSystem (conn) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); @@ -140,18 +149,20 @@ public CreateActionRoleCommand createActionRole (IAcmeConnector conn, String rol throw new IllegalArgumentException ("Cannot create a role with something that is not a role type"); if (conn.getRole (roleName) != null) throw new IllegalArgumentException ("Role already exists in " + conn.getQualifiedName ()); - return new CreateActionRoleCommand ((AcmeModelInstance )m_modelInstance, conn.getQualifiedName (), roleName, + return new CreateActionRoleCommand (CREATE_ACTION_ROLE_CMD, (AcmeModelInstance )m_modelInstance, conn.getQualifiedName (), roleName, roleType.getName ()); } + @Operation(name=CREATE_ACTION_CONNECTOR_CMD) public CreateActionConnectorCommand createActionConnector (IAcmeSystem sys, String connName) { if (ModelHelper.getAcmeSystem (sys) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); if (sys.lookupName (connName, false) != null) throw new IllegalArgumentException ("Name already exists in " + sys.getName ()); - return new CreateActionConnectorCommand ((AcmeModelInstance )m_modelInstance, sys.getName (), connName); + return new CreateActionConnectorCommand (CREATE_ACTION_CONNECTOR_CMD, (AcmeModelInstance )m_modelInstance, sys.getName (), connName); } + @Operation(name=CREATE_TOPIC_ROLE_CMD) public CreateTopicRoleCommand createTopicRole (IAcmeConnector conn, String roleName, IAcmeElementType roleType) { if (ModelHelper.getAcmeSystem (conn) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); @@ -159,17 +170,18 @@ public CreateTopicRoleCommand createTopicRole (IAcmeConnector conn, String roleN throw new IllegalArgumentException ("Cannot create a role with something that is not a role type"); if (conn.getRole (roleName) != null) throw new IllegalArgumentException ("Role already exists in " + conn.getQualifiedName ()); - return new CreateTopicRoleCommand ((AcmeModelInstance )m_modelInstance, conn.getQualifiedName (), roleName, + return new CreateTopicRoleCommand (CREATE_TOPIC_ROLE_CMD, (AcmeModelInstance )m_modelInstance, conn.getQualifiedName (), roleName, roleType.getName ()); } + @Operation(name=CREATE_TOPIC_CONNECTOR_CMD) public CreateTopicConnectorCommand createTopicConnector (IAcmeSystem sys, String connName, String topic, String msgType) { if (ModelHelper.getAcmeSystem (sys) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); if (sys.lookupName (connName, false) != null) throw new IllegalArgumentException ("Name already exists in " + sys.getName ()); - return new CreateTopicConnectorCommand ((AcmeModelInstance )m_modelInstance, sys.getName (), connName, topic, + return new CreateTopicConnectorCommand (CREATE_TOPIC_CONNECTOR_CMD, (AcmeModelInstance )m_modelInstance, sys.getName (), connName, topic, msgType); } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/RosModelUpdateOperatorsImpl.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/RosModelUpdateOperatorsImpl.java index d54442520..3b0a8c4a3 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/RosModelUpdateOperatorsImpl.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/RosModelUpdateOperatorsImpl.java @@ -1,6 +1,7 @@ package org.sa.rainbow.brass.model.acme; import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.core.error.RainbowException; import org.sa.rainbow.model.acme.AcmeModelInstance; public class RosModelUpdateOperatorsImpl extends AcmeModelInstance { @@ -19,7 +20,11 @@ protected AcmeModelInstance generateInstance (IAcmeSystem sys) { @Override public RosModelCommandFactory getCommandFactory () { if (m_commandFactory == null) { - m_commandFactory = new RosModelCommandFactory (this); + try { + m_commandFactory = new RosModelCommandFactory (this); + } catch (RainbowException e) { + e.printStackTrace(); + } } return m_commandFactory; } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/SetSystemCommand.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/SetSystemCommand.java index e5c87f54d..a1bb7f99e 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/SetSystemCommand.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/acme/SetSystemCommand.java @@ -17,8 +17,8 @@ public class SetSystemCommand extends RosAcmeModelCommand { private IAcmeSystem m_system; private String m_systemAsString; - public SetSystemCommand (AcmeModelInstance model, String target, String newSystem) { - super ("setSystem", model, target, newSystem); + public SetSystemCommand (String commandName, AcmeModelInstance model, String target, String newSystem) { + super (commandName, model, target, newSystem); m_systemAsString = newSystem; } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/CancelInstructionsCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/CancelInstructionsCmd.java new file mode 100644 index 000000000..f2324ff03 --- /dev/null +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/CancelInstructionsCmd.java @@ -0,0 +1,59 @@ +package org.sa.rainbow.brass.model.instructions; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class CancelInstructionsCmd extends AbstractRainbowModelOperation { + + private LinkedList m_oldInstructions; + + public CancelInstructionsCmd(String commandName, IModelInstance model, + String target, String... parameters) { + super(commandName, model, target, parameters); + } + + @Override + public Boolean getResult() throws IllegalStateException { + // TODO Auto-generated method stub + return null; + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents(messageFactory, "cancelInstructions"); + } + + @Override + protected void subExecute() throws RainbowException { + Collection oldInst = getModelContext().getModelInstance().getInstructions(); + if (oldInst == null) + m_oldInstructions = new LinkedList(); + else + m_oldInstructions = new LinkedList(oldInst); + getModelContext().getModelInstance().setInstructions(Collections.emptyList()); + } + + @Override + protected void subRedo() throws RainbowException { + subExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + getModelContext ().getModelInstance ().setInstructions (m_oldInstructions); + } + + @Override + protected boolean checkModelValidForCommand(InstructionGraphProgress model) { + return true; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/ChargeInstruction.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/ChargeInstruction.java index 411f76180..9cabfe45f 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/ChargeInstruction.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/ChargeInstruction.java @@ -1,5 +1,6 @@ package org.sa.rainbow.brass.model.instructions; +import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -32,6 +33,11 @@ public String getInstruction() { public String getNextInstructionLabel() { return m_nextLabel; } + + @Override + public String toString() { + return MessageFormat.format("{0} -> Charge({1})", m_instruction, m_chargingTime); + } @Override public IInstruction copy() { diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphCommandFactory.java index 202919c79..2d26ee45b 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphCommandFactory.java @@ -1,56 +1,63 @@ -package org.sa.rainbow.brass.model.instructions; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -/** - * Created by schmerl on 12/9/2016. - */ -public class InstructionGraphCommandFactory extends ModelCommandFactory { - - public static InstructionGraphLoadCommand loadCommand (ModelsManager mm, String modelName, InputStream stream, - String source) { - return new InstructionGraphLoadCommand (modelName, mm, stream, source); - } - - - public InstructionGraphCommandFactory (InstructionGraphModelInstance model) { - super (InstructionGraphModelInstance.class, model); - } - - @Override - protected void fillInCommandMap () { - m_commandMap.put ("setInstructions".toLowerCase (), SetInstructionsCmd.class); - m_commandMap.put ("setExecutingInstruction".toLowerCase (), SetExecutingInstructionCmd.class); - m_commandMap.put ("setExecutionFailed".toLowerCase (), SetExecutionFailedCmd.class); - - } - - @Override - public SaveInstructionGraphCmd saveCommand (String location) throws RainbowModelException { - try (FileOutputStream os = new FileOutputStream (location)) { - return new SaveInstructionGraphCmd (null, location, os, m_modelInstance.getOriginalSource ()); - } - catch (IOException e) { - return null; - } - } - - public SetInstructionsCmd setInstructionsCmd (String instructionGraphCode) { - return new SetInstructionsCmd ((InstructionGraphModelInstance )m_modelInstance, "", instructionGraphCode); - } - - public SetExecutingInstructionCmd setExecutingInstructionCmd (String instructionLabel, String state) { - return new SetExecutingInstructionCmd ((InstructionGraphModelInstance )m_modelInstance, "", instructionLabel, - state); - } - - public SetExecutionFailedCmd setExecutionFailedCmd (String instructionLabel) { - return new SetExecutionFailedCmd ((InstructionGraphModelInstance )m_modelInstance, "", instructionLabel); - } -} +package org.sa.rainbow.brass.model.instructions; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +/** + * Created by schmerl on 12/9/2016. + */ +public class InstructionGraphCommandFactory extends ModelCommandFactory { + + private static final String CANCEL_INSTRUCTIONS_CMD = "cancelInstructions"; + private static final String SET_EXECUTION_FAILED_CMD = "setExecutionFailed"; + private static final String SET_EXECUTING_INSTRUCTION_CMD = "setExecutingInstruction"; + private static final String SET_INSTRUCTIONS_CMD = "setInstructions"; + + @LoadOperation + public static InstructionGraphLoadCommand loadCommand (ModelsManager mm, String modelName, InputStream stream, + String source) { + return new InstructionGraphLoadCommand (modelName, mm, stream, source); + } + + + public InstructionGraphCommandFactory (InstructionGraphModelInstance model) throws RainbowException { + super (InstructionGraphModelInstance.class, model); + } + + @Override + public SaveInstructionGraphCmd saveCommand (String location) throws RainbowModelException { + try (FileOutputStream os = new FileOutputStream (location)) { + return new SaveInstructionGraphCmd (null, location, os, m_modelInstance.getOriginalSource ()); + } + catch (IOException e) { + return null; + } + } + + @Operation(name=SET_INSTRUCTIONS_CMD) + public SetInstructionsCmd setInstructionsCmd (String instructionGraphCode) { + return new SetInstructionsCmd (SET_INSTRUCTIONS_CMD,(InstructionGraphModelInstance )m_modelInstance, "", instructionGraphCode); + } + + @Operation(name=CANCEL_INSTRUCTIONS_CMD) + public CancelInstructionsCmd cancelInstructionsCmd() { + return new CancelInstructionsCmd(CANCEL_INSTRUCTIONS_CMD, (InstructionGraphModelInstance )m_modelInstance, ""); + } + + @Operation(name=SET_EXECUTING_INSTRUCTION_CMD) + public SetExecutingInstructionCmd setExecutingInstructionCmd (String instructionLabel, String state) { + return new SetExecutingInstructionCmd (SET_EXECUTING_INSTRUCTION_CMD, (InstructionGraphModelInstance )m_modelInstance, "", instructionLabel, + state); + } + + @Operation(name=SET_EXECUTION_FAILED_CMD) + public SetExecutionFailedCmd setExecutionFailedCmd (String instructionLabel) { + return new SetExecutionFailedCmd (SET_EXECUTION_FAILED_CMD,(InstructionGraphModelInstance )m_modelInstance, "", instructionLabel); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphLoadCommand.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphLoadCommand.java index 2e0793a59..93bfa090d 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphLoadCommand.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphLoadCommand.java @@ -1,75 +1,75 @@ -package org.sa.rainbow.brass.model.instructions; - -import static org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.commons.io.IOUtils; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; - -/** - * Created by schmerl on 12/9/2016. - */ -public class InstructionGraphLoadCommand extends AbstractLoadModelCmd { - - private final String m_modelName; - private final InputStream m_stream; - private InstructionGraphModelInstance m_result; - - public InstructionGraphLoadCommand (String modelName, IModelsManager mm, InputStream is, String source) { - super ("loadInstructionGraph", mm, modelName, is, source); - m_modelName = modelName; - m_stream = is; - - } - - @Override - public InstructionGraphModelInstance getResult () throws IllegalStateException { - return m_result; - } - - @Override - public ModelReference getModelReference () { - return new ModelReference (m_modelName, INSTRUCTION_GRAPH_TYPE); - } - - @Override - protected void subExecute () throws RainbowException { - // Parse the instruction graph. This will be done very simply in the first instance through string manipulation - try { - if (m_stream != null) { - String str = IOUtils.toString (m_stream); - InstructionGraphProgress g = InstructionGraphProgress.parseFromString (getModelReference (), str); - m_result = new InstructionGraphModelInstance (g, getOriginalSource ()); - doPostExecute (); - } - else { - InstructionGraphProgress g = new InstructionGraphProgress (getModelReference ()); - m_result = new InstructionGraphModelInstance (g, getOriginalSource ()); - doPostExecute (); - } - } - catch (IOException e) { - throw new RainbowException (e); - } - } - - @Override - protected void subRedo () throws RainbowException { - doPostExecute (); - } - - @Override - protected void subUndo () throws RainbowException { - doPostUndo (); - } - - @Override - protected boolean checkModelValidForCommand (Object o) { - return true; - } -} +package org.sa.rainbow.brass.model.instructions; + +import static org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; + +/** + * Created by schmerl on 12/9/2016. + */ +public class InstructionGraphLoadCommand extends AbstractLoadModelCmd { + + private final String m_modelName; + private final InputStream m_stream; + private InstructionGraphModelInstance m_result; + + public InstructionGraphLoadCommand (String modelName, IModelsManager mm, InputStream is, String source) { + super ("loadInstructionGraph", mm, modelName, is, source); + m_modelName = modelName; + m_stream = is; + + } + + @Override + public InstructionGraphModelInstance getResult () throws IllegalStateException { + return m_result; + } + + @Override + public ModelReference getModelReference () { + return new ModelReference (m_modelName, INSTRUCTION_GRAPH_TYPE); + } + + @Override + protected void subExecute () throws RainbowException { + // Parse the instruction graph. This will be done very simply in the first instance through string manipulation + try { + if (m_stream != null) { + String str = IOUtils.toString (m_stream); + InstructionGraphProgress g = InstructionGraphProgress.parseFromString (getModelReference (), str); + m_result = new InstructionGraphModelInstance (g, getOriginalSource ()); + doPostExecute (); + } + else { + InstructionGraphProgress g = new InstructionGraphProgress (getModelReference ()); + m_result = new InstructionGraphModelInstance (g, getOriginalSource ()); + doPostExecute (); + } + } + catch (IOException e) { + throw new RainbowException (e); + } + } + + @Override + protected void subRedo () throws RainbowException { + doPostExecute (); + } + + @Override + protected void subUndo () throws RainbowException { + doPostUndo (); + } + + @Override + protected boolean checkModelValidForCommand (Object o) { + return true; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphModelInstance.java index 45627f4c1..5fd5f004a 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphModelInstance.java @@ -1,70 +1,73 @@ -package org.sa.rainbow.brass.model.instructions; - -import org.sa.rainbow.core.error.RainbowCopyException; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; - -/** - * Created by schmerl on 12/9/2016. - */ -public class InstructionGraphModelInstance implements IModelInstance{ - - - public static final String INSTRUCTION_GRAPH_TYPE = "InstructionGraphProgress"; - private InstructionGraphProgress m_graph; - private InstructionGraphCommandFactory m_commandFactory; - private String m_source; - - public InstructionGraphModelInstance (InstructionGraphProgress graph, String source) { - setModelInstance (graph); - setOriginalSource (source); - } - @Override - public InstructionGraphProgress getModelInstance () { - return m_graph; - } - - @Override - public void setModelInstance (InstructionGraphProgress model) { - m_graph = model; - } - - @Override - public IModelInstance copyModelInstance (String newName) throws RainbowCopyException { - return new InstructionGraphModelInstance (getModelInstance ().copy (), getOriginalSource ()); - } - - @Override - public String getModelType () { - return INSTRUCTION_GRAPH_TYPE; - } - - @Override - public String getModelName () { - return getModelInstance ().getModelReference ().getModelName (); - } - - @Override - public InstructionGraphCommandFactory getCommandFactory () { - if (m_commandFactory == null) { - m_commandFactory = new InstructionGraphCommandFactory (this); - } - return m_commandFactory; - } - - @Override - public void setOriginalSource (String source) { - m_source = source; - } - - @Override - public String getOriginalSource () { - return m_source; - } - - @Override - public void dispose () throws RainbowException { - m_graph = null; - m_source = null; - } -} +package org.sa.rainbow.brass.model.instructions; + +import org.sa.rainbow.core.error.RainbowCopyException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; + +/** + * Created by schmerl on 12/9/2016. + */ +public class InstructionGraphModelInstance implements IModelInstance{ + + + public static final String INSTRUCTION_GRAPH_TYPE = "InstructionGraphProgress"; + private InstructionGraphProgress m_graph; + private InstructionGraphCommandFactory m_commandFactory; + private String m_source; + + public InstructionGraphModelInstance (InstructionGraphProgress graph, String source) { + setModelInstance (graph); + setOriginalSource (source); + } + @Override + public InstructionGraphProgress getModelInstance () { + return m_graph; + } + + @Override + public void setModelInstance (InstructionGraphProgress model) { + m_graph = model; + } + + @Override + public IModelInstance copyModelInstance (String newName) throws RainbowCopyException { + return new InstructionGraphModelInstance (getModelInstance ().copy (), getOriginalSource ()); + } + + @Override + public String getModelType () { + return INSTRUCTION_GRAPH_TYPE; + } + + @Override + public String getModelName () { + return getModelInstance ().getModelReference ().getModelName (); + } + + @Override + public InstructionGraphCommandFactory getCommandFactory () { + if (m_commandFactory == null) { + try { + m_commandFactory = new InstructionGraphCommandFactory (this); + } catch (RainbowException e) { + } + } + return m_commandFactory; + } + + @Override + public void setOriginalSource (String source) { + m_source = source; + } + + @Override + public String getOriginalSource () { + return m_source; + } + + @Override + public void dispose () throws RainbowException { + m_graph = null; + m_source = null; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphProgress.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphProgress.java index ab0af34dd..62867453d 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphProgress.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/InstructionGraphProgress.java @@ -1,293 +1,293 @@ -package org.sa.rainbow.brass.model.instructions; - -import java.util.ArrayDeque; -import java.util.Collection; -import java.util.Collections; -import java.util.Deque; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.models.ModelReference; - -/** - * Created by schmerl on 12/9/2016. - */ -public class InstructionGraphProgress { - - public static enum IGExecutionStateT { - NONE, EXECUTING, FINISHED_SUCCESS, FINISHED_FAILED - } - - public static InstructionGraphProgress parseFromString (ModelReference ref, String igStr) { - // Remove all the returns from string - List instructions = parseFromString (igStr); - InstructionGraphProgress ig = new InstructionGraphProgress (ref); - ig.setInstructions (instructions); - return ig; - } - - public static List parseFromString (String igStr) { - List instructions = new LinkedList (); - igStr = igStr.replace ("\n", "").replace ("\r", ""); - igStr = igStr.replace("\\", ""); - igStr = igStr.substring (2); // Remove P( - String[] is = igStr.split ("V"); - Pattern instructionPattern = Pattern.compile ("\\((.*),.*do\\s+(.*) then (.*)\\).*"); - - for (String i : is) { - Matcher m = instructionPattern.matcher (i); - - if (m.matches ()) { - String label = m.group(1); - String instruction = m.group(2); - String nextLabel = m.group(3); - IInstruction inst2; - - if (instruction.startsWith(MoveAbsHInstruction.COMMAND_NAME)) { - inst2 = new MoveAbsHInstruction(label, instruction, nextLabel); - } - else if (instruction.startsWith (ForwardInstruction.COMMAND_NAME)) { - inst2 = new ForwardInstruction (label, instruction, nextLabel); - } - else if (instruction.startsWith (ChargeInstruction.COMMAND_NAME)) { - inst2 = new ChargeInstruction (label, instruction, nextLabel); - } - else if (instruction.startsWith (SetLocalizationFidelityInstruction.COMMAND_NAME)) { - inst2 = new SetLocalizationFidelityInstruction (label, instruction, nextLabel); - } - else if (instruction.startsWith(SetSensorInstruction.COMMAND_NAME)) { - inst2 = new SetSensorInstruction(label, instruction, nextLabel); - } - else if (instruction.startsWith(StartNodesInstruction.COMMAND_NAME)) { - inst2 = new StartNodesInstruction(label, instruction, nextLabel); - } - else if (instruction.startsWith(KillNodesInstruction.COMMAND_NAME)) { - inst2 = new KillNodesInstruction(label, instruction, nextLabel); - } - else if (instruction.startsWith(SetConfigInstruction.COMMAND_NAME)) { - inst2 = new SetConfigInstruction(label, instruction, nextLabel); - } - else if (instruction.startsWith(SetReconfiguringInstruction.COMMAND_NAME)) { - inst2 = new SetReconfiguringInstruction(label, instruction, nextLabel); - } - else { - //TODO - // Other ignorable instructions - inst2 = null; - System.out.print("IGERROR: " + label + ":" + instruction + ":" + nextLabel); - -// inst2 = new MoveAbsHInstruction(label, instruction, nextLabel); - } - - if (inst2 != null) { - instructions.add(inst2); - } - } - else { - System.out.println("IGERROR: " + i); - } - } - return instructions; - } - - public List getInstructions () { - return m_instructionList; - } - - /** - * - * @return The remaining instructions, excluding the current instruction, to be executed - */ - public List getRemainingInstructions () { - List remainingInstructions = new LinkedList<>(); - IInstruction instPtr = getCurrentInstruction(); - - while (instPtr != null && m_instructions.containsKey(instPtr.getNextInstructionLabel().trim())) { - String nextLabel = instPtr.getNextInstructionLabel().trim(); - IInstruction nextInstruction = m_instructions.get(nextLabel); - remainingInstructions.add(nextInstruction); - instPtr = m_instructions.get(nextLabel); - } - - return remainingInstructions; - } - - public IInstruction getInstruction (String instLabel) { - IInstruction inst = m_instructions.get (instLabel); - if (inst == null) return null; - return inst.copy (); - } - - public String getExecutingInstruction () { - return m_currentNode; - } - - public boolean getCurrentOK () { - return isCurrentOK(); - } - - public IInstruction getCurrentInstruction () { - return m_instructions.get (m_currentNode); - } - - public static class ExecutionObservation { - String label; - boolean successful; - long startTime; - long endTime; - } - - private Map m_instructions = new HashMap<> (); - private List m_instructionList = Collections. emptyList (); - private final ModelReference m_model; - private String m_currentNode; - private boolean m_currentOK = true; - private Deque m_executionHistory = new ArrayDeque<> (); - private IGExecutionStateT m_instructionGraphState = IGExecutionStateT.NONE; - - public InstructionGraphProgress (ModelReference model) { - m_model = model; - } - - public ModelReference getModelReference () { - return m_model; - } - - public InstructionGraphProgress copy () { - InstructionGraphProgress ig = new InstructionGraphProgress (m_model); - ig.m_instructions = new HashMap<> (); - ig.m_executionHistory = new ArrayDeque<> (m_executionHistory); - - for (Map.Entry i : m_instructions.entrySet ()) { - ig.m_instructions.put (i.getKey (), i.getValue ().copy ()); - } - - return ig; - } - - public void setInstructions (List instructions) { - m_instructionList = new LinkedList (instructions); - m_instructions.clear (); - for (IInstruction i : instructions) { - m_instructions.put (i.getInstructionLabel(), i); - } - setInstructionGraphState(IGExecutionStateT.NONE); - setCurrentOK(true); - } - - public void setExecutingInstruction (String instLabel, String state) { -// if (m_instructions.containsKey (instLabel)) { - m_currentNode = instLabel; - if (!isCurrentOK()) - { - setCurrentOK(true); -// } -// ExecutionObservation observation = new ExecutionObservation (); -// observation.startTime = new Date().getTime (); -// observation.label = instLabel; -// observation. -// m_executionHistory.push (observation); - } - if (m_instructions.get (m_currentNode) != null) { - if (m_instructions.get (m_instructions.get (m_currentNode).getNextInstructionLabel ()) == null - && "SUCCESS".equals (state)) { - setInstructionGraphState (IGExecutionStateT.FINISHED_SUCCESS); - } - else { - setInstructionGraphState (IGExecutionStateT.EXECUTING); - } - } - else { - setInstructionGraphState (IGExecutionStateT.EXECUTING); - } - - } - - public void setCurrentOK (boolean ok) { - m_currentOK = ok; - if (!m_currentOK) { - setInstructionGraphState (IGExecutionStateT.FINISHED_FAILED); - } - } - - public IGExecutionStateT getInstructionGraphState() { - return m_instructionGraphState; - } - - public void setInstructionGraphState (IGExecutionStateT instructionGraphState) { - m_instructionGraphState = instructionGraphState; - } - - public static List> segmentByInstructionType(List instructions, Class clz) { - List> segments = new LinkedList<> (); - List currentSegment = new LinkedList<>(); - Iterator it = instructions.iterator(); - while (it.hasNext()) { - IInstruction next = it.next(); - if (clz.isInstance(next)) { - if (!currentSegment.isEmpty()) { - if (!currentSegment.isEmpty()) segments.add(currentSegment); - currentSegment = new LinkedList<> (); - } - } - else { - currentSegment.add(next); - } - } - if (!currentSegment.isEmpty()) segments.add(currentSegment); - return segments; - } - - // Note: this assumes sequential instructions - @Override - public String toString () { - StringBuffer b = new StringBuffer (); - b.append ("P("); - if (!m_instructionList.isEmpty ()) { - outputInstruction (m_instructionList.get (0), 1, b); - b.append ("\n"); - int i = 0; - for (i = 1; i < m_instructionList.size (); i++) { - outputInstruction (m_instructionList.get (i), i + 1, b); - b.append ("::\n"); - } - b.append ("V("); - b.append (i + 1); - b.append (", end)::\n"); - } - b.append ("nil)"); - return b.toString (); - } - - private void outputInstruction (IInstruction instruction, int i, StringBuffer b) { - b.append ("V("); - b.append (i); - b.append (", do "); - b.append (instruction.getInstruction()); - b.append (" then "); - b.append (i + 1); - b.append (")"); - } - - public static void main (String[] args) { - InstructionGraphProgress ip = parseFromString (new ModelReference ("test", "test"), - "[P(V(1, do SetReconfiguring(1) then 2),V(2, do KillNodes(%mapServer%)\\\r\n" + - " \\ then 3)::V(3, do KillNodes(%laserscanNodelet%) then 4)::V(4, do KillNodes(%amcl%)\\\r\n" + - " \\ then 5)::V(5, do SetSensor (%CAMERA%, %on%) then 6)::V(6, do StartNodes(%aruco%)\\\r\n" + - " \\ then 7)::V(7, do StartNodes(%mapServerObs%) then 8)::V(8, do SetReconfiguring(0)\\\r\n" + - " \\ then 9)::V(9, do MoveAbsH(-6.22, 0.00, 0.25, 1.5708) then 10)::V(10, do MoveAbsH(-6.22,\\\r\n" + - " \\ 10.27, 0.25, 1.5708) then 11)::V(11, end)::nil)"); - IInstruction instruction = ip.getInstruction ("5"); - System.out.println (); - } - - private boolean isCurrentOK() { - return m_currentOK; - } - -} +package org.sa.rainbow.brass.model.instructions; + +import java.util.ArrayDeque; +import java.util.Collection; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.models.ModelReference; + +/** + * Created by schmerl on 12/9/2016. + */ +public class InstructionGraphProgress { + + public static enum IGExecutionStateT { + NONE, EXECUTING, FINISHED_SUCCESS, FINISHED_FAILED + } + + public static InstructionGraphProgress parseFromString (ModelReference ref, String igStr) { + // Remove all the returns from string + List instructions = parseFromString (igStr); + InstructionGraphProgress ig = new InstructionGraphProgress (ref); + ig.setInstructions (instructions); + return ig; + } + + public static List parseFromString (String igStr) { + List instructions = new LinkedList (); + igStr = igStr.replace ("\n", "").replace ("\r", ""); + igStr = igStr.replace("\\", ""); + igStr = igStr.substring (2); // Remove P( + String[] is = igStr.split ("V"); + Pattern instructionPattern = Pattern.compile ("\\((.*),.*do\\s+(.*) then (.*)\\).*"); + + for (String i : is) { + Matcher m = instructionPattern.matcher (i); + + if (m.matches ()) { + String label = m.group(1); + String instruction = m.group(2); + String nextLabel = m.group(3); + IInstruction inst2; + + if (instruction.startsWith(MoveAbsHInstruction.COMMAND_NAME)) { + inst2 = new MoveAbsHInstruction(label, instruction, nextLabel); + } + else if (instruction.startsWith (ForwardInstruction.COMMAND_NAME)) { + inst2 = new ForwardInstruction (label, instruction, nextLabel); + } + else if (instruction.startsWith (ChargeInstruction.COMMAND_NAME)) { + inst2 = new ChargeInstruction (label, instruction, nextLabel); + } + else if (instruction.startsWith (SetLocalizationFidelityInstruction.COMMAND_NAME)) { + inst2 = new SetLocalizationFidelityInstruction (label, instruction, nextLabel); + } + else if (instruction.startsWith(SetSensorInstruction.COMMAND_NAME)) { + inst2 = new SetSensorInstruction(label, instruction, nextLabel); + } + else if (instruction.startsWith(StartNodesInstruction.COMMAND_NAME)) { + inst2 = new StartNodesInstruction(label, instruction, nextLabel); + } + else if (instruction.startsWith(KillNodesInstruction.COMMAND_NAME)) { + inst2 = new KillNodesInstruction(label, instruction, nextLabel); + } + else if (instruction.startsWith(SetConfigInstruction.COMMAND_NAME)) { + inst2 = new SetConfigInstruction(label, instruction, nextLabel); + } + else if (instruction.startsWith(SetReconfiguringInstruction.COMMAND_NAME)) { + inst2 = new SetReconfiguringInstruction(label, instruction, nextLabel); + } + else { + //TODO + // Other ignorable instructions + inst2 = null; + System.out.print("IGERROR: " + label + ":" + instruction + ":" + nextLabel); + +// inst2 = new MoveAbsHInstruction(label, instruction, nextLabel); + } + + if (inst2 != null) { + instructions.add(inst2); + } + } + else { + System.out.println("IGERROR: " + i); + } + } + return instructions; + } + + public List getInstructions () { + return m_instructionList; + } + + /** + * + * @return The remaining instructions, excluding the current instruction, to be executed + */ + public List getRemainingInstructions () { + List remainingInstructions = new LinkedList<>(); + IInstruction instPtr = getCurrentInstruction(); + + while (instPtr != null && m_instructions.containsKey(instPtr.getNextInstructionLabel().trim())) { + String nextLabel = instPtr.getNextInstructionLabel().trim(); + IInstruction nextInstruction = m_instructions.get(nextLabel); + remainingInstructions.add(nextInstruction); + instPtr = m_instructions.get(nextLabel); + } + + return remainingInstructions; + } + + public IInstruction getInstruction (String instLabel) { + IInstruction inst = m_instructions.get (instLabel); + if (inst == null) return null; + return inst.copy (); + } + + public String getExecutingInstruction () { + return m_currentNode; + } + + public boolean getCurrentOK () { + return isCurrentOK(); + } + + public IInstruction getCurrentInstruction () { + return m_instructions.get (m_currentNode); + } + + public static class ExecutionObservation { + String label; + boolean successful; + long startTime; + long endTime; + } + + private Map m_instructions = new HashMap<> (); + private List m_instructionList = Collections. emptyList (); + private final ModelReference m_model; + private String m_currentNode; + private boolean m_currentOK = true; + private Deque m_executionHistory = new ArrayDeque<> (); + private IGExecutionStateT m_instructionGraphState = IGExecutionStateT.NONE; + + public InstructionGraphProgress (ModelReference model) { + m_model = model; + } + + public ModelReference getModelReference () { + return m_model; + } + + public InstructionGraphProgress copy () { + InstructionGraphProgress ig = new InstructionGraphProgress (m_model); + ig.m_instructions = new HashMap<> (); + ig.m_executionHistory = new ArrayDeque<> (m_executionHistory); + + for (Map.Entry i : m_instructions.entrySet ()) { + ig.m_instructions.put (i.getKey (), i.getValue ().copy ()); + } + + return ig; + } + + public void setInstructions (List instructions) { + m_instructionList = new LinkedList (instructions); + m_instructions.clear (); + for (IInstruction i : instructions) { + m_instructions.put (i.getInstructionLabel(), i); + } + setInstructionGraphState(IGExecutionStateT.NONE); + setCurrentOK(true); + } + + public void setExecutingInstruction (String instLabel, String state) { +// if (m_instructions.containsKey (instLabel)) { + m_currentNode = instLabel; + if (!isCurrentOK()) + { + setCurrentOK(true); +// } +// ExecutionObservation observation = new ExecutionObservation (); +// observation.startTime = new Date().getTime (); +// observation.label = instLabel; +// observation. +// m_executionHistory.push (observation); + } + if (m_instructions.get (m_currentNode) != null) { + if (m_instructions.get (m_instructions.get (m_currentNode).getNextInstructionLabel ()) == null + && "SUCCESS".equals (state)) { + setInstructionGraphState (IGExecutionStateT.FINISHED_SUCCESS); + } + else { + setInstructionGraphState (IGExecutionStateT.EXECUTING); + } + } + else { + setInstructionGraphState (IGExecutionStateT.EXECUTING); + } + + } + + public void setCurrentOK (boolean ok) { + m_currentOK = ok; + if (!m_currentOK) { + setInstructionGraphState (IGExecutionStateT.FINISHED_FAILED); + } + } + + public IGExecutionStateT getInstructionGraphState() { + return m_instructionGraphState; + } + + public void setInstructionGraphState (IGExecutionStateT instructionGraphState) { + m_instructionGraphState = instructionGraphState; + } + + public static List> segmentByInstructionType(List instructions, Class clz) { + List> segments = new LinkedList<> (); + List currentSegment = new LinkedList<>(); + Iterator it = instructions.iterator(); + while (it.hasNext()) { + IInstruction next = it.next(); + if (clz.isInstance(next)) { + if (!currentSegment.isEmpty()) { + if (!currentSegment.isEmpty()) segments.add(currentSegment); + currentSegment = new LinkedList<> (); + } + } + else { + currentSegment.add(next); + } + } + if (!currentSegment.isEmpty()) segments.add(currentSegment); + return segments; + } + + // Note: this assumes sequential instructions + @Override + public String toString () { + StringBuffer b = new StringBuffer (); + b.append ("P("); + if (!m_instructionList.isEmpty ()) { + outputInstruction (m_instructionList.get (0), 1, b); + b.append ("\n"); + int i = 0; + for (i = 1; i < m_instructionList.size (); i++) { + outputInstruction (m_instructionList.get (i), i + 1, b); + b.append ("::\n"); + } + b.append ("V("); + b.append (i + 1); + b.append (", end)::\n"); + } + b.append ("nil)"); + return b.toString (); + } + + private void outputInstruction (IInstruction instruction, int i, StringBuffer b) { + b.append ("V("); + b.append (i); + b.append (", do "); + b.append (instruction.getInstruction()); + b.append (" then "); + b.append (i + 1); + b.append (")"); + } + + public static void main (String[] args) { + InstructionGraphProgress ip = parseFromString (new ModelReference ("test", "test"), + "[P(V(1, do SetReconfiguring(1) then 2),V(2, do KillNodes(%mapServer%)\\\r\n" + + " \\ then 3)::V(3, do KillNodes(%laserscanNodelet%) then 4)::V(4, do KillNodes(%amcl%)\\\r\n" + + " \\ then 5)::V(5, do SetSensor (%CAMERA%, %on%) then 6)::V(6, do StartNodes(%aruco%)\\\r\n" + + " \\ then 7)::V(7, do StartNodes(%mapServerObs%) then 8)::V(8, do SetReconfiguring(0)\\\r\n" + + " \\ then 9)::V(9, do MoveAbsH(-6.22, 0.00, 0.25, 1.5708) then 10)::V(10, do MoveAbsH(-6.22,\\\r\n" + + " \\ 10.27, 0.25, 1.5708) then 11)::V(11, end)::nil)"); + IInstruction instruction = ip.getInstruction ("5"); + System.out.println (); + } + + private boolean isCurrentOK() { + return m_currentOK; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/KillNodesInstruction.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/KillNodesInstruction.java index c7aa33d5d..afae66135 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/KillNodesInstruction.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/KillNodesInstruction.java @@ -1,61 +1,61 @@ -package org.sa.rainbow.brass.model.instructions; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class KillNodesInstruction implements IInstruction { - public static final String COMMAND_NAME = "KillNodes"; - private String m_label; - private String m_instruction; - private String m_nextLabel; - private String m_node; - - public KillNodesInstruction(String label, String instruction, String nextLabel) { - m_label = label; - m_instruction = instruction; - m_nextLabel = nextLabel; - - parseInformation(); - } - - private void parseInformation() { - Pattern startPattern = Pattern.compile(COMMAND_NAME+"\\s*\\((.+)\\)"); - Matcher m = startPattern.matcher(m_instruction.trim()); - if (m.matches()) { - m_node = extractContents(m.group(1)); - } - } - - private String extractContents(String s) { - if (s.startsWith("%") || s.startsWith("\"")) - s = s.substring(1); - if (s.endsWith("%") || s.endsWith("\"")) - s = s.substring(0, s.length()-1); - return s; - } - - @Override - public String getInstructionLabel() { - return m_label; - } - - @Override - public String getInstruction() { - return m_instruction; - } - - @Override - public String getNextInstructionLabel() { - return m_nextLabel; - } - - @Override - public IInstruction copy() { - return new KillNodesInstruction(m_label, m_instruction, m_nextLabel); - } - - public String getNode() { - return m_node; - } - -} +package org.sa.rainbow.brass.model.instructions; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class KillNodesInstruction implements IInstruction { + public static final String COMMAND_NAME = "KillNodes"; + private String m_label; + private String m_instruction; + private String m_nextLabel; + private String m_node; + + public KillNodesInstruction(String label, String instruction, String nextLabel) { + m_label = label; + m_instruction = instruction; + m_nextLabel = nextLabel; + + parseInformation(); + } + + private void parseInformation() { + Pattern startPattern = Pattern.compile(COMMAND_NAME+"\\s*\\((.+)\\)"); + Matcher m = startPattern.matcher(m_instruction.trim()); + if (m.matches()) { + m_node = extractContents(m.group(1)); + } + } + + private String extractContents(String s) { + if (s.startsWith("%") || s.startsWith("\"")) + s = s.substring(1); + if (s.endsWith("%") || s.endsWith("\"")) + s = s.substring(0, s.length()-1); + return s; + } + + @Override + public String getInstructionLabel() { + return m_label; + } + + @Override + public String getInstruction() { + return m_instruction; + } + + @Override + public String getNextInstructionLabel() { + return m_nextLabel; + } + + @Override + public IInstruction copy() { + return new KillNodesInstruction(m_label, m_instruction, m_nextLabel); + } + + public String getNode() { + return m_node; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/MoveAbsHInstruction.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/MoveAbsHInstruction.java index 0bf436c80..037d35bf9 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/MoveAbsHInstruction.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/MoveAbsHInstruction.java @@ -1,5 +1,6 @@ package org.sa.rainbow.brass.model.instructions; +import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -99,6 +100,11 @@ private void parseMoveAbsHTargetPose () { System.out.println ("Error matching instruction: " + m_instruction); } } + + @Override + public String toString() { + return MessageFormat.format("{0} -> MoveAbsH({1},{2},{3}) {4}->{5}", m_instruction.trim(), m_targetX, m_targetY, m_speed, m_srcWaypoint==null?"?":m_srcWaypoint,m_tgtWaypoint==null?"?":m_tgtWaypoint); + } @Override public boolean equals (Object obj) { diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SaveInstructionGraphCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SaveInstructionGraphCmd.java index 34d81143a..b27ac5c41 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SaveInstructionGraphCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SaveInstructionGraphCmd.java @@ -1,51 +1,51 @@ -package org.sa.rainbow.brass.model.instructions; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; - -import java.io.FileOutputStream; -import java.io.PrintStream; - -/** - * Created by schmerl on 12/9/2016. - */ -public class SaveInstructionGraphCmd extends AbstractSaveModelCmd { - public SaveInstructionGraphCmd (IModelsManager mm, String location, FileOutputStream os, String source) { - super ("saveInstructionGraph", mm, location, os, source); - } - - @Override - public Object getResult () throws IllegalStateException { - return null; - } - - @Override - public ModelReference getModelReference () { - return new ModelReference ("", "InstructionGraphProgress"); - } - - @Override - protected void subExecute () throws RainbowException { - InstructionGraphProgress model = getModelContext ().getModelInstance (); - try (PrintStream ps = new PrintStream (getStream ())) { - ps.print (model.toString ()); - } - } - - @Override - protected void subRedo () throws RainbowException { - - } - - @Override - protected void subUndo () throws RainbowException { - - } - - @Override - protected boolean checkModelValidForCommand (InstructionGraphProgress instructionGraph) { - return true; - } -} +package org.sa.rainbow.brass.model.instructions; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; + +import java.io.FileOutputStream; +import java.io.PrintStream; + +/** + * Created by schmerl on 12/9/2016. + */ +public class SaveInstructionGraphCmd extends AbstractSaveModelCmd { + public SaveInstructionGraphCmd (IModelsManager mm, String location, FileOutputStream os, String source) { + super ("saveInstructionGraph", mm, location, os, source); + } + + @Override + public Object getResult () throws IllegalStateException { + return null; + } + + @Override + public ModelReference getModelReference () { + return new ModelReference ("", "InstructionGraphProgress"); + } + + @Override + protected void subExecute () throws RainbowException { + InstructionGraphProgress model = getModelContext ().getModelInstance (); + try (PrintStream ps = new PrintStream (getStream ())) { + ps.print (model.toString ()); + } + } + + @Override + protected void subRedo () throws RainbowException { + + } + + @Override + protected void subUndo () throws RainbowException { + + } + + @Override + protected boolean checkModelValidForCommand (InstructionGraphProgress instructionGraph) { + return true; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetConfigInstruction.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetConfigInstruction.java index f481bec95..d2c6c634a 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetConfigInstruction.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetConfigInstruction.java @@ -1,54 +1,54 @@ -package org.sa.rainbow.brass.model.instructions; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class SetConfigInstruction implements IInstruction { - public static final String COMMAND_NAME = "SetCP1Config"; - - private String m_label; - private String m_instruction; - private String m_nextLabel; - - private String m_config; - - public SetConfigInstruction(String label, String instruction, String nextLabel) { - m_label = label; - m_instruction = instruction; - m_nextLabel = nextLabel; - - parseInformation(); - } - private void parseInformation() { - Pattern startPattern = Pattern.compile(COMMAND_NAME+"\\s*\\((.+)\\)"); - Matcher m = startPattern.matcher(m_instruction); - if (m.matches()) { - m_config = m.group(1); - } - } - - public String getConfig() { - return m_config; - } - - @Override - public String getInstructionLabel() { - return m_label; - } - - @Override - public String getInstruction() { - return m_instruction; - } - - @Override - public String getNextInstructionLabel() { - return m_nextLabel; - } - - @Override - public IInstruction copy() { - return new SetConfigInstruction(m_label, m_instruction, m_nextLabel); - } - -} +package org.sa.rainbow.brass.model.instructions; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class SetConfigInstruction implements IInstruction { + public static final String COMMAND_NAME = "SetCP1Config"; + + private String m_label; + private String m_instruction; + private String m_nextLabel; + + private String m_config; + + public SetConfigInstruction(String label, String instruction, String nextLabel) { + m_label = label; + m_instruction = instruction; + m_nextLabel = nextLabel; + + parseInformation(); + } + private void parseInformation() { + Pattern startPattern = Pattern.compile(COMMAND_NAME+"\\s*\\((.+)\\)"); + Matcher m = startPattern.matcher(m_instruction); + if (m.matches()) { + m_config = m.group(1); + } + } + + public String getConfig() { + return m_config; + } + + @Override + public String getInstructionLabel() { + return m_label; + } + + @Override + public String getInstruction() { + return m_instruction; + } + + @Override + public String getNextInstructionLabel() { + return m_nextLabel; + } + + @Override + public IInstruction copy() { + return new SetConfigInstruction(m_label, m_instruction, m_nextLabel); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetExecutingInstructionCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetExecutingInstructionCmd.java index 9d672a92c..5528d44c1 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetExecutingInstructionCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetExecutingInstructionCmd.java @@ -1,58 +1,58 @@ -package org.sa.rainbow.brass.model.instructions; - -import java.util.List; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -/** - * Created by schmerl on 12/9/2016. - */ -public class SetExecutingInstructionCmd extends AbstractRainbowModelOperation { - private String m_instructionLabel; - private String m_oldInstructionLabel; - private String m_state; - private String m_oldState; - - public SetExecutingInstructionCmd (InstructionGraphModelInstance modelInstance, String target, - String instructionLabel, String state) { - super ("setExecutingInstruction", modelInstance, "", instructionLabel, state); - m_instructionLabel = instructionLabel; - m_state = state; - } - - @Override - public String getResult () throws IllegalStateException { - return m_instructionLabel; - } - - @Override - protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setExecutingInstruction"); - } - - @Override - protected void subExecute () throws RainbowException { - m_oldInstructionLabel = getModelContext ().getModelInstance ().getExecutingInstruction (); - m_oldState = ""; // Hack - getModelContext ().getModelInstance ().setExecutingInstruction (m_instructionLabel, m_state); - } - - @Override - protected void subRedo () throws RainbowException { - getModelContext ().getModelInstance ().setExecutingInstruction (m_instructionLabel, m_state); - } - - @Override - protected void subUndo () throws RainbowException { - getModelContext ().getModelInstance ().setExecutingInstruction (m_oldInstructionLabel, m_oldState); - - } - - @Override - protected boolean checkModelValidForCommand (InstructionGraphProgress instructionGraph) { - return true; - } -} +package org.sa.rainbow.brass.model.instructions; + +import java.util.List; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +/** + * Created by schmerl on 12/9/2016. + */ +public class SetExecutingInstructionCmd extends AbstractRainbowModelOperation { + private String m_instructionLabel; + private String m_oldInstructionLabel; + private String m_state; + private String m_oldState; + + public SetExecutingInstructionCmd (String commandName, InstructionGraphModelInstance modelInstance, String target, + String instructionLabel, String state) { + super (commandName, modelInstance, "", instructionLabel, state); + m_instructionLabel = instructionLabel; + m_state = state; + } + + @Override + public String getResult () throws IllegalStateException { + return m_instructionLabel; + } + + @Override + protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { + return generateEvents (messageFactory, "setExecutingInstruction"); + } + + @Override + protected void subExecute () throws RainbowException { + m_oldInstructionLabel = getModelContext ().getModelInstance ().getExecutingInstruction (); + m_oldState = ""; // Hack + getModelContext ().getModelInstance ().setExecutingInstruction (m_instructionLabel, m_state); + } + + @Override + protected void subRedo () throws RainbowException { + getModelContext ().getModelInstance ().setExecutingInstruction (m_instructionLabel, m_state); + } + + @Override + protected void subUndo () throws RainbowException { + getModelContext ().getModelInstance ().setExecutingInstruction (m_oldInstructionLabel, m_oldState); + + } + + @Override + protected boolean checkModelValidForCommand (InstructionGraphProgress instructionGraph) { + return true; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetExecutionFailedCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetExecutionFailedCmd.java index 13c1b9c64..38afc6d7a 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetExecutionFailedCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetExecutionFailedCmd.java @@ -1,56 +1,56 @@ -package org.sa.rainbow.brass.model.instructions; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -import java.util.List; - -/** - * Created by schmerl on 12/9/2016. - */ -public class SetExecutionFailedCmd extends AbstractRainbowModelOperation { - private Boolean m_result; - private boolean m_old; - - - public SetExecutionFailedCmd (InstructionGraphModelInstance modelInstance, String target, String instructionLabel) { - super ("setExecutionFailed", modelInstance, target, instructionLabel); - } - - @Override - public Boolean getResult () throws IllegalStateException { - return m_result; - } - - @Override - protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setExecutionFailed"); - } - - @Override - protected void subExecute () throws RainbowException { - m_old = getModelContext ().getModelInstance ().getCurrentOK(); - Boolean b = Boolean.parseBoolean (getParameters ()[0]); - getModelContext ().getModelInstance ().setCurrentOK (b); - - } - - @Override - protected void subRedo () throws RainbowException { - Boolean b = Boolean.parseBoolean (getParameters ()[0]); - getModelContext ().getModelInstance ().setCurrentOK (b); - } - - @Override - protected void subUndo () throws RainbowException { - getModelContext ().getModelInstance ().setCurrentOK (m_old); - - } - - @Override - protected boolean checkModelValidForCommand (InstructionGraphProgress instructionGraph) { - return true; - } -} +package org.sa.rainbow.brass.model.instructions; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +import java.util.List; + +/** + * Created by schmerl on 12/9/2016. + */ +public class SetExecutionFailedCmd extends AbstractRainbowModelOperation { + private Boolean m_result; + private boolean m_old; + + + public SetExecutionFailedCmd (String commandName, InstructionGraphModelInstance modelInstance, String target, String instructionLabel) { + super (commandName, modelInstance, target, instructionLabel); + } + + @Override + public Boolean getResult () throws IllegalStateException { + return m_result; + } + + @Override + protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { + return generateEvents (messageFactory, getName()); + } + + @Override + protected void subExecute () throws RainbowException { + m_old = getModelContext ().getModelInstance ().getCurrentOK(); + Boolean b = Boolean.parseBoolean (getParameters ()[0]); + getModelContext ().getModelInstance ().setCurrentOK (b); + + } + + @Override + protected void subRedo () throws RainbowException { + Boolean b = Boolean.parseBoolean (getParameters ()[0]); + getModelContext ().getModelInstance ().setCurrentOK (b); + } + + @Override + protected void subUndo () throws RainbowException { + getModelContext ().getModelInstance ().setCurrentOK (m_old); + + } + + @Override + protected boolean checkModelValidForCommand (InstructionGraphProgress instructionGraph) { + return true; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetInstructionsCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetInstructionsCmd.java index 893debbe5..41d951fd3 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetInstructionsCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetInstructionsCmd.java @@ -1,64 +1,64 @@ -package org.sa.rainbow.brass.model.instructions; - -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -/** - * Created by schmerl on 12/9/2016. - */ -public class SetInstructionsCmd extends AbstractRainbowModelOperation, InstructionGraphProgress>{ - private final String m_instructionsStr; - private List m_result; - private List m_oldInstructions; - - public SetInstructionsCmd (InstructionGraphModelInstance modelInstance, String target, String instructionGraphCode) { - super ("setInstructions", modelInstance, target, instructionGraphCode); - m_instructionsStr = instructionGraphCode; - - } - - @Override - public List getResult () throws IllegalStateException { - return m_result; - } - - @Override - protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, getName ()); - } - - @Override - protected void subExecute () throws RainbowException { - List instructionList = InstructionGraphProgress.parseFromString (m_instructionsStr); - Collection oldInst = getModelContext ().getModelInstance () - .getInstructions (); - if (oldInst == null) { - m_oldInstructions = new LinkedList<> (); - } - else { - m_oldInstructions = new LinkedList (oldInst); - } - getModelContext ().getModelInstance ().setInstructions (instructionList); - } - - @Override - protected void subRedo () throws RainbowException { - subExecute (); - } - - @Override - protected void subUndo () throws RainbowException { - getModelContext ().getModelInstance ().setInstructions (m_oldInstructions); - } - - @Override - protected boolean checkModelValidForCommand (InstructionGraphProgress instructionGraph) { - return true; - } -} +package org.sa.rainbow.brass.model.instructions; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +/** + * Created by schmerl on 12/9/2016. + */ +public class SetInstructionsCmd extends AbstractRainbowModelOperation, InstructionGraphProgress>{ + private final String m_instructionsStr; + private List m_result; + private List m_oldInstructions; + + public SetInstructionsCmd (String commandName, InstructionGraphModelInstance modelInstance, String target, String instructionGraphCode) { + super (commandName, modelInstance, target, instructionGraphCode); + m_instructionsStr = instructionGraphCode; + + } + + @Override + public List getResult () throws IllegalStateException { + return m_result; + } + + @Override + protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { + return generateEvents (messageFactory, getName ()); + } + + @Override + protected void subExecute () throws RainbowException { + List instructionList = InstructionGraphProgress.parseFromString (m_instructionsStr); + Collection oldInst = getModelContext ().getModelInstance () + .getInstructions (); + if (oldInst == null) { + m_oldInstructions = new LinkedList<> (); + } + else { + m_oldInstructions = new LinkedList (oldInst); + } + getModelContext ().getModelInstance ().setInstructions (instructionList); + } + + @Override + protected void subRedo () throws RainbowException { + subExecute (); + } + + @Override + protected void subUndo () throws RainbowException { + getModelContext ().getModelInstance ().setInstructions (m_oldInstructions); + } + + @Override + protected boolean checkModelValidForCommand (InstructionGraphProgress instructionGraph) { + return true; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetSensorInstruction.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetSensorInstruction.java index 9745568fa..fb252cd8d 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetSensorInstruction.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/SetSensorInstruction.java @@ -1,77 +1,77 @@ -package org.sa.rainbow.brass.model.instructions; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; - -public class SetSensorInstruction implements IInstruction { - public static final String COMMAND_NAME = "SetSensor"; - - - private String m_label; - private String m_instruction; - private String m_nextLabel; - - private Sensors m_sensor; - private boolean m_enablement; - - public SetSensorInstruction(String label, String instruction, String nextLabel) { - m_label = label; - m_instruction = instruction; - m_nextLabel = nextLabel; - - parseSensorInformation(); - } - - private void parseSensorInformation() { - Pattern sensorPattern = Pattern.compile("SetSensor\\s*\\(\\s*(.+),\\s*(.+)\\)"); - Matcher m = sensorPattern.matcher(m_instruction); - if (m.matches()) { - String s = m.group(1); - String e = m.group(2); - s= extractContents(s); - e= extractContents(e); - m_sensor = Sensors.valueOf(s); - if ("on".equalsIgnoreCase(e)) m_enablement=true; - else if ("off".equalsIgnoreCase(e)) m_enablement=false; - else m_enablement = Boolean.getBoolean(e); - } - } - - private String extractContents(String s) { - if (s.startsWith("%") || s.startsWith("\"")) - s = s.substring(1); - if (s.endsWith("%") || s.endsWith("\"")) - s = s.substring(0, s.length()-1); - return s; - } - - @Override - public String getInstructionLabel() { - return m_label; - } - - @Override - public String getInstruction() { - return m_instruction; - } - - @Override - public String getNextInstructionLabel() { - return m_nextLabel; - } - - @Override - public IInstruction copy() { - SetSensorInstruction ss = new SetSensorInstruction(m_label, m_instruction, m_nextLabel); - ss.m_sensor = m_sensor; - ss.m_enablement = m_enablement; - return ss; - } - - public Sensors getSensor() {return m_sensor;} - - public boolean getEnablement() {return m_enablement;} - -} +package org.sa.rainbow.brass.model.instructions; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; + +public class SetSensorInstruction implements IInstruction { + public static final String COMMAND_NAME = "SetSensor"; + + + private String m_label; + private String m_instruction; + private String m_nextLabel; + + private Sensors m_sensor; + private boolean m_enablement; + + public SetSensorInstruction(String label, String instruction, String nextLabel) { + m_label = label; + m_instruction = instruction; + m_nextLabel = nextLabel; + + parseSensorInformation(); + } + + private void parseSensorInformation() { + Pattern sensorPattern = Pattern.compile("SetSensor\\s*\\(\\s*(.+),\\s*(.+)\\)"); + Matcher m = sensorPattern.matcher(m_instruction); + if (m.matches()) { + String s = m.group(1); + String e = m.group(2); + s= extractContents(s); + e= extractContents(e); + m_sensor = Sensors.valueOf(s); + if ("on".equalsIgnoreCase(e)) m_enablement=true; + else if ("off".equalsIgnoreCase(e)) m_enablement=false; + else m_enablement = Boolean.getBoolean(e); + } + } + + private String extractContents(String s) { + if (s.startsWith("%") || s.startsWith("\"")) + s = s.substring(1); + if (s.endsWith("%") || s.endsWith("\"")) + s = s.substring(0, s.length()-1); + return s; + } + + @Override + public String getInstructionLabel() { + return m_label; + } + + @Override + public String getInstruction() { + return m_instruction; + } + + @Override + public String getNextInstructionLabel() { + return m_nextLabel; + } + + @Override + public IInstruction copy() { + SetSensorInstruction ss = new SetSensorInstruction(m_label, m_instruction, m_nextLabel); + ss.m_sensor = m_sensor; + ss.m_enablement = m_enablement; + return ss; + } + + public Sensors getSensor() {return m_sensor;} + + public boolean getEnablement() {return m_enablement;} + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/StartNodesInstruction.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/StartNodesInstruction.java index dddc11a0e..3ae7fe68a 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/StartNodesInstruction.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/instructions/StartNodesInstruction.java @@ -1,61 +1,61 @@ -package org.sa.rainbow.brass.model.instructions; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class StartNodesInstruction implements IInstruction { - public static final String COMMAND_NAME = "StartNodes"; - private String m_label; - private String m_instruction; - private String m_nextLabel; - private String m_node; - - public StartNodesInstruction(String label, String instruction, String nextLabel) { - m_label = label; - m_instruction = instruction; - m_nextLabel = nextLabel; - - parseInformation (); - } - - private void parseInformation() { - Pattern startPattern = Pattern.compile(COMMAND_NAME+"\\s*\\((.+)\\)"); - Matcher m = startPattern.matcher(m_instruction.trim()); - if (m.matches()) { - m_node = extractContents(m.group(1)); - } - } - - private String extractContents(String s) { - if (s.startsWith("%") || s.startsWith("\"")) - s = s.substring(1); - if (s.endsWith("%") || s.endsWith("\"")) - s = s.substring(0, s.length()-1); - return s; - } - - @Override - public String getInstructionLabel() { - return m_label; - } - - @Override - public String getInstruction() { - return m_instruction; - } - - @Override - public String getNextInstructionLabel() { - return m_nextLabel; - } - - @Override - public IInstruction copy() { - return new StartNodesInstruction(m_label, m_instruction, m_nextLabel); - } - - public String getNode() { - return m_node; - } - -} +package org.sa.rainbow.brass.model.instructions; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class StartNodesInstruction implements IInstruction { + public static final String COMMAND_NAME = "StartNodes"; + private String m_label; + private String m_instruction; + private String m_nextLabel; + private String m_node; + + public StartNodesInstruction(String label, String instruction, String nextLabel) { + m_label = label; + m_instruction = instruction; + m_nextLabel = nextLabel; + + parseInformation (); + } + + private void parseInformation() { + Pattern startPattern = Pattern.compile(COMMAND_NAME+"\\s*\\((.+)\\)"); + Matcher m = startPattern.matcher(m_instruction.trim()); + if (m.matches()) { + m_node = extractContents(m.group(1)); + } + } + + private String extractContents(String s) { + if (s.startsWith("%") || s.startsWith("\"")) + s = s.substring(1); + if (s.endsWith("%") || s.endsWith("\"")) + s = s.substring(0, s.length()-1); + return s; + } + + @Override + public String getInstructionLabel() { + return m_label; + } + + @Override + public String getInstruction() { + return m_instruction; + } + + @Override + public String getNextInstructionLabel() { + return m_nextLabel; + } + + @Override + public IInstruction copy() { + return new StartNodesInstruction(m_label, m_instruction, m_nextLabel); + } + + public String getNode() { + return m_node; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMap.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMap.java index 8f42279b1..d80e21b80 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMap.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMap.java @@ -40,9 +40,8 @@ public EnvMap(ModelReference model, Properties props) { m_new_node_id = 0; m_arcs = new HashMap<>(); m_arcs_lookup = new LinkedList(); - // initWithSimpleMap(); // TODO: Substitute hardwired version of the map by one - // parsed from file - loadFromFile(props.getProperty(PropertiesConnector.MAP_PROPKEY)); + m_originalFile = props.getProperty(PropertiesConnector.MAP_PROPKEY); + loadFromFile(m_originalFile); } public EnvMap(ModelReference model) { @@ -52,6 +51,14 @@ public EnvMap(ModelReference model) { m_new_node_id = 0; m_arcs = new HashMap<>(); } + + public void reload() { + m_last_insertion = new NodeInsertion(); + m_nodes.clear(); + m_arcs.clear(); + m_arcs_lookup.clear(); + loadFromFile(m_originalFile); + } public ModelReference getModelReference() { return m_model; @@ -75,6 +82,7 @@ public synchronized EnvMap copy() { private int m_new_node_id; private final ModelReference m_model; + private String m_originalFile; public synchronized void updateArcsLookup() { m_arcs_lookup = new LinkedList(new LinkedHashSet(m_arcs.values())); diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMapCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMapCommandFactory.java index 1b1155557..38a33fbaa 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMapCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMapCommandFactory.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.io.InputStream; +import org.sa.rainbow.core.error.RainbowException; import org.sa.rainbow.core.error.RainbowModelException; import org.sa.rainbow.core.models.IModelInstance; import org.sa.rainbow.core.models.ModelsManager; @@ -12,10 +13,14 @@ public class EnvMapCommandFactory extends ModelCommandFactory { - public EnvMapCommandFactory (IModelInstance model) { + private static final String INSERT_NODE_CMD = "insertNode"; + + + public EnvMapCommandFactory (IModelInstance model) throws RainbowException { super (EnvMapModelInstance.class, model); } + @LoadOperation public static EnvMapLoadCmd loadCommand (ModelsManager mm, String modelName, InputStream stream, String source){ return new EnvMapLoadCmd (mm, modelName, stream, source); } @@ -30,12 +35,8 @@ public SaveEnvMapCmd saveCommand (String location) throws RainbowModelException } } - @Override - protected void fillInCommandMap () { - m_commandMap.put("insertNode".toLowerCase (), InsertNodeCmd.class); - } - + @Operation(name=INSERT_NODE_CMD) public InsertNodeCmd insertNodeCmd (String n, String na, String nb, String x, String y, String blocked) { - return new InsertNodeCmd ((EnvMapModelInstance )m_modelInstance, "", n, na, nb, x, y, blocked); + return new InsertNodeCmd (INSERT_NODE_CMD, (EnvMapModelInstance )m_modelInstance, "", n, na, nb, x, y, blocked); } } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMapModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMapModelInstance.java index ebae74e4e..4294938d2 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMapModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/EnvMapModelInstance.java @@ -48,7 +48,12 @@ public String getModelName () { @Override public EnvMapCommandFactory getCommandFactory () { if (m_commandFactory==null){ - m_commandFactory = new EnvMapCommandFactory(this); + try { + m_commandFactory = new EnvMapCommandFactory(this); + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } return m_commandFactory; } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/InsertNodeCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/InsertNodeCmd.java index 3b1392bdb..03942ccf0 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/InsertNodeCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/InsertNodeCmd.java @@ -16,9 +16,9 @@ public class InsertNodeCmd extends AbstractRainbowModelOperation getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "insertNode"); + return generateEvents (messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/MapTranslator.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/MapTranslator.java index b85d292d6..d734041db 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/MapTranslator.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/MapTranslator.java @@ -4,6 +4,7 @@ import java.io.FileWriter; import java.io.IOException; import java.text.DecimalFormat; +import java.text.MessageFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; @@ -801,7 +802,7 @@ public static void exportTranslation(String f, String code){ out.close(); } catch (IOException e){ - System.out.println("Error exporting PRISM map translation:\n" + e); + System.out.println(MessageFormat.format("Error exporting PRISM map translation to ''{0}''. Error: {1}", f, e.getMessage())); } } diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/Phase1MapPropertyKeys.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/Phase1MapPropertyKeys.java index 45c203f3b..0c5e8f8b3 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/Phase1MapPropertyKeys.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/Phase1MapPropertyKeys.java @@ -1,7 +1,7 @@ -package org.sa.rainbow.brass.model.map; - -public interface Phase1MapPropertyKeys { - public static final String CHARGING_STATION = "charging_station"; - public static final String DISTANCE = "distance"; - public static final String ENABLEMENT = "enablement"; -} +package org.sa.rainbow.brass.model.map; + +public interface Phase1MapPropertyKeys { + public static final String CHARGING_STATION = "charging_station"; + public static final String DISTANCE = "distance"; + public static final String ENABLEMENT = "enablement"; +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/Phase2MapPropertyKeys.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/Phase2MapPropertyKeys.java index 0d05bf4fe..e7bfd7199 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/Phase2MapPropertyKeys.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/map/Phase2MapPropertyKeys.java @@ -1,12 +1,12 @@ -package org.sa.rainbow.brass.model.map; - -public interface Phase2MapPropertyKeys extends Phase1MapPropertyKeys { - - public static final String ILLUMINANCE = "illuminance"; - public static final String OBSTRUCTIONS = "obstructions"; - public static final String HITRATES = "hitrates"; - public static final String TIMES = "times"; - - enum ObsLevel {LOW, MEDIUM, HIGH, NONE}; - -} +package org.sa.rainbow.brass.model.map; + +public interface Phase2MapPropertyKeys extends Phase1MapPropertyKeys { + + public static final String ILLUMINANCE = "illuminance"; + public static final String OBSTRUCTIONS = "obstructions"; + public static final String HITRATES = "hitrates"; + public static final String TIMES = "times"; + + enum ObsLevel {LOW, MEDIUM, HIGH, NONE}; + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionCommandFactory.java index afed993ef..6d0e69bcf 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionCommandFactory.java @@ -1,107 +1,115 @@ -package org.sa.rainbow.brass.model.mission; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.sa.rainbow.brass.model.instructions.SetLocalizationFidelityInstruction.LocalizationFidelity; -import org.sa.rainbow.brass.model.p2_cp3.clock.SetCurrentTimeCmd; -import org.sa.rainbow.brass.model.robot.SetBatteryChargeCmd; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -/** - * Created by schmerl on 12/27/2016. - */ -public class MissionCommandFactory extends ModelCommandFactory { - - public static MissionStateLoadCmd loadCommand (ModelsManager mm, String modelName, InputStream - stream, String source) { - return new MissionStateLoadCmd (mm, modelName, stream, source); - } - - public MissionCommandFactory ( - IModelInstance model) { - super (MissionStateModelInstance.class, model); - } - - @Override - protected void fillInCommandMap () { - m_commandMap.put ("setCurrentLocation".toLowerCase (), SetCurrentLocationCmd.class); - m_commandMap.put ("setRobotObstructed".toLowerCase (), SetRobotObstructedCmd.class); - m_commandMap.put ("setRobotOnTime".toLowerCase (), SetRobotOnTimeCmd.class); - m_commandMap.put ("setRobotAccurate".toLowerCase (), SetRobotAccurateCmd.class); - m_commandMap.put ("setDeadlineCmd".toLowerCase (), SetDeadlineCmd.class); - m_commandMap.put ("setTargetWaypoint".toLowerCase (), SetTargetWaypointCmd.class); - m_commandMap.put ("setGroundPlanError".toLowerCase (), SetGroundPlaneErrorCmd.class); - m_commandMap.put ("setCalibrationError".toLowerCase (), SetCalibrationErrorCmd.class); - m_commandMap.put ("recalibrate", RecalibrateCmd.class); - // TODO: This may be a hack - m_commandMap.put ("setRobotLocalizationFidelity".toLowerCase (), SetRobotLocalizationFidelityCmd.class); - } - - @Override - public SaveMissionCmd saveCommand (String location) throws RainbowModelException { - try (FileOutputStream os = new FileOutputStream (location)) { - return new SaveMissionCmd(null, location, os, m_modelInstance.getOriginalSource ()); - } - catch (IOException e) { - return null; - } - } - - public SetCurrentLocationCmd setCurrentLocationCmd (double x, double y, double w) { - return new SetCurrentLocationCmd ((MissionStateModelInstance) m_modelInstance, "", Double.toString (x), - Double.toString (y), Double.toString (w)); - } - - public SetRobotObstructedCmd setRobotObstructedCmd (boolean robotObstructed) { - return new SetRobotObstructedCmd ((MissionStateModelInstance) m_modelInstance, "", - Boolean.toString (robotObstructed)); - } - - public SetRobotOnTimeCmd setRobotOnTimeCmd (boolean robotOnTime) { - return new SetRobotOnTimeCmd ((MissionStateModelInstance) m_modelInstance, "", - Boolean.toString (robotOnTime)); - } - - public SetRobotAccurateCmd setRobotAccurateCmd (boolean robotAccurate) { - return new SetRobotAccurateCmd ((MissionStateModelInstance) m_modelInstance, "", - Boolean.toString (robotAccurate)); - } - - public SetDeadlineCmd setDeadlineCmd (long d) { - return new SetDeadlineCmd ((MissionStateModelInstance) m_modelInstance, "", - Double.toString (d)); - } - - public SetTargetWaypointCmd setTargetWaypointCmd (String t) { - return new SetTargetWaypointCmd ((MissionStateModelInstance )m_modelInstance, "", t); - } - - public SetGroundPlaneErrorCmd setGroundPlaneErrorCmd (double t, double r) { - return new SetGroundPlaneErrorCmd ((MissionStateModelInstance )m_modelInstance, "", Double.toString (t), - Double.toString (r)); - } - - public SetCalibrationErrorCmd setCalibrationError (double r, - double r_scale, - double t, - double t_scale, - double rv, - double tv) { - return new SetCalibrationErrorCmd ((MissionStateModelInstance )m_modelInstance, "", Double.toString (r), - Double.toString (r_scale), Double.toString (t), Double.toString (t_scale), Double.toString (rv), - Double.toString (tv)); - } - - public RecalibrateCmd recalibrate (boolean bad) { - return new RecalibrateCmd ((MissionStateModelInstance )m_modelInstance, "", Boolean.toString (bad)); - } - - public SetRobotLocalizationFidelityCmd setRobotLocalizationFidelityCmd (LocalizationFidelity fidelity) { - return new SetRobotLocalizationFidelityCmd((MissionStateModelInstance) m_modelInstance, "", fidelity.toString()); - } -} +package org.sa.rainbow.brass.model.mission; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.sa.rainbow.brass.model.instructions.SetLocalizationFidelityInstruction.LocalizationFidelity; +import org.sa.rainbow.brass.model.p2_cp3.clock.SetCurrentTimeCmd; +import org.sa.rainbow.brass.model.robot.SetBatteryChargeCmd; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +/** + * Created by schmerl on 12/27/2016. + */ +public class MissionCommandFactory extends ModelCommandFactory { + + private static final String SET_ROBOT_LOCALIZATION_FIDELITY_CMD = "setRobotLocalizationFidelity"; + private static final String RECALIBRATE_CMD = "recalibrate"; + private static final String SET_CALIBRATION_ERROR_CMD = "setCalibrationError"; + private static final String SET_GROUND_PLAN_ERROR_CMD = "setGroundPlanError"; + private static final String SET_TARGET_WAYPOINT_CMD = "setTargetWaypoint"; + private static final String SET_DEADLINE_CMD = "setDeadlineCmd"; + private static final String SET_ROBOT_ACCURATE_CMD = "setRobotAccurate"; + private static final String SET_ROBOT_ON_TIME_CMD = "setRobotOnTime"; + private static final String SET_ROBOT_OBSTRUCTED_CMD = "setRobotObstructed"; + private static final String SET_CURRENT_LOCATION_CMD = "setCurrentLocation"; + + @LoadOperation + public static MissionStateLoadCmd loadCommand (ModelsManager mm, String modelName, InputStream + stream, String source) { + return new MissionStateLoadCmd (mm, modelName, stream, source); + } + + public MissionCommandFactory ( + IModelInstance model) throws RainbowException { + super (MissionStateModelInstance.class, model); + } + + @Override + public SaveMissionCmd saveCommand (String location) throws RainbowModelException { + try (FileOutputStream os = new FileOutputStream (location)) { + return new SaveMissionCmd(null, location, os, m_modelInstance.getOriginalSource ()); + } + catch (IOException e) { + return null; + } + } + + @Operation(name=SET_CURRENT_LOCATION_CMD) + public SetCurrentLocationCmd setCurrentLocationCmd (double x, double y, double w) { + return new SetCurrentLocationCmd (SET_CURRENT_LOCATION_CMD,(MissionStateModelInstance) m_modelInstance, "", Double.toString (x), + Double.toString (y), Double.toString (w)); + } + + @Operation(name=SET_ROBOT_OBSTRUCTED_CMD) + public SetRobotObstructedCmd setRobotObstructedCmd (boolean robotObstructed) { + return new SetRobotObstructedCmd (SET_ROBOT_OBSTRUCTED_CMD, (MissionStateModelInstance) m_modelInstance, "", + Boolean.toString (robotObstructed)); + } + + @Operation(name=SET_ROBOT_ON_TIME_CMD) + public SetRobotOnTimeCmd setRobotOnTimeCmd (boolean robotOnTime) { + return new SetRobotOnTimeCmd (SET_ROBOT_ON_TIME_CMD, (MissionStateModelInstance) m_modelInstance, "", + Boolean.toString (robotOnTime)); + } + + @Operation(name=SET_ROBOT_ACCURATE_CMD) + public SetRobotAccurateCmd setRobotAccurateCmd (boolean robotAccurate) { + return new SetRobotAccurateCmd (SET_ROBOT_ACCURATE_CMD, (MissionStateModelInstance) m_modelInstance, "", + Boolean.toString (robotAccurate)); + } + + @Operation(name=SET_DEADLINE_CMD) + public SetDeadlineCmd setDeadlineCmd (long d) { + return new SetDeadlineCmd (SET_DEADLINE_CMD, (MissionStateModelInstance) m_modelInstance, "", + Double.toString (d)); + } + + @Operation(name=SET_TARGET_WAYPOINT_CMD) + public SetTargetWaypointCmd setTargetWaypointCmd (String t) { + return new SetTargetWaypointCmd (SET_TARGET_WAYPOINT_CMD, (MissionStateModelInstance )m_modelInstance, "", t); + } + + @Operation(name=SET_GROUND_PLAN_ERROR_CMD) + public SetGroundPlaneErrorCmd setGroundPlaneErrorCmd (double t, double r) { + return new SetGroundPlaneErrorCmd (SET_GROUND_PLAN_ERROR_CMD, (MissionStateModelInstance )m_modelInstance, "", Double.toString (t), + Double.toString (r)); + } + + @Operation(name=SET_CALIBRATION_ERROR_CMD) + public SetCalibrationErrorCmd setCalibrationError (double r, + double r_scale, + double t, + double t_scale, + double rv, + double tv) { + return new SetCalibrationErrorCmd (SET_CALIBRATION_ERROR_CMD, (MissionStateModelInstance )m_modelInstance, "", Double.toString (r), + Double.toString (r_scale), Double.toString (t), Double.toString (t_scale), Double.toString (rv), + Double.toString (tv)); + } + + @Operation(name=RECALIBRATE_CMD) + public RecalibrateCmd recalibrate (boolean bad) { + return new RecalibrateCmd (RECALIBRATE_CMD, (MissionStateModelInstance )m_modelInstance, "", Boolean.toString (bad)); + } + + @Operation(name=SET_ROBOT_LOCALIZATION_FIDELITY_CMD) + public SetRobotLocalizationFidelityCmd setRobotLocalizationFidelityCmd (LocalizationFidelity fidelity) { + return new SetRobotLocalizationFidelityCmd(SET_ROBOT_LOCALIZATION_FIDELITY_CMD, (MissionStateModelInstance) m_modelInstance, "", fidelity.toString()); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionState.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionState.java index db47048c1..62a059649 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionState.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionState.java @@ -1,363 +1,363 @@ -package org.sa.rainbow.brass.model.mission; - -import java.text.SimpleDateFormat; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.Deque; -import java.util.List; -import java.util.TimeZone; - -import org.sa.rainbow.brass.model.instructions.SetLocalizationFidelityInstruction.LocalizationFidelity; -import org.sa.rainbow.core.models.ModelReference; - -/** - * Created by schmerl on 12/27/2016. - */ -public class MissionState { - - // This should be in UTC - public static final SimpleDateFormat BRASS_DATE_FORMAT = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss'Z'"); - static { - BRASS_DATE_FORMAT.setTimeZone (TimeZone.getTimeZone ("UTC")); - } - - public static enum Heading { - NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST; - - public static Heading convertFromRadians (double w) { - if (w < 0) { - w = w + 2 * Math.PI; - } - if (w < Math.PI / 8 && w >= 7 * Math.PI / 8) return EAST; - if (w >= Math.PI / 8 && w < 3 * Math.PI / 8) return NORTHEAST; - if (w >= 3 * Math.PI / 8 && w < 5 * Math.PI / 8) return NORTH; - if (w >= 5 * Math.PI / 8 && w < 7 * Math.PI / 8) return NORTHWEST; - if (w >= 7 * Math.PI / 8 && w < 9 * Math.PI / 8) return WEST; - if (w >= 9 * Math.PI / 8 && w < 11 * Math.PI / 8) return Heading.SOUTHWEST; - if (w >= 11 * Math.PI / 8 && w < 13 * Math.PI / 8) return SOUTH; - if (w >= 13 * Math.PI / 8 && w < 15 * Math.PI / 8) return SOUTHEAST; - return EAST; - - } - - public static double convertToRadians (Heading h) { - if (h == EAST) return 0; - if (h == NORTHEAST) return Math.PI / 4; - if (h == NORTH) return Math.PI / 2; - if (h == NORTHWEST) return 3 * Math.PI / 4; - if (h == WEST) return Math.PI; - if (h == SOUTHWEST) return 5 * Math.PI / 4; - if (h == SOUTH) return 3 * Math.PI / 2; - if (h == SOUTHEAST) return 7 * Math.PI / 4; - return 0; - } - }; - - public static class LocationRecording { - protected double m_x; - protected double m_y; - protected double m_w; - protected Heading m_heading; - protected long m_time; - - public double getX () { - return m_x; - } - - public double getY () { - return m_y; - } - - public long getTime () { - return m_time; - } - - public Heading getHeading () { - return m_heading; - } - - public double getRotation () { - return m_w; - } - - public LocationRecording copy () { - LocationRecording l = new LocationRecording (); - l.m_x = m_x; - l.m_y = m_y; - l.m_w = m_w; - l.m_heading = m_heading; - l.m_time = m_time; - return l; - } - } - - - private final ModelReference m_model; - - //private List m_instructionHistory = new ArrayList<> (); - private Deque m_predictedTimeHistory = new ArrayDeque<> (); - private Deque m_predictedAccuracyHistory = new ArrayDeque<> (); - private Deque m_timeScore = new ArrayDeque<> (); - private Deque m_accuracyScore = new ArrayDeque<> (); - private Deque m_safetyScore = new ArrayDeque<> (); - - Deque m_locationHistory = new ArrayDeque<> (); - Deque m_chargeHistory = new ArrayDeque<> (); - Deque m_deadlineHistory = new ArrayDeque<> (); - Deque m_localizationFidelityHistory = new ArrayDeque<> (); - - private boolean m_robotObstructed = false; - private boolean m_robotOnTime = true; - private boolean m_robotAccurate = true; - private String m_targetWaypoint = ""; - - private double m_currentTime = 0; - - public MissionState (ModelReference model) { - m_model = model; - } - - public ModelReference getModelReference () { - return m_model; - } - - public void setCurrentPose (double x, double y, double w) { - LocationRecording l = new LocationRecording (); - l.m_x = x; - l.m_y = y; - l.m_w = w; - l.m_heading = Heading.convertFromRadians (w); - l.m_time = new Date ().getTime (); - synchronized (m_locationHistory) { - m_locationHistory.push (l); - } - } - - public LocationRecording getCurrentPose () { - if (m_locationHistory.isEmpty ()) return null; - synchronized (m_locationHistory) { - return m_locationHistory.peek ().copy (); - } - } - - public LocationRecording getInitialPose () { - synchronized (m_locationHistory) { - if (m_locationHistory.isEmpty ()) return null; - return m_locationHistory.getLast ().copy (); - } - } - - public void setRobotObstructed (boolean robotObstructed) { - m_robotObstructed = robotObstructed; - } - - public boolean isRobotObstructed () { - return m_robotObstructed; - } - - public void setRobotOnTime (boolean isOnTime) { - m_robotOnTime = isOnTime; - } - - public boolean isRobotOnTime () { - return m_robotOnTime; - } - - public void setRobotAccurate (boolean isAccurate) { - m_robotAccurate = isAccurate; - } - - public boolean isRobotAccurate () { - return m_robotAccurate; - } - - public void setBatteryCharge (Double charge) { - synchronized (m_chargeHistory) { - m_chargeHistory.push (charge); - } - } - - public Double getBatteryCharge () { - synchronized (m_chargeHistory) { - - Double charge = m_chargeHistory.peek (); - if (charge == null) return null; - return charge; - } - } - - public void setDeadline (long d) { - synchronized (m_deadlineHistory) { - - m_deadlineHistory.push (d); - } - } - - public Long getDeadline () { - synchronized (m_deadlineHistory) { - - return m_deadlineHistory.peek (); - } - } - - public void setLocalizationFidelity (LocalizationFidelity fidelity) { - m_localizationFidelityHistory.push (fidelity); - } - - public LocalizationFidelity getLocalizationFidelity () { - return m_localizationFidelityHistory.peek (); - } - - public void setTargetWaypoint (String waypoint) { - m_targetWaypoint = waypoint; - } - - public String getTargetWaypoint () { - return m_targetWaypoint; - } - - public double getCurrentTime () { - return m_currentTime; - } - - public void setCurrentTime (double time) { - m_currentTime = time; - } - -// public double getSpeed() { -// LocationRecording recent, next; -// synchronized (m_locationHistory) { -// if (m_locationHistory.size () > 2) { -// recent = m_locationHistory.pop (); -// next = m_locationHistory.pop (); -// m_locationHistory.push (next); -// m_locationHistory.push (recent); -// } -// else return 0; -// } -// double dist = Math.sqrt () -// -// } - /** - * - * @return True iff the robot encounters (or expects to encounter) problems - */ - public boolean isAdaptationNeeded () { - return isRobotObstructed () || !isRobotOnTime () || !isRobotAccurate () || isBadlyCalibrated (); - } - - public MissionState copy () { - MissionState s = new MissionState (m_model); - s.m_locationHistory = new ArrayDeque<> (m_locationHistory); - s.m_chargeHistory = new ArrayDeque<> (m_chargeHistory); - s.m_deadlineHistory = new ArrayDeque<> (m_deadlineHistory); - return s; - } - - // Below are for challenge problem 2 - - public static class GroundPlaneError { - public double translational_error; - public double rotational_error; - } - - public static class CalibrationError { - public double rotational_error; - public double rotational_scale; - public double translational_error; - public double translational_scale; - public double rotational_velocity_at_time_of_error; - public double translational_velocity_at_time_of_error; - } - - Deque m_groundPlaneErrorHistory = new ArrayDeque<> (); - Deque m_calibarationErrorHistory = new ArrayDeque<> (); - private boolean m_isBadlyCalibrated = false; - - public List getGroundPlaneSample (int sampleSize) { - if (m_groundPlaneErrorHistory.size () < sampleSize) return Collections. emptyList (); - List ret = new ArrayList<> (sampleSize); - synchronized (m_groundPlaneErrorHistory) { - for (int i = 0; i < sampleSize; i++) { - ret.add (m_groundPlaneErrorHistory.pop ()); - } - // Now put them back - for (int i = ret.size (); i > 0; i--) { - m_groundPlaneErrorHistory.push (ret.get (i - 1)); - } - } - return ret; - } - - public boolean isBadlyCalibrated () { - return m_isBadlyCalibrated; - } - - public void setBadlyCalibrated (boolean bad) { - System.out.println ( - "Setting calibration state to " + bad + ". isAdapationNeeded() is now " + isAdaptationNeeded ()); - m_isBadlyCalibrated = bad; - } - - public void addGroundPlaneSample (GroundPlaneError error) { - synchronized (m_groundPlaneErrorHistory) { - m_groundPlaneErrorHistory.push (error); - } - } - - protected static final int NUM_SAMPLES = 4; - protected double[] r_sample = new double[NUM_SAMPLES]; // Rolling window - protected int r_num = 0; // Number of samples - protected int r_idx = 0; // Index of oldest sample - - public double rErrAvg () { - double sum = 0.0; - for (int i = 0; i < r_num; i++) { - sum += r_sample[i]; - } - return sum / r_num; - } - - public void addCalibrationErrorSample (CalibrationError c) { - synchronized (m_calibarationErrorHistory) { -// if (r_num < 3) { // Need at least 3 samples for an average -// // Add this to the winddow -// r_sample[r_idx] = c.rotational_error; -// r_num++; -// r_idx = (r_idx + 1) % NUM_SAMPLES; -// } -// if (r_num > 3) { -// // discount outliers -// r_num = Math.min (++r_num, NUM_SAMPLES); -// r_idx = (r_idx + 1) % NUM_SAMPLES; -// if (Math.abs (c.rotational_error - rErrAvg ()) < ROTATIONAL_ERROR_THRESHOLD) { -// r_sample[r_idx] = c.rotational_error; -// } -// } -// // Record each outlier - m_calibarationErrorHistory.push (c); - } - } - - public List getCallibrationErrorSample (int sampleSize) { - if (m_calibarationErrorHistory.size () < sampleSize) return Collections. emptyList (); - List ret = new ArrayList<> (); - synchronized (m_calibarationErrorHistory) { - for (int i = 0; i < sampleSize; i++) { - ret.add (m_calibarationErrorHistory.pop ()); - } - // Now put them back - for (int i = ret.size (); i > 0; i--) { - m_calibarationErrorHistory.push (ret.get (i - 1)); - } - } - return ret; - } - - public Deque getCalibrationErrorObservations () { - return m_calibarationErrorHistory; - } - -} +package org.sa.rainbow.brass.model.mission; + +import java.text.SimpleDateFormat; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.Deque; +import java.util.List; +import java.util.TimeZone; + +import org.sa.rainbow.brass.model.instructions.SetLocalizationFidelityInstruction.LocalizationFidelity; +import org.sa.rainbow.core.models.ModelReference; + +/** + * Created by schmerl on 12/27/2016. + */ +public class MissionState { + + // This should be in UTC + public static final SimpleDateFormat BRASS_DATE_FORMAT = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss'Z'"); + static { + BRASS_DATE_FORMAT.setTimeZone (TimeZone.getTimeZone ("UTC")); + } + + public static enum Heading { + NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST; + + public static Heading convertFromRadians (double w) { + if (w < 0) { + w = w + 2 * Math.PI; + } + if (w < Math.PI / 8 && w >= 7 * Math.PI / 8) return EAST; + if (w >= Math.PI / 8 && w < 3 * Math.PI / 8) return NORTHEAST; + if (w >= 3 * Math.PI / 8 && w < 5 * Math.PI / 8) return NORTH; + if (w >= 5 * Math.PI / 8 && w < 7 * Math.PI / 8) return NORTHWEST; + if (w >= 7 * Math.PI / 8 && w < 9 * Math.PI / 8) return WEST; + if (w >= 9 * Math.PI / 8 && w < 11 * Math.PI / 8) return Heading.SOUTHWEST; + if (w >= 11 * Math.PI / 8 && w < 13 * Math.PI / 8) return SOUTH; + if (w >= 13 * Math.PI / 8 && w < 15 * Math.PI / 8) return SOUTHEAST; + return EAST; + + } + + public static double convertToRadians (Heading h) { + if (h == EAST) return 0; + if (h == NORTHEAST) return Math.PI / 4; + if (h == NORTH) return Math.PI / 2; + if (h == NORTHWEST) return 3 * Math.PI / 4; + if (h == WEST) return Math.PI; + if (h == SOUTHWEST) return 5 * Math.PI / 4; + if (h == SOUTH) return 3 * Math.PI / 2; + if (h == SOUTHEAST) return 7 * Math.PI / 4; + return 0; + } + }; + + public static class LocationRecording { + protected double m_x; + protected double m_y; + protected double m_w; + protected Heading m_heading; + protected long m_time; + + public double getX () { + return m_x; + } + + public double getY () { + return m_y; + } + + public long getTime () { + return m_time; + } + + public Heading getHeading () { + return m_heading; + } + + public double getRotation () { + return m_w; + } + + public LocationRecording copy () { + LocationRecording l = new LocationRecording (); + l.m_x = m_x; + l.m_y = m_y; + l.m_w = m_w; + l.m_heading = m_heading; + l.m_time = m_time; + return l; + } + } + + + private final ModelReference m_model; + + //private List m_instructionHistory = new ArrayList<> (); + private Deque m_predictedTimeHistory = new ArrayDeque<> (); + private Deque m_predictedAccuracyHistory = new ArrayDeque<> (); + private Deque m_timeScore = new ArrayDeque<> (); + private Deque m_accuracyScore = new ArrayDeque<> (); + private Deque m_safetyScore = new ArrayDeque<> (); + + Deque m_locationHistory = new ArrayDeque<> (); + Deque m_chargeHistory = new ArrayDeque<> (); + Deque m_deadlineHistory = new ArrayDeque<> (); + Deque m_localizationFidelityHistory = new ArrayDeque<> (); + + private boolean m_robotObstructed = false; + private boolean m_robotOnTime = true; + private boolean m_robotAccurate = true; + private String m_targetWaypoint = ""; + + private double m_currentTime = 0; + + public MissionState (ModelReference model) { + m_model = model; + } + + public ModelReference getModelReference () { + return m_model; + } + + public void setCurrentPose (double x, double y, double w) { + LocationRecording l = new LocationRecording (); + l.m_x = x; + l.m_y = y; + l.m_w = w; + l.m_heading = Heading.convertFromRadians (w); + l.m_time = new Date ().getTime (); + synchronized (m_locationHistory) { + m_locationHistory.push (l); + } + } + + public LocationRecording getCurrentPose () { + if (m_locationHistory.isEmpty ()) return null; + synchronized (m_locationHistory) { + return m_locationHistory.peek ().copy (); + } + } + + public LocationRecording getInitialPose () { + synchronized (m_locationHistory) { + if (m_locationHistory.isEmpty ()) return null; + return m_locationHistory.getLast ().copy (); + } + } + + public void setRobotObstructed (boolean robotObstructed) { + m_robotObstructed = robotObstructed; + } + + public boolean isRobotObstructed () { + return m_robotObstructed; + } + + public void setRobotOnTime (boolean isOnTime) { + m_robotOnTime = isOnTime; + } + + public boolean isRobotOnTime () { + return m_robotOnTime; + } + + public void setRobotAccurate (boolean isAccurate) { + m_robotAccurate = isAccurate; + } + + public boolean isRobotAccurate () { + return m_robotAccurate; + } + + public void setBatteryCharge (Double charge) { + synchronized (m_chargeHistory) { + m_chargeHistory.push (charge); + } + } + + public Double getBatteryCharge () { + synchronized (m_chargeHistory) { + + Double charge = m_chargeHistory.peek (); + if (charge == null) return null; + return charge; + } + } + + public void setDeadline (long d) { + synchronized (m_deadlineHistory) { + + m_deadlineHistory.push (d); + } + } + + public Long getDeadline () { + synchronized (m_deadlineHistory) { + + return m_deadlineHistory.peek (); + } + } + + public void setLocalizationFidelity (LocalizationFidelity fidelity) { + m_localizationFidelityHistory.push (fidelity); + } + + public LocalizationFidelity getLocalizationFidelity () { + return m_localizationFidelityHistory.peek (); + } + + public void setTargetWaypoint (String waypoint) { + m_targetWaypoint = waypoint; + } + + public String getTargetWaypoint () { + return m_targetWaypoint; + } + + public double getCurrentTime () { + return m_currentTime; + } + + public void setCurrentTime (double time) { + m_currentTime = time; + } + +// public double getSpeed() { +// LocationRecording recent, next; +// synchronized (m_locationHistory) { +// if (m_locationHistory.size () > 2) { +// recent = m_locationHistory.pop (); +// next = m_locationHistory.pop (); +// m_locationHistory.push (next); +// m_locationHistory.push (recent); +// } +// else return 0; +// } +// double dist = Math.sqrt () +// +// } + /** + * + * @return True iff the robot encounters (or expects to encounter) problems + */ + public boolean isAdaptationNeeded () { + return isRobotObstructed () || !isRobotOnTime () || !isRobotAccurate () || isBadlyCalibrated (); + } + + public MissionState copy () { + MissionState s = new MissionState (m_model); + s.m_locationHistory = new ArrayDeque<> (m_locationHistory); + s.m_chargeHistory = new ArrayDeque<> (m_chargeHistory); + s.m_deadlineHistory = new ArrayDeque<> (m_deadlineHistory); + return s; + } + + // Below are for challenge problem 2 + + public static class GroundPlaneError { + public double translational_error; + public double rotational_error; + } + + public static class CalibrationError { + public double rotational_error; + public double rotational_scale; + public double translational_error; + public double translational_scale; + public double rotational_velocity_at_time_of_error; + public double translational_velocity_at_time_of_error; + } + + Deque m_groundPlaneErrorHistory = new ArrayDeque<> (); + Deque m_calibarationErrorHistory = new ArrayDeque<> (); + private boolean m_isBadlyCalibrated = false; + + public List getGroundPlaneSample (int sampleSize) { + if (m_groundPlaneErrorHistory.size () < sampleSize) return Collections. emptyList (); + List ret = new ArrayList<> (sampleSize); + synchronized (m_groundPlaneErrorHistory) { + for (int i = 0; i < sampleSize; i++) { + ret.add (m_groundPlaneErrorHistory.pop ()); + } + // Now put them back + for (int i = ret.size (); i > 0; i--) { + m_groundPlaneErrorHistory.push (ret.get (i - 1)); + } + } + return ret; + } + + public boolean isBadlyCalibrated () { + return m_isBadlyCalibrated; + } + + public void setBadlyCalibrated (boolean bad) { + System.out.println ( + "Setting calibration state to " + bad + ". isAdapationNeeded() is now " + isAdaptationNeeded ()); + m_isBadlyCalibrated = bad; + } + + public void addGroundPlaneSample (GroundPlaneError error) { + synchronized (m_groundPlaneErrorHistory) { + m_groundPlaneErrorHistory.push (error); + } + } + + protected static final int NUM_SAMPLES = 4; + protected double[] r_sample = new double[NUM_SAMPLES]; // Rolling window + protected int r_num = 0; // Number of samples + protected int r_idx = 0; // Index of oldest sample + + public double rErrAvg () { + double sum = 0.0; + for (int i = 0; i < r_num; i++) { + sum += r_sample[i]; + } + return sum / r_num; + } + + public void addCalibrationErrorSample (CalibrationError c) { + synchronized (m_calibarationErrorHistory) { +// if (r_num < 3) { // Need at least 3 samples for an average +// // Add this to the winddow +// r_sample[r_idx] = c.rotational_error; +// r_num++; +// r_idx = (r_idx + 1) % NUM_SAMPLES; +// } +// if (r_num > 3) { +// // discount outliers +// r_num = Math.min (++r_num, NUM_SAMPLES); +// r_idx = (r_idx + 1) % NUM_SAMPLES; +// if (Math.abs (c.rotational_error - rErrAvg ()) < ROTATIONAL_ERROR_THRESHOLD) { +// r_sample[r_idx] = c.rotational_error; +// } +// } +// // Record each outlier + m_calibarationErrorHistory.push (c); + } + } + + public List getCallibrationErrorSample (int sampleSize) { + if (m_calibarationErrorHistory.size () < sampleSize) return Collections. emptyList (); + List ret = new ArrayList<> (); + synchronized (m_calibarationErrorHistory) { + for (int i = 0; i < sampleSize; i++) { + ret.add (m_calibarationErrorHistory.pop ()); + } + // Now put them back + for (int i = ret.size (); i > 0; i--) { + m_calibarationErrorHistory.push (ret.get (i - 1)); + } + } + return ret; + } + + public Deque getCalibrationErrorObservations () { + return m_calibarationErrorHistory; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionStateLoadCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionStateLoadCmd.java index bf49d1875..de1e116c4 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionStateLoadCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionStateLoadCmd.java @@ -1,58 +1,58 @@ -package org.sa.rainbow.brass.model.mission; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; - -import java.io.InputStream; - -import static org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE; - -/** - * Created by schmerl on 12/28/2016. - */ -public class MissionStateLoadCmd extends AbstractLoadModelCmd { - private final String m_modelName; - private final InputStream m_stream; - private MissionStateModelInstance m_result; - - public MissionStateLoadCmd (IModelsManager mm, String resource, InputStream is, String source) { - super ("loadMissionState", mm, resource, is, source); - m_modelName = resource; - m_stream = is; - } - - @Override - public IModelInstance getResult () throws IllegalStateException { - return m_result; - } - public ModelReference getModelReference () { - return new ModelReference (m_modelName, MissionStateModelInstance.MISSION_STATE_TYPE); - } - - @Override - protected void subExecute () throws RainbowException { - if (m_stream == null) { - MissionState m = new MissionState (getModelReference ()); - m_result = new MissionStateModelInstance (m, getOriginalSource ()); - doPostExecute (); - } - } - - @Override - protected void subRedo () throws RainbowException { - doPostExecute (); - } - - @Override - protected void subUndo () throws RainbowException { - doPostUndo (); - } - - @Override - protected boolean checkModelValidForCommand (Object o) { - return true; - } -} +package org.sa.rainbow.brass.model.mission; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; + +import java.io.InputStream; + +import static org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE; + +/** + * Created by schmerl on 12/28/2016. + */ +public class MissionStateLoadCmd extends AbstractLoadModelCmd { + private final String m_modelName; + private final InputStream m_stream; + private MissionStateModelInstance m_result; + + public MissionStateLoadCmd (IModelsManager mm, String resource, InputStream is, String source) { + super ("loadMissionState", mm, resource, is, source); + m_modelName = resource; + m_stream = is; + } + + @Override + public IModelInstance getResult () throws IllegalStateException { + return m_result; + } + public ModelReference getModelReference () { + return new ModelReference (m_modelName, MissionStateModelInstance.MISSION_STATE_TYPE); + } + + @Override + protected void subExecute () throws RainbowException { + if (m_stream == null) { + MissionState m = new MissionState (getModelReference ()); + m_result = new MissionStateModelInstance (m, getOriginalSource ()); + doPostExecute (); + } + } + + @Override + protected void subRedo () throws RainbowException { + doPostExecute (); + } + + @Override + protected void subUndo () throws RainbowException { + doPostUndo (); + } + + @Override + protected boolean checkModelValidForCommand (Object o) { + return true; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionStateModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionStateModelInstance.java index bf65f62c5..1c874f589 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionStateModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/MissionStateModelInstance.java @@ -1,70 +1,70 @@ -package org.sa.rainbow.brass.model.mission; - -import org.sa.rainbow.core.error.RainbowCopyException; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -/** - * Created by schmerl on 12/27/2016. - */ -public class MissionStateModelInstance implements IModelInstance { - - public static final String MISSION_STATE_TYPE = "MissionState"; - private MissionState m_missionState; - private MissionCommandFactory m_commandFactory; - private String m_source; - - public MissionStateModelInstance (MissionState s, String source) { - setModelInstance (s); - setOriginalSource (source); - } - - @Override - public MissionState getModelInstance () { - return m_missionState; - } - - @Override - public void setModelInstance (MissionState model) { - m_missionState = model; - } - - @Override - public IModelInstance copyModelInstance (String newName) throws RainbowCopyException { - return new MissionStateModelInstance (getModelInstance ().copy (), getOriginalSource ()); - } - - @Override - public String getModelType () { - return MISSION_STATE_TYPE; - } - - @Override - public String getModelName () { - return getModelInstance ().getModelReference ().getModelName (); - } - - @Override - public MissionCommandFactory getCommandFactory () { - if (m_commandFactory == null) { - m_commandFactory = new MissionCommandFactory (this); - } - return m_commandFactory; - } - - @Override - public void setOriginalSource (String source) { - m_source = source; - } - - @Override - public String getOriginalSource () { - return m_source; - } - - @Override - public void dispose () throws RainbowException { - - } -} +package org.sa.rainbow.brass.model.mission; + +import org.sa.rainbow.core.error.RainbowCopyException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +/** + * Created by schmerl on 12/27/2016. + */ +public class MissionStateModelInstance implements IModelInstance { + + public static final String MISSION_STATE_TYPE = "MissionState"; + private MissionState m_missionState; + private MissionCommandFactory m_commandFactory; + private String m_source; + + public MissionStateModelInstance (MissionState s, String source) { + setModelInstance (s); + setOriginalSource (source); + } + + @Override + public MissionState getModelInstance () { + return m_missionState; + } + + @Override + public void setModelInstance (MissionState model) { + m_missionState = model; + } + + @Override + public IModelInstance copyModelInstance (String newName) throws RainbowCopyException { + return new MissionStateModelInstance (getModelInstance ().copy (), getOriginalSource ()); + } + + @Override + public String getModelType () { + return MISSION_STATE_TYPE; + } + + @Override + public String getModelName () { + return getModelInstance ().getModelReference ().getModelName (); + } + + @Override + public MissionCommandFactory getCommandFactory () throws RainbowException { + if (m_commandFactory == null) { + m_commandFactory = new MissionCommandFactory (this); + } + return m_commandFactory; + } + + @Override + public void setOriginalSource (String source) { + m_source = source; + } + + @Override + public String getOriginalSource () { + return m_source; + } + + @Override + public void dispose () throws RainbowException { + + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/RecalibrateCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/RecalibrateCmd.java index 93f11676c..d341a8cb7 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/RecalibrateCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/RecalibrateCmd.java @@ -11,8 +11,8 @@ public class RecalibrateCmd extends AbstractRainbowModelOperation getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "recalibrate"); + return generateEvents (messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SaveMissionCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SaveMissionCmd.java index 11135dcad..ea618da79 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SaveMissionCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SaveMissionCmd.java @@ -1,59 +1,59 @@ -package org.sa.rainbow.brass.model.mission; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; - -import java.io.OutputStream; -import java.io.PrintStream; - -/** - * Created by schmerl on 12/27/2016. - */ -public class SaveMissionCmd extends AbstractSaveModelCmd { - public SaveMissionCmd (IModelsManager mm, String resource, OutputStream os, String source) { - super ("saveMissionState", mm, resource, os, source); - } - - @Override - public Object getResult () throws IllegalStateException { - return null; - } - - @Override - public ModelReference getModelReference () { - return new ModelReference ("", "MissionState"); - } - - @Override - protected void subExecute () throws RainbowException { - MissionState model = getModelContext ().getModelInstance (); - try (PrintStream ps = new PrintStream (getStream ())) { - for (MissionState.LocationRecording l : model.m_locationHistory) { - ps.print ("("); - ps.print (l.getX ()); - ps.print (","); - ps.print (l.getY ()); - ps.print (")@"); - ps.print (l.getTime ()); - ps.print ("\n"); - } - } - } - - @Override - protected void subRedo () throws RainbowException { - - } - - @Override - protected void subUndo () throws RainbowException { - - } - - @Override - protected boolean checkModelValidForCommand (MissionState missionState) { - return true; - } -} +package org.sa.rainbow.brass.model.mission; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; + +import java.io.OutputStream; +import java.io.PrintStream; + +/** + * Created by schmerl on 12/27/2016. + */ +public class SaveMissionCmd extends AbstractSaveModelCmd { + public SaveMissionCmd (IModelsManager mm, String resource, OutputStream os, String source) { + super ("saveMissionState", mm, resource, os, source); + } + + @Override + public Object getResult () throws IllegalStateException { + return null; + } + + @Override + public ModelReference getModelReference () { + return new ModelReference ("", "MissionState"); + } + + @Override + protected void subExecute () throws RainbowException { + MissionState model = getModelContext ().getModelInstance (); + try (PrintStream ps = new PrintStream (getStream ())) { + for (MissionState.LocationRecording l : model.m_locationHistory) { + ps.print ("("); + ps.print (l.getX ()); + ps.print (","); + ps.print (l.getY ()); + ps.print (")@"); + ps.print (l.getTime ()); + ps.print ("\n"); + } + } + } + + @Override + protected void subRedo () throws RainbowException { + + } + + @Override + protected void subUndo () throws RainbowException { + + } + + @Override + protected boolean checkModelValidForCommand (MissionState missionState) { + return true; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetCalibrationErrorCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetCalibrationErrorCmd.java index 854d7336a..6b525da42 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetCalibrationErrorCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetCalibrationErrorCmd.java @@ -12,9 +12,9 @@ public class SetCalibrationErrorCmd extends AbstractRainbowModelOperation getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setCalibrationError"); + return generateEvents (messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetCurrentLocationCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetCurrentLocationCmd.java index 15a777c08..6499d84ec 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetCurrentLocationCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetCurrentLocationCmd.java @@ -1,58 +1,58 @@ -package org.sa.rainbow.brass.model.mission; - -import java.util.List; - -import org.sa.rainbow.brass.model.mission.MissionState.Heading; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -/** - * Created by schmerl on 12/27/2016. - */ -public class SetCurrentLocationCmd extends AbstractRainbowModelOperation { - private final double m_x; - private final double m_y; - private double m_w; - private Heading m_heading; - - public SetCurrentLocationCmd (MissionStateModelInstance model, String target, String x, - String y, String w) { - super ("setCurrentLocation", model, target, x, y, w); - m_x = Double.parseDouble (x); - m_y = Double.parseDouble (y); - m_w = Double.parseDouble (w); - } - - @Override - public MissionState.LocationRecording getResult () throws IllegalStateException { - return getModelContext ().getModelInstance ().getCurrentPose (); - } - - @Override - protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setCurrentLocation"); - } - - @Override - protected void subExecute () throws RainbowException { - getModelContext ().getModelInstance ().setCurrentPose (m_x, m_y, m_w); - } - - @Override - protected void subRedo () throws RainbowException { - getModelContext ().getModelInstance ().setCurrentPose (m_x, m_y, m_w); - } - - @Override - protected void subUndo () throws RainbowException { - getModelContext ().getModelInstance ().m_locationHistory.pop (); - } - - @Override - protected boolean checkModelValidForCommand (MissionState missionState) { - return missionState == getModelContext - ().getModelInstance (); - } -} +package org.sa.rainbow.brass.model.mission; + +import java.util.List; + +import org.sa.rainbow.brass.model.mission.MissionState.Heading; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +/** + * Created by schmerl on 12/27/2016. + */ +public class SetCurrentLocationCmd extends AbstractRainbowModelOperation { + private final double m_x; + private final double m_y; + private double m_w; + private Heading m_heading; + + public SetCurrentLocationCmd (String commandName, MissionStateModelInstance model, String target, String x, + String y, String w) { + super (commandName, model, target, x, y, w); + m_x = Double.parseDouble (x); + m_y = Double.parseDouble (y); + m_w = Double.parseDouble (w); + } + + @Override + public MissionState.LocationRecording getResult () throws IllegalStateException { + return getModelContext ().getModelInstance ().getCurrentPose (); + } + + @Override + protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { + return generateEvents (messageFactory, getName()); + } + + @Override + protected void subExecute () throws RainbowException { + getModelContext ().getModelInstance ().setCurrentPose (m_x, m_y, m_w); + } + + @Override + protected void subRedo () throws RainbowException { + getModelContext ().getModelInstance ().setCurrentPose (m_x, m_y, m_w); + } + + @Override + protected void subUndo () throws RainbowException { + getModelContext ().getModelInstance ().m_locationHistory.pop (); + } + + @Override + protected boolean checkModelValidForCommand (MissionState missionState) { + return missionState == getModelContext + ().getModelInstance (); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetDeadlineCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetDeadlineCmd.java index 26cc1b5d0..e9958c493 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetDeadlineCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetDeadlineCmd.java @@ -11,8 +11,8 @@ public class SetDeadlineCmd extends AbstractRainbowModelOperation getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setDeadlineCharge"); + return generateEvents (messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetGroundPlaneErrorCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetGroundPlaneErrorCmd.java index d5e93db04..538f07230 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetGroundPlaneErrorCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetGroundPlaneErrorCmd.java @@ -12,8 +12,8 @@ public class SetGroundPlaneErrorCmd extends AbstractRainbowModelOperation getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setGroundPlaneError"); + return generateEvents (messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotAccurateCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotAccurateCmd.java index c85b3a3f2..da309bf4b 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotAccurateCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotAccurateCmd.java @@ -10,8 +10,8 @@ public class SetRobotAccurateCmd extends AbstractRainbowModelOperation { private boolean m_robotAccurate; - public SetRobotAccurateCmd(MissionStateModelInstance model, String target, String robotAccurate) { - super("setRobotAccurate", model, target, robotAccurate); + public SetRobotAccurateCmd(String commandName, MissionStateModelInstance model, String target, String robotAccurate) { + super(commandName, model, target, robotAccurate); m_robotAccurate = Boolean.parseBoolean(robotAccurate); } @@ -27,7 +27,7 @@ protected boolean checkModelValidForCommand(MissionState missionState) { @Override protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setRobotAccurate"); + return generateEvents(messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotLocalizationFidelityCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotLocalizationFidelityCmd.java index c03e8afb7..d7bd50c58 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotLocalizationFidelityCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotLocalizationFidelityCmd.java @@ -11,8 +11,8 @@ public class SetRobotLocalizationFidelityCmd extends AbstractRainbowModelOperation { private LocalizationFidelity m_fidelity; - public SetRobotLocalizationFidelityCmd(MissionStateModelInstance model, String target, String fidelity) { - super("setRobotLocalizationFidelity", model, target, fidelity); + public SetRobotLocalizationFidelityCmd(String commandName, MissionStateModelInstance model, String target, String fidelity) { + super(commandName, model, target, fidelity); m_fidelity = LocalizationFidelity.valueOf(fidelity); } @@ -28,7 +28,7 @@ protected boolean checkModelValidForCommand(MissionState missionState) { @Override protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setRobotLocalizationFidelity"); + return generateEvents(messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotObstructedCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotObstructedCmd.java index 5ac345be2..fd9821e4a 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotObstructedCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotObstructedCmd.java @@ -10,8 +10,8 @@ public class SetRobotObstructedCmd extends AbstractRainbowModelOperation { private boolean m_robotObstructed; - public SetRobotObstructedCmd (MissionStateModelInstance model, String target, String robotObstructed) { - super ("setRobotObstructed", model, target, robotObstructed); + public SetRobotObstructedCmd (String commandName, MissionStateModelInstance model, String target, String robotObstructed) { + super (commandName, model, target, robotObstructed); m_robotObstructed = Boolean.parseBoolean(robotObstructed); } @@ -22,7 +22,7 @@ public Boolean getResult() throws IllegalStateException { @Override protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setRobotObstructed"); + return generateEvents(messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotOnTimeCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotOnTimeCmd.java index 694668a06..ad5141023 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotOnTimeCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetRobotOnTimeCmd.java @@ -10,8 +10,8 @@ public class SetRobotOnTimeCmd extends AbstractRainbowModelOperation { private boolean m_robotOnTime; - public SetRobotOnTimeCmd (MissionStateModelInstance model, String target, String robotOnTime) { - super ("setRobotOnTime", model, target, robotOnTime); + public SetRobotOnTimeCmd (String commandName, MissionStateModelInstance model, String target, String robotOnTime) { + super (commandName, model, target, robotOnTime); m_robotOnTime = Boolean.parseBoolean(robotOnTime); } @@ -27,7 +27,7 @@ protected boolean checkModelValidForCommand(MissionState missionState) { @Override protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setRobotOnTime"); + return generateEvents(messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetTargetWaypointCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetTargetWaypointCmd.java index e9a921fd7..85e09b541 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetTargetWaypointCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/mission/SetTargetWaypointCmd.java @@ -11,8 +11,8 @@ public class SetTargetWaypointCmd extends AbstractRainbowModelOperation getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setTargetWaypoint"); + return generateEvents (messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/CP1ModelAccessor.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/CP1ModelAccessor.java index 00b3d4625..d8b1e8453 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/CP1ModelAccessor.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/CP1ModelAccessor.java @@ -1,35 +1,35 @@ -package org.sa.rainbow.brass.model.p2_cp1; - -import org.sa.rainbow.brass.model.P2ModelAccessor; -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.EnvMapModelInstance; -import org.sa.rainbow.brass.model.p2_cp1.robot.CP1RobotStateModelInstance; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionStateModelInstance; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowStateModelInstance; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.ports.IModelsManagerPort; - -public class CP1ModelAccessor extends P2ModelAccessor{ - private CP1RobotStateModelInstance m_robotStateModel; - - public CP1ModelAccessor (IModelsManagerPort mmp) { - super(mmp); - } - - public CP1RobotStateModelInstance getRobotStateModel() { - if (m_robotStateModel == null) { - CP1RobotStateModelInstance modelInstance = (CP1RobotStateModelInstance) m_modelsManagerPort.getModelInstance( - new ModelReference("Robot", RobotStateModelInstance.ROBOT_STATE_TYPE)); - m_robotStateModel = modelInstance; - } - return m_robotStateModel; - } - - -} +package org.sa.rainbow.brass.model.p2_cp1; + +import org.sa.rainbow.brass.model.P2ModelAccessor; +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.EnvMapModelInstance; +import org.sa.rainbow.brass.model.p2_cp1.robot.CP1RobotStateModelInstance; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionStateModelInstance; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowStateModelInstance; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.IModelsManagerPort; + +public class CP1ModelAccessor extends P2ModelAccessor{ + private CP1RobotStateModelInstance m_robotStateModel; + + public CP1ModelAccessor (IModelsManagerPort mmp) { + super(mmp); + } + + public CP1RobotStateModelInstance getRobotStateModel() { + if (m_robotStateModel == null) { + CP1RobotStateModelInstance modelInstance = (CP1RobotStateModelInstance) m_modelsManagerPort.getModelInstance( + new ModelReference("Robot", RobotStateModelInstance.ROBOT_STATE_TYPE)); + m_robotStateModel = modelInstance; + } + return m_robotStateModel; + } + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotState.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotState.java index 165c6352f..4aff07183 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotState.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotState.java @@ -1,30 +1,30 @@ -package org.sa.rainbow.brass.model.p2_cp1.robot; - -import java.util.ArrayDeque; -import java.util.Deque; - -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.core.models.ModelReference; - -public class CP1RobotState extends RobotState { - - Deque> m_configHistory = new ArrayDeque<>(); - - public CP1RobotState(ModelReference model) { - super(model); - } - - public String getConfigId() { - synchronized(m_configHistory) { - TimeStamped peek = m_configHistory.peek(); - return peek!=null?peek.data:""; - } - } - - public void setConfigId(String configId) { - synchronized(m_configHistory) { - m_configHistory.push(new TimeStamped(configId)); - } - } - -} +package org.sa.rainbow.brass.model.p2_cp1.robot; + +import java.util.ArrayDeque; +import java.util.Deque; + +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.core.models.ModelReference; + +public class CP1RobotState extends RobotState { + + Deque> m_configHistory = new ArrayDeque<>(); + + public CP1RobotState(ModelReference model) { + super(model); + } + + public String getConfigId() { + synchronized(m_configHistory) { + TimeStamped peek = m_configHistory.peek(); + return peek!=null?peek.data:""; + } + } + + public void setConfigId(String configId) { + synchronized(m_configHistory) { + m_configHistory.push(new TimeStamped(configId)); + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateCommandFactory.java index d247006b6..48c985df2 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateCommandFactory.java @@ -1,41 +1,41 @@ -package org.sa.rainbow.brass.model.p2_cp1.robot; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.sa.rainbow.brass.model.p2_cp3.robot.SaveCP3RobotStateCmd; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.RobotStateCommandFactory; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; - -public class CP1RobotStateCommandFactory extends RobotStateCommandFactory { - public CP1RobotStateCommandFactory(CP1RobotStateModelInstance model) { - super(CP1RobotStateModelInstance.class, model); - } - - public static CP1RobotStateLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream stream, String source) { - return new CP1RobotStateLoadCmd(mm, modelName, stream, source); - } - - @Override - public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { - try (FileOutputStream os = new FileOutputStream(location)) { - return new SaveCP3RobotStateCmd(null, location, os, m_modelInstance.getOriginalSource()); - } catch (IOException e) { - return null; - } - } - - @Override - protected void fillInCommandMap() { - super.fillInCommandMap(); - m_commandMap.put("setConfig".toLowerCase(), SetConfigCmd.class); - } - - public SetConfigCmd setConfigCmd(String configId) { - return new SetConfigCmd((CP1RobotStateModelInstance )m_modelInstance, "", configId); - } -} +package org.sa.rainbow.brass.model.p2_cp1.robot; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.sa.rainbow.brass.model.p2_cp3.robot.SaveCP3RobotStateCmd; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.RobotStateCommandFactory; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; + +public class CP1RobotStateCommandFactory extends RobotStateCommandFactory { + private static final String SET_CONFIG_CMD = "setConfig"; + + public CP1RobotStateCommandFactory(CP1RobotStateModelInstance model) throws RainbowException { + super(CP1RobotStateModelInstance.class, model); + } + + @LoadOperation + public static CP1RobotStateLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream stream, String source) { + return new CP1RobotStateLoadCmd(mm, modelName, stream, source); + } + + @Override + public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { + try (FileOutputStream os = new FileOutputStream(location)) { + return new SaveCP3RobotStateCmd(null, location, os, m_modelInstance.getOriginalSource()); + } catch (IOException e) { + return null; + } + } + + + @Operation(name=SET_CONFIG_CMD) + public SetConfigCmd setConfigCmd(String configId) { + return new SetConfigCmd(SET_CONFIG_CMD, (CP1RobotStateModelInstance )m_modelInstance, "", configId); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateLoadCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateLoadCmd.java index 7d3a73469..879abaf7b 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateLoadCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateLoadCmd.java @@ -1,24 +1,24 @@ -package org.sa.rainbow.brass.model.p2_cp1.robot; - -import java.io.InputStream; - -import org.sa.rainbow.brass.model.robot.RobotStateLoadCmd; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelsManager; - -public class CP1RobotStateLoadCmd extends RobotStateLoadCmd { - - public CP1RobotStateLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { - super(mm, resource, is, source); - } - - @Override - protected void subExecute() throws RainbowException { - if (m_stream == null) { - CP1RobotState m = new CP1RobotState(getModelReference()); - m_result = new CP1RobotStateModelInstance(m, getOriginalSource()); - doPostExecute(); - } - } - -} +package org.sa.rainbow.brass.model.p2_cp1.robot; + +import java.io.InputStream; + +import org.sa.rainbow.brass.model.robot.RobotStateLoadCmd; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelsManager; + +public class CP1RobotStateLoadCmd extends RobotStateLoadCmd { + + public CP1RobotStateLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { + super(mm, resource, is, source); + } + + @Override + protected void subExecute() throws RainbowException { + if (m_stream == null) { + CP1RobotState m = new CP1RobotState(getModelReference()); + m_result = new CP1RobotStateModelInstance(m, getOriginalSource()); + doPostExecute(); + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateModelInstance.java index 5302a9b7e..9f16939af 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/CP1RobotStateModelInstance.java @@ -1,26 +1,27 @@ -package org.sa.rainbow.brass.model.p2_cp1.robot; - -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class CP1RobotStateModelInstance extends RobotStateModelInstance { - private CP1RobotStateCommandFactory m_commandFactory; - - public CP1RobotStateModelInstance(CP1RobotState r, String source) { - super(r, source); - } - - @Override - public CP1RobotState getModelInstance() { - return (CP1RobotState )super.getModelInstance(); - } - - @Override - public ModelCommandFactory getCommandFactory() { - if (m_commandFactory == null) { - m_commandFactory = new CP1RobotStateCommandFactory(this); - } - return m_commandFactory; - } -} +package org.sa.rainbow.brass.model.p2_cp1.robot; + +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class CP1RobotStateModelInstance extends RobotStateModelInstance { + private CP1RobotStateCommandFactory m_commandFactory; + + public CP1RobotStateModelInstance(CP1RobotState r, String source) { + super(r, source); + } + + @Override + public CP1RobotState getModelInstance() { + return (CP1RobotState )super.getModelInstance(); + } + + @Override + public ModelCommandFactory getCommandFactory() throws RainbowException { + if (m_commandFactory == null) { + m_commandFactory = new CP1RobotStateCommandFactory(this); + } + return m_commandFactory; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/SaveCP1RobotStateCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/SaveCP1RobotStateCmd.java index ec7589f5f..a4db2f965 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/SaveCP1RobotStateCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/SaveCP1RobotStateCmd.java @@ -1,39 +1,39 @@ -package org.sa.rainbow.brass.model.p2_cp1.robot; - -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.EnumSet; -import java.util.Iterator; - -import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel.TimeStamped; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.SaveRobotStateCmd; -import org.sa.rainbow.core.models.IModelsManager; - -public class SaveCP1RobotStateCmd extends SaveRobotStateCmd { - - public SaveCP1RobotStateCmd(IModelsManager mm, String resource, OutputStream os, String source) { - super(mm, resource, os, source); - } - - @Override - protected void insertRobotState(PrintStream ps, RobotState model) { - super.insertRobotState(ps, model); - if (model instanceof CP1RobotState) { - CP1RobotState cp3 = (CP1RobotState )model; - ps.print(" configHistory: [\n"); - for (Iterator> iterator = cp3.m_configHistory.iterator(); iterator.hasNext();) { - TimeStamped entry = iterator.next(); - ps.print("{timestamp: " + entry.timestamp + ", config: " + entry.data + "}"); - if (iterator.hasNext()) ps.print(","); - } - - ps.print("]"); - } - - } - -} +package org.sa.rainbow.brass.model.p2_cp1.robot; + +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.EnumSet; +import java.util.Iterator; + +import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel.TimeStamped; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.SaveRobotStateCmd; +import org.sa.rainbow.core.models.IModelsManager; + +public class SaveCP1RobotStateCmd extends SaveRobotStateCmd { + + public SaveCP1RobotStateCmd(IModelsManager mm, String resource, OutputStream os, String source) { + super(mm, resource, os, source); + } + + @Override + protected void insertRobotState(PrintStream ps, RobotState model) { + super.insertRobotState(ps, model); + if (model instanceof CP1RobotState) { + CP1RobotState cp3 = (CP1RobotState )model; + ps.print(" configHistory: [\n"); + for (Iterator> iterator = cp3.m_configHistory.iterator(); iterator.hasNext();) { + TimeStamped entry = iterator.next(); + ps.print("{timestamp: " + entry.timestamp + ", config: " + entry.data + "}"); + if (iterator.hasNext()) ps.print(","); + } + + ps.print("]"); + } + + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/SetConfigCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/SetConfigCmd.java index ab794b6b9..4a10a18ad 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/SetConfigCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp1/robot/SetConfigCmd.java @@ -1,50 +1,50 @@ -package org.sa.rainbow.brass.model.p2_cp1.robot; - -import java.util.List; - -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public class SetConfigCmd extends AbstractRainbowModelOperation { - - public SetConfigCmd(CP1RobotStateModelInstance model, String target, - String config) { - super("setConfig", model, target, config); - } - - @Override - public String getResult() throws IllegalStateException { - return ((CP1RobotState )getModelContext()).getConfigId(); - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setConfig"); - } - - @Override - protected void subExecute() throws RainbowException { - ((CP1RobotState )getModelContext().getModelInstance()).setConfigId(getParameters()[0]); - } - - @Override - protected void subRedo() throws RainbowException { - subExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - // TODO Auto-generated method stub - - } - - @Override - protected boolean checkModelValidForCommand(RobotState model) { - return model == getModelContext().getModelInstance(); - } - -} +package org.sa.rainbow.brass.model.p2_cp1.robot; + +import java.util.List; + +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class SetConfigCmd extends AbstractRainbowModelOperation { + + public SetConfigCmd(String commandName, CP1RobotStateModelInstance model, String target, + String config) { + super(commandName, model, target, config); + } + + @Override + public String getResult() throws IllegalStateException { + return ((CP1RobotState )getModelContext()).getConfigId(); + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents(messageFactory, getName()); + } + + @Override + protected void subExecute() throws RainbowException { + ((CP1RobotState )getModelContext().getModelInstance()).setConfigId(getParameters()[0]); + } + + @Override + protected void subRedo() throws RainbowException { + subExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + // TODO Auto-generated method stub + + } + + @Override + protected boolean checkModelValidForCommand(RobotState model) { + return model == getModelContext().getModelInstance(); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/CP3ModelAccessor.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/CP3ModelAccessor.java index 7f98b1e84..32e0a4b34 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/CP3ModelAccessor.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/CP3ModelAccessor.java @@ -1,38 +1,38 @@ -package org.sa.rainbow.brass.model.p2_cp3; - -import org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.brass.model.P2ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.acme.TurtlebotModelInstance; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotStateModelInstance; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; -import org.sa.rainbow.core.ports.IModelsManagerPort; - -public class CP3ModelAccessor extends P2ModelAccessor implements ICP3ModelAccessor { - private CP3RobotStateModelInstance m_robotStateModel; - private TurtlebotModelInstance m_turtlebotArchModel; - public CP3ModelAccessor (IModelsManagerPort mmp) { - super(mmp); - } - - @Override - public TurtlebotModelInstance getTurtlebotModel() { - if (m_turtlebotArchModel == null) { - m_turtlebotArchModel = (TurtlebotModelInstance) m_modelsManagerPort - .getModelInstance(new ModelReference("Turtlebot", "Acme")); - } - return m_turtlebotArchModel; - } - - @Override - public CP3RobotStateModelInstance getRobotStateModel() { - if (m_robotStateModel == null) { - CP3RobotStateModelInstance modelInstance = (CP3RobotStateModelInstance) m_modelsManagerPort.getModelInstance( - new ModelReference("Robot", RobotStateModelInstance.ROBOT_STATE_TYPE)); - m_robotStateModel = modelInstance; - } - return m_robotStateModel; - } -} +package org.sa.rainbow.brass.model.p2_cp3; + +import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.brass.model.P2ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.acme.TurtlebotModelInstance; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotStateModelInstance; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelsManagerPort; + +public class CP3ModelAccessor extends P2ModelAccessor implements ICP3ModelAccessor { + private CP3RobotStateModelInstance m_robotStateModel; + private TurtlebotModelInstance m_turtlebotArchModel; + public CP3ModelAccessor (IModelsManagerPort mmp) { + super(mmp); + } + + @Override + public TurtlebotModelInstance getTurtlebotModel() { + if (m_turtlebotArchModel == null) { + m_turtlebotArchModel = (TurtlebotModelInstance) m_modelsManagerPort + .getModelInstance(new ModelReference("Turtlebot", "Acme")); + } + return m_turtlebotArchModel; + } + + @Override + public CP3RobotStateModelInstance getRobotStateModel() { + if (m_robotStateModel == null) { + CP3RobotStateModelInstance modelInstance = (CP3RobotStateModelInstance) m_modelsManagerPort.getModelInstance( + new ModelReference("Robot", RobotStateModelInstance.ROBOT_STATE_TYPE)); + m_robotStateModel = modelInstance; + } + return m_robotStateModel; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/SetActiveCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/SetActiveCmd.java index b7c973f93..f85b1c6cd 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/SetActiveCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/SetActiveCmd.java @@ -1,66 +1,66 @@ -package org.sa.rainbow.brass.model.p2_cp3.acme; - -import java.util.LinkedList; -import java.util.List; - -import org.acmestudio.acme.core.IAcmeType; -import org.acmestudio.acme.core.type.IAcmeEnumType; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.acmestudio.acme.model.util.core.UMEnumValue; -import org.acmestudio.acme.type.AcmeTypeHelper; -import org.sa.rainbow.brass.model.p2_cp3.acme.TurtlebotModelInstance.ActiveT; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; -import org.sa.rainbow.model.acme.AcmeModelOperation; - -public class SetActiveCmd extends AcmeModelOperation { - - private ActiveT m_enablement; - - public SetActiveCmd(AcmeModelInstance model, String target, String enablement) { - super("setActive", model, target, enablement); - m_enablement = TurtlebotModelInstance.ActiveT.valueOf(enablement); - } - - @Override - public IAcmeProperty getResult() throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty(); - } - - @Override - protected List> doConstructCommand() throws RainbowModelException { - - IAcmeComponent cr = getModelContext().resolveInModel(getTarget(), IAcmeComponent.class); - if (cr == null) - throw new RainbowModelException("Cannot find component " + getTarget() + " in the system"); - IAcmeEnumType et = (IAcmeEnumType) AcmeTypeHelper.extractTypeStructure((IAcmeType )cr.lookupName("ActiveT", true)); - - if (!et.getValues().contains(m_enablement.name())) { - throw new RainbowModelException("Cannot assign value to EnablementT: " + m_enablement.name()); - } - - IAcmeProperty prop = cr.getProperty("enablement"); - - List> cmds = new LinkedList<>(); - - if (prop != null) { - m_command = cr.getCommandFactory().propertyValueSetCommand(prop, - new UMEnumValue(m_enablement.name())); - cmds.add(m_command); - } else { - m_command = cr.getCommandFactory().propertyCreateCommand(cr, "enablement", et, new UMEnumValue(m_enablement.name())); - cmds.add(m_command); - } - return cmds; - } - - @Override - protected boolean checkModelValidForCommand(IAcmeSystem model) { - return true; - } - -} +package org.sa.rainbow.brass.model.p2_cp3.acme; + +import java.util.LinkedList; +import java.util.List; + +import org.acmestudio.acme.core.IAcmeType; +import org.acmestudio.acme.core.type.IAcmeEnumType; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.acmestudio.acme.model.util.core.UMEnumValue; +import org.acmestudio.acme.type.AcmeTypeHelper; +import org.sa.rainbow.brass.model.p2_cp3.acme.TurtlebotModelInstance.ActiveT; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.AcmeModelOperation; + +public class SetActiveCmd extends AcmeModelOperation { + + private ActiveT m_enablement; + + public SetActiveCmd(String commandName, AcmeModelInstance model, String target, String enablement) { + super(commandName, model, target, enablement); + m_enablement = TurtlebotModelInstance.ActiveT.valueOf(enablement); + } + + @Override + public IAcmeProperty getResult() throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty(); + } + + @Override + protected List> doConstructCommand() throws RainbowModelException { + + IAcmeComponent cr = getModelContext().resolveInModel(getTarget(), IAcmeComponent.class); + if (cr == null) + throw new RainbowModelException("Cannot find component " + getTarget() + " in the system"); + IAcmeEnumType et = (IAcmeEnumType) AcmeTypeHelper.extractTypeStructure((IAcmeType )cr.lookupName("ActiveT", true)); + + if (!et.getValues().contains(m_enablement.name())) { + throw new RainbowModelException("Cannot assign value to EnablementT: " + m_enablement.name()); + } + + IAcmeProperty prop = cr.getProperty("enablement"); + + List> cmds = new LinkedList<>(); + + if (prop != null) { + m_command = cr.getCommandFactory().propertyValueSetCommand(prop, + new UMEnumValue(m_enablement.name())); + cmds.add(m_command); + } else { + m_command = cr.getCommandFactory().propertyCreateCommand(cr, "enablement", et, new UMEnumValue(m_enablement.name())); + cmds.add(m_command); + } + return cmds; + } + + @Override + protected boolean checkModelValidForCommand(IAcmeSystem model) { + return true; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotLoadModelCommand.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotLoadModelCommand.java index e23483848..fb77d5ac7 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotLoadModelCommand.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotLoadModelCommand.java @@ -1,70 +1,70 @@ -package org.sa.rainbow.brass.model.p2_cp3.acme; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.acmestudio.acme.core.resource.IAcmeResource; -import org.acmestudio.acme.core.resource.ParsingFailureException; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.standalone.resource.StandaloneResourceProvider; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; - -public class TurtlebotLoadModelCommand extends AbstractLoadModelCmd { - - private InputStream m_inputStream; - private String m_systemName; - private TurtlebotModelInstance m_result; - - public TurtlebotLoadModelCommand(IModelsManager mm, String resource, InputStream is, String source) { - super("loadTurtlebotModel", mm, resource, is, source); - m_systemName = resource; - m_inputStream = is; - } - - @Override - public TurtlebotModelInstance getResult() throws IllegalStateException { - return m_result; - } - - @Override - public ModelReference getModelReference() { - return new ModelReference(m_systemName, "Acme"); - } - - @Override - protected void subExecute() throws RainbowException { - try { - IAcmeResource resource = StandaloneResourceProvider.instance() - .acmeResourceForObject(new File(getOriginalSource())); - m_result = new TurtlebotModelInstance(resource.getModel().getSystem(m_systemName), getOriginalSource()); - doPostExecute(); - } catch (ParsingFailureException | IOException e) { - throw new RainbowException(e); - } - } - - @Override - protected void subRedo() throws RainbowException { - doPostExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - doPostUndo(); - } - - @Override - protected boolean checkModelValidForCommand(Object model) { - return true; - } - - @Override - public String getName() { - return "loadTurtlebotModel"; - } - -} +package org.sa.rainbow.brass.model.p2_cp3.acme; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + +import org.acmestudio.acme.core.resource.IAcmeResource; +import org.acmestudio.acme.core.resource.ParsingFailureException; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.standalone.resource.StandaloneResourceProvider; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; + +public class TurtlebotLoadModelCommand extends AbstractLoadModelCmd { + + private InputStream m_inputStream; + private String m_systemName; + private TurtlebotModelInstance m_result; + + public TurtlebotLoadModelCommand(IModelsManager mm, String resource, InputStream is, String source) { + super("loadTurtlebotModel", mm, resource, is, source); + m_systemName = resource; + m_inputStream = is; + } + + @Override + public TurtlebotModelInstance getResult() throws IllegalStateException { + return m_result; + } + + @Override + public ModelReference getModelReference() { + return new ModelReference(m_systemName, "Acme"); + } + + @Override + protected void subExecute() throws RainbowException { + try { + IAcmeResource resource = StandaloneResourceProvider.instance() + .acmeResourceForObject(new File(getOriginalSource())); + m_result = new TurtlebotModelInstance(resource.getModel().getSystem(m_systemName), getOriginalSource()); + doPostExecute(); + } catch (ParsingFailureException | IOException e) { + throw new RainbowException(e); + } + } + + @Override + protected void subRedo() throws RainbowException { + doPostExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + doPostUndo(); + } + + @Override + protected boolean checkModelValidForCommand(Object model) { + return true; + } + + @Override + public String getName() { + return "loadTurtlebotModel"; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotModelCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotModelCommandFactory.java index 74bcdf1a5..5128109d8 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotModelCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotModelCommandFactory.java @@ -1,33 +1,32 @@ -package org.sa.rainbow.brass.model.p2_cp3.acme; - -import java.io.InputStream; - -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.model.acme.AcmeModelCommandFactory; - -public class TurtlebotModelCommandFactory extends AcmeModelCommandFactory { - - public static TurtlebotLoadModelCommand loadCommand(ModelsManager mm, String name, InputStream stream, String source) { - return new TurtlebotLoadModelCommand (mm, name, stream, source); - } - - - public TurtlebotModelCommandFactory(TurtlebotModelInstance model) { - super(model); - } - - @Override - protected void fillInCommandMap() { - super.fillInCommandMap(); - m_commandMap.put("setActive".toLowerCase(), SetActiveCmd.class); - } - - public SetActiveCmd setActive(IAcmeComponent comp, TurtlebotModelInstance.ActiveT enablement) { - if (ModelHelper.getAcmeSystem(comp) != m_modelInstance.getModelInstance()) { - throw new IllegalArgumentException("Cannot create a command for a system that is not managed by this command factory"); - } - return new SetActiveCmd((TurtlebotModelInstance )m_modelInstance, comp.getQualifiedName(), enablement.name()); - } -} +package org.sa.rainbow.brass.model.p2_cp3.acme; + +import java.io.InputStream; + +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.model.acme.AcmeModelCommandFactory; + +public class TurtlebotModelCommandFactory extends AcmeModelCommandFactory { + + private static final String SET_ACTIVE_CMD = "setActive"; + + @LoadOperation + public static TurtlebotLoadModelCommand loadCommand(ModelsManager mm, String name, InputStream stream, String source) { + return new TurtlebotLoadModelCommand (mm, name, stream, source); + } + + + public TurtlebotModelCommandFactory(TurtlebotModelInstance model) throws RainbowException { + super(model); + } + + @Operation(name=SET_ACTIVE_CMD) + public SetActiveCmd setActive(IAcmeComponent comp, TurtlebotModelInstance.ActiveT enablement) { + if (ModelHelper.getAcmeSystem(comp) != m_modelInstance.getModelInstance()) { + throw new IllegalArgumentException("Cannot create a command for a system that is not managed by this command factory"); + } + return new SetActiveCmd(SET_ACTIVE_CMD, (TurtlebotModelInstance )m_modelInstance, comp.getQualifiedName(), enablement.name()); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotModelInstance.java index 8d514dca8..6cb33e317 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/acme/TurtlebotModelInstance.java @@ -1,68 +1,69 @@ -package org.sa.rainbow.brass.model.p2_cp3.acme; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import org.acmestudio.acme.core.type.IAcmeEnumValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class TurtlebotModelInstance extends AcmeModelInstance { - - public static enum ActiveT {ACTIVE, INACTIVE, FAILED}; - - - private TurtlebotModelCommandFactory m_commandFactory; - - public TurtlebotModelInstance(IAcmeSystem system, String source) { - super(system, source); - } - - @Override - protected AcmeModelInstance generateInstance(IAcmeSystem sys) { - return new TurtlebotModelInstance(sys, getOriginalSource()); - } - - @Override - public TurtlebotModelCommandFactory getCommandFactory() { - if (m_commandFactory == null) - m_commandFactory = new TurtlebotModelCommandFactory(this); - return m_commandFactory; - } - - public Collection getActiveComponents() { - return getComponentEnablement("ACTIVE"); - } - - private Collection getComponentEnablement(String compare) { - Set components = getModelInstance().getComponents(); - Set active = new HashSet (); - for (IAcmeComponent c : components) { - IAcmeProperty property = c.getProperty("enablement"); - if (property != null) { - IAcmePropertyValue value = property.getValue(); - if (value instanceof IAcmeEnumValue) { - IAcmeEnumValue en = (IAcmeEnumValue) value; - if (en.getValue().equals(compare)) { - active.add(c.getName()); - } - - } - } - } - return active; - } - - public Collection getFailedComponents() { - return getComponentEnablement("FAILED"); - } - - public Collection getInactiveComponents() { - return getComponentEnablement("INACTIVE"); - } - -} +package org.sa.rainbow.brass.model.p2_cp3.acme; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import org.acmestudio.acme.core.type.IAcmeEnumValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class TurtlebotModelInstance extends AcmeModelInstance { + + public static enum ActiveT {ACTIVE, INACTIVE, FAILED}; + + + private TurtlebotModelCommandFactory m_commandFactory; + + public TurtlebotModelInstance(IAcmeSystem system, String source) { + super(system, source); + } + + @Override + protected AcmeModelInstance generateInstance(IAcmeSystem sys) { + return new TurtlebotModelInstance(sys, getOriginalSource()); + } + + @Override + public TurtlebotModelCommandFactory getCommandFactory() throws RainbowException { + if (m_commandFactory == null) + m_commandFactory = new TurtlebotModelCommandFactory(this); + return m_commandFactory; + } + + public Collection getActiveComponents() { + return getComponentEnablement("ACTIVE"); + } + + private Collection getComponentEnablement(String compare) { + Set components = getModelInstance().getComponents(); + Set active = new HashSet (); + for (IAcmeComponent c : components) { + IAcmeProperty property = c.getProperty("enablement"); + if (property != null) { + IAcmePropertyValue value = property.getValue(); + if (value instanceof IAcmeEnumValue) { + IAcmeEnumValue en = (IAcmeEnumValue) value; + if (en.getValue().equals(compare)) { + active.add(c.getName()); + } + + } + } + } + return active; + } + + public Collection getFailedComponents() { + return getComponentEnablement("FAILED"); + } + + public Collection getInactiveComponents() { + return getComponentEnablement("INACTIVE"); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/Clock.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/Clock.java index afa701b6f..90728a2ea 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/Clock.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/Clock.java @@ -1,34 +1,34 @@ -package org.sa.rainbow.brass.model.p2_cp3.clock; - -import org.sa.rainbow.core.models.ModelReference; -/** - * The system publishes a simulation clock time. This represents the model for the clock. - * @author schmerl - * - */ -public class Clock { - private ModelReference m_model; - private double m_currentTime = 0.0; - - public Clock (ModelReference model) { - m_model = model; - } - - public void setCurrentTime (double time) { - m_currentTime = time; - } - - public double currentTime() { - return m_currentTime; - } - - public Clock copy() { - Clock c = new Clock(m_model); - c.m_currentTime = m_currentTime; - return c; - } - - public ModelReference getModelReference() { - return m_model; - } -} +package org.sa.rainbow.brass.model.p2_cp3.clock; + +import org.sa.rainbow.core.models.ModelReference; +/** + * The system publishes a simulation clock time. This represents the model for the clock. + * @author schmerl + * + */ +public class Clock { + private ModelReference m_model; + private double m_currentTime = 0.0; + + public Clock (ModelReference model) { + m_model = model; + } + + public void setCurrentTime (double time) { + m_currentTime = time; + } + + public double currentTime() { + return m_currentTime; + } + + public Clock copy() { + Clock c = new Clock(m_model); + c.m_currentTime = m_currentTime; + return c; + } + + public ModelReference getModelReference() { + return m_model; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockCommandFactory.java index 5e213a7d4..8c0485d9e 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockCommandFactory.java @@ -1,36 +1,36 @@ -package org.sa.rainbow.brass.model.p2_cp3.clock; - -import java.io.InputStream; - -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class ClockCommandFactory extends ModelCommandFactory { - - public static ClockLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream - stream, String source) { - return new ClockLoadCmd(mm, modelName, stream, source); - } - - public ClockCommandFactory(IModelInstance model) { - super (ClockModelInstance.class, model); - } - - @Override - protected void fillInCommandMap() { - m_commandMap.put("setCurrentTime".toLowerCase(), SetCurrentTimeCmd.class); - } - - @Override - public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { - // TODO Auto-generated method stub - return null; - } - - public SetCurrentTimeCmd setCurrentTimeCmd(double t) { - return new SetCurrentTimeCmd((ClockModelInstance )m_modelInstance, "", Double.toString(t)); - } -} +package org.sa.rainbow.brass.model.p2_cp3.clock; + +import java.io.InputStream; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class ClockCommandFactory extends ModelCommandFactory { + + private static final String SET_CURRENT_TIME_CMD = "setCurrentTime"; + + @LoadOperation + public static ClockLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream + stream, String source) { + return new ClockLoadCmd(mm, modelName, stream, source); + } + + public ClockCommandFactory(IModelInstance model) throws RainbowException { + super (ClockModelInstance.class, model); + } + + @Override + public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { + // TODO Auto-generated method stub + return null; + } + + @Operation(name=SET_CURRENT_TIME_CMD) + public SetCurrentTimeCmd setCurrentTimeCmd(double t) { + return new SetCurrentTimeCmd(SET_CURRENT_TIME_CMD, (ClockModelInstance )m_modelInstance, "", Double.toString(t)); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockLoadCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockLoadCmd.java index 2dacfd556..f51b2101c 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockLoadCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockLoadCmd.java @@ -1,61 +1,61 @@ -package org.sa.rainbow.brass.model.p2_cp3.clock; - -import java.io.InputStream; - -import org.sa.rainbow.brass.model.mission.MissionState; -import org.sa.rainbow.brass.model.mission.MissionStateModelInstance; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; - -public class ClockLoadCmd extends AbstractLoadModelCmd { - - private String m_modelName; - private InputStream m_stream; - private ClockModelInstance m_result; - - public ClockLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { - super("loadClock", mm, resource, is, source); - m_modelName = resource; - m_stream = is; - } - - @Override - public IModelInstance getResult() throws IllegalStateException { - return m_result; - } - - @Override - public ModelReference getModelReference() { - return new ModelReference(m_modelName, ClockModelInstance.CLOCK_TYPE); - } - - @Override - protected void subExecute() throws RainbowException { - if (m_stream == null) { - Clock c = new Clock(getModelReference()); - m_result = new ClockModelInstance(c, getOriginalSource ()); - doPostExecute (); - } - } - - @Override - protected void subRedo() throws RainbowException { - doPostExecute (); - - } - - @Override - protected void subUndo() throws RainbowException { - doPostUndo (); - - } - - @Override - protected boolean checkModelValidForCommand(Object model) { - return true; - } - -} +package org.sa.rainbow.brass.model.p2_cp3.clock; + +import java.io.InputStream; + +import org.sa.rainbow.brass.model.mission.MissionState; +import org.sa.rainbow.brass.model.mission.MissionStateModelInstance; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; + +public class ClockLoadCmd extends AbstractLoadModelCmd { + + private String m_modelName; + private InputStream m_stream; + private ClockModelInstance m_result; + + public ClockLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { + super("loadClock", mm, resource, is, source); + m_modelName = resource; + m_stream = is; + } + + @Override + public IModelInstance getResult() throws IllegalStateException { + return m_result; + } + + @Override + public ModelReference getModelReference() { + return new ModelReference(m_modelName, ClockModelInstance.CLOCK_TYPE); + } + + @Override + protected void subExecute() throws RainbowException { + if (m_stream == null) { + Clock c = new Clock(getModelReference()); + m_result = new ClockModelInstance(c, getOriginalSource ()); + doPostExecute (); + } + } + + @Override + protected void subRedo() throws RainbowException { + doPostExecute (); + + } + + @Override + protected void subUndo() throws RainbowException { + doPostUndo (); + + } + + @Override + protected boolean checkModelValidForCommand(Object model) { + return true; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockModelInstance.java index e4c32d526..af672d665 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockModelInstance.java @@ -1,66 +1,66 @@ -package org.sa.rainbow.brass.model.p2_cp3.clock; - -import org.sa.rainbow.core.error.RainbowCopyException; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class ClockModelInstance implements IModelInstance { - - public static final String CLOCK_TYPE = "Clock"; - private Clock m_clock; - private ClockCommandFactory m_commandFactory; - private String m_source; - - public ClockModelInstance(Clock c, String source) { - setModelInstance(c); - setOriginalSource(source); - } - - @Override - public Clock getModelInstance() { - return m_clock; - } - - @Override - public void setModelInstance(Clock model) { - m_clock = model; - } - - @Override - public IModelInstance copyModelInstance(String newName) throws RainbowCopyException { - return new ClockModelInstance(m_clock.copy(), getOriginalSource()); - } - - @Override - public String getModelType() { - return CLOCK_TYPE; - } - - @Override - public String getModelName() { - return getModelInstance().getModelReference().getModelName (); - } - - @Override - public ClockCommandFactory getCommandFactory() { - if (m_commandFactory == null) - m_commandFactory = new ClockCommandFactory(this); - return m_commandFactory; - } - - @Override - public void setOriginalSource(String source) { - m_source = source; - } - - @Override - public String getOriginalSource() { - return m_source; - } - - @Override - public void dispose() throws RainbowException { - } - -} +package org.sa.rainbow.brass.model.p2_cp3.clock; + +import org.sa.rainbow.core.error.RainbowCopyException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class ClockModelInstance implements IModelInstance { + + public static final String CLOCK_TYPE = "Clock"; + private Clock m_clock; + private ClockCommandFactory m_commandFactory; + private String m_source; + + public ClockModelInstance(Clock c, String source) { + setModelInstance(c); + setOriginalSource(source); + } + + @Override + public Clock getModelInstance() { + return m_clock; + } + + @Override + public void setModelInstance(Clock model) { + m_clock = model; + } + + @Override + public IModelInstance copyModelInstance(String newName) throws RainbowCopyException { + return new ClockModelInstance(m_clock.copy(), getOriginalSource()); + } + + @Override + public String getModelType() { + return CLOCK_TYPE; + } + + @Override + public String getModelName() { + return getModelInstance().getModelReference().getModelName (); + } + + @Override + public ClockCommandFactory getCommandFactory() throws RainbowException { + if (m_commandFactory == null) + m_commandFactory = new ClockCommandFactory(this); + return m_commandFactory; + } + + @Override + public void setOriginalSource(String source) { + m_source = source; + } + + @Override + public String getOriginalSource() { + return m_source; + } + + @Override + public void dispose() throws RainbowException { + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockedModel.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockedModel.java index c077a5fa3..e777ed8b7 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockedModel.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/ClockedModel.java @@ -1,37 +1,37 @@ -package org.sa.rainbow.brass.model.p2_cp3.clock; - -import java.util.Date; -/** - * A model that stores histories of values (like locations, etc.) shoud be - * timestamped with respect to a clock. Therefore, all such models should inherit - * this. If a clock is provided, this is used; otherwise we use system time. - * @author schmerl - * - */ -public class ClockedModel { - - private Clock m_clock = null; - - public void setClock(Clock clock) { - m_clock = clock; - } - - public double clockTime() { - if (m_clock == null) { - return new Date().getTime(); - } - else - return m_clock.currentTime (); - } - - public class TimeStamped { - public double timestamp; - public T data; - - public TimeStamped(T d) { - data = d; - timestamp = clockTime(); - } - } - -} +package org.sa.rainbow.brass.model.p2_cp3.clock; + +import java.util.Date; +/** + * A model that stores histories of values (like locations, etc.) shoud be + * timestamped with respect to a clock. Therefore, all such models should inherit + * this. If a clock is provided, this is used; otherwise we use system time. + * @author schmerl + * + */ +public class ClockedModel { + + private Clock m_clock = null; + + public void setClock(Clock clock) { + m_clock = clock; + } + + public double clockTime() { + if (m_clock == null) { + return new Date().getTime(); + } + else + return m_clock.currentTime (); + } + + public class TimeStamped { + public double timestamp; + public T data; + + public TimeStamped(T d) { + data = d; + timestamp = clockTime(); + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/SetClockModelCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/SetClockModelCmd.java index cc68b6cbd..081b31748 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/SetClockModelCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/SetClockModelCmd.java @@ -1,62 +1,62 @@ -package org.sa.rainbow.brass.model.p2_cp3.clock; - -import java.text.MessageFormat; -import java.util.List; - -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public abstract class SetClockModelCmd extends AbstractRainbowModelOperation { - - private String m_clockReference; - - public SetClockModelCmd(IModelInstance model, String target, - String clockReference) { - super("setClockModel", model, target, clockReference); - m_clockReference = clockReference; - } - - @Override - public String getResult() throws IllegalStateException { - // TODO Auto-generated method stub - return null; - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - // TODO Auto-generated method stub - return null; - } - - @Override - protected void subExecute() throws RainbowException { - IModelInstance mr = Rainbow.instance().getRainbowMaster().modelsManager().getModelInstance(ModelReference.fromString(m_clockReference)); - if (mr instanceof ClockModelInstance) { - Clock clock = ((ClockModelInstance )mr).getModelInstance(); - getModelContext().getModelInstance().setClock(clock); - } - else { - throw new RainbowException(MessageFormat.format("Model {0} is not a Clock!", m_clockReference)); - } - - } - - @Override - protected void subRedo() throws RainbowException { - } - - @Override - protected void subUndo() throws RainbowException { - } - - @Override - protected boolean checkModelValidForCommand(ClockedModel model) { - return true; - } - -} +package org.sa.rainbow.brass.model.p2_cp3.clock; + +import java.text.MessageFormat; +import java.util.List; + +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public abstract class SetClockModelCmd extends AbstractRainbowModelOperation { + + private String m_clockReference; + + public SetClockModelCmd(String commandName, IModelInstance model, String target, + String clockReference) { + super(commandName, model, target, clockReference); + m_clockReference = clockReference; + } + + @Override + public String getResult() throws IllegalStateException { + // TODO Auto-generated method stub + return null; + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + // TODO Auto-generated method stub + return null; + } + + @Override + protected void subExecute() throws RainbowException { + IModelInstance mr = Rainbow.instance().getRainbowMaster().modelsManager().getModelInstance(ModelReference.fromString(m_clockReference)); + if (mr instanceof ClockModelInstance) { + Clock clock = ((ClockModelInstance )mr).getModelInstance(); + getModelContext().getModelInstance().setClock(clock); + } + else { + throw new RainbowException(MessageFormat.format("Model {0} is not a Clock!", m_clockReference)); + } + + } + + @Override + protected void subRedo() throws RainbowException { + } + + @Override + protected void subUndo() throws RainbowException { + } + + @Override + protected boolean checkModelValidForCommand(ClockedModel model) { + return true; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/SetCurrentTimeCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/SetCurrentTimeCmd.java index f363f3984..9199d1991 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/SetCurrentTimeCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/clock/SetCurrentTimeCmd.java @@ -14,8 +14,8 @@ public class SetCurrentTimeCmd extends AbstractRainbowModelOperation { - - public static MissionStateLoadCmd loadCommand (ModelsManager mm, String modelName, InputStream - stream, String source) { - return new MissionStateLoadCmd (mm, modelName, stream, source); - } - - public MissionCommandFactory ( - IModelInstance model) { - super (MissionStateModelInstance.class, model); - } - - @Override - protected void fillInCommandMap () { - m_commandMap.put ("setCurrentLocation".toLowerCase (), SetCurrentLocationCmd.class); - m_commandMap.put ("setDeadlineCmd".toLowerCase (), SetDeadlineCmd.class); - m_commandMap.put ("setTargetWaypoint".toLowerCase (), SetTargetWaypointCmd.class); - m_commandMap.put("setReconfiguring".toLowerCase(), SetReconfiguringCmd.class); - m_commandMap.put("setUtilityPreference".toLowerCase(), SetUtilityPreferenceCmd.class); - - } - - @Override - public SaveMissionCmd saveCommand (String location) throws RainbowModelException { - try (FileOutputStream os = new FileOutputStream (location)) { - return new SaveMissionCmd(null, location, os, m_modelInstance.getOriginalSource ()); - } - catch (IOException e) { - return null; - } - } - - public SetCurrentLocationCmd setCurrentLocationCmd (double x, double y, double w) { - return new SetCurrentLocationCmd ((MissionStateModelInstance) m_modelInstance, "", Double.toString (x), - Double.toString (y), Double.toString (w)); - } - - public SetDeadlineCmd setDeadlineCmd (long d) { - return new SetDeadlineCmd ((MissionStateModelInstance) m_modelInstance, "", - Double.toString (d)); - } - - public SetTargetWaypointCmd setTargetWaypointCmd (String t) { - return new SetTargetWaypointCmd ((MissionStateModelInstance )m_modelInstance, "", t); - } - - public SetReconfiguringCmd setReconfiguringCmd(boolean r) { - return new SetReconfiguringCmd((MissionStateModelInstance )m_modelInstance, "", Boolean.toString(r)); - } - - public SetUtilityPreferenceCmd setUtilityPreference(UtilityPreference preference) { - return new SetUtilityPreferenceCmd((MissionStateModelInstance )m_modelInstance, "", preference.toString()); - } -} +package org.sa.rainbow.brass.model.p2_cp3.mission; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.UtilityPreference; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowStateModelInstance; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +/** + * Created by schmerl on 12/27/2016. + */ +public class MissionCommandFactory extends ModelCommandFactory { + + private static final String SET_UTILITY_PREFERENCE_CMD = "setUtilityPreference"; + private static final String SET_RECONFIGURING_CMD = "setReconfiguring"; + private static final String SET_TARGET_WAYPOINT_CMD = "setTargetWaypoint"; + private static final String SET_DEADLINE_CMD = "setDeadline"; + private static final String SET_CURRENT_LOCATION_CMD = "setCurrentLocation"; + + @LoadOperation + public static MissionStateLoadCmd loadCommand (ModelsManager mm, String modelName, InputStream + stream, String source) { + return new MissionStateLoadCmd (mm, modelName, stream, source); + } + + public MissionCommandFactory ( + IModelInstance model) throws RainbowException { + super (MissionStateModelInstance.class, model); + } + + @Override + public SaveMissionCmd saveCommand (String location) throws RainbowModelException { + try (FileOutputStream os = new FileOutputStream (location)) { + return new SaveMissionCmd(null, location, os, m_modelInstance.getOriginalSource ()); + } + catch (IOException e) { + return null; + } + } + + @Operation(name=SET_CURRENT_LOCATION_CMD) + public SetCurrentLocationCmd setCurrentLocationCmd (double x, double y, double w) { + return new SetCurrentLocationCmd (SET_CURRENT_LOCATION_CMD, (MissionStateModelInstance) m_modelInstance, "", Double.toString (x), + Double.toString (y), Double.toString (w)); + } + + @Operation(name=SET_DEADLINE_CMD) + public SetDeadlineCmd setDeadlineCmd (long d) { + return new SetDeadlineCmd (SET_DEADLINE_CMD, (MissionStateModelInstance) m_modelInstance, "", + Double.toString (d)); + } + + @Operation(name=SET_TARGET_WAYPOINT_CMD) + public SetTargetWaypointCmd setTargetWaypointCmd (String t) { + return new SetTargetWaypointCmd (SET_TARGET_WAYPOINT_CMD, (MissionStateModelInstance )m_modelInstance, "", t); + } + + @Operation(name=SET_RECONFIGURING_CMD) + public SetReconfiguringCmd setReconfiguringCmd(boolean r) { + return new SetReconfiguringCmd(SET_RECONFIGURING_CMD, (MissionStateModelInstance )m_modelInstance, "", Boolean.toString(r)); + } + + @Operation(name=SET_UTILITY_PREFERENCE_CMD) + public SetUtilityPreferenceCmd setUtilityPreference(UtilityPreference preference) { + return new SetUtilityPreferenceCmd(SET_UTILITY_PREFERENCE_CMD, (MissionStateModelInstance )m_modelInstance, "", preference.toString()); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionState.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionState.java index ec5f9f2a6..4a84eab5a 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionState.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionState.java @@ -1,214 +1,214 @@ -package org.sa.rainbow.brass.model.p2_cp3.mission; - -import java.text.SimpleDateFormat; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.Deque; -import java.util.List; -import java.util.TimeZone; - -import org.sa.rainbow.brass.model.instructions.SetLocalizationFidelityInstruction.LocalizationFidelity; -import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel; -import org.sa.rainbow.core.models.ModelReference; - -/** - * Created by schmerl on 12/27/2016. - */ -public class MissionState extends ClockedModel { - - // This should be in UTC - public static final SimpleDateFormat BRASS_DATE_FORMAT = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss'Z'"); - static { - BRASS_DATE_FORMAT.setTimeZone (TimeZone.getTimeZone ("UTC")); - } - - public static enum UtilityPreference { - FAVOR_SAFETY("favor-safety"), - FAVOR_TIMELINESS("favor-timeliness"), - FAVOR_EFFICIENCY("favor-efficiency"); - - private String mnemonic; - - private UtilityPreference(String mn) { - mnemonic = mn; - } - - @Override - public String toString() { - return mnemonic; - } - - public static UtilityPreference getValue(String mn) { - for (UtilityPreference p : UtilityPreference.values()) { - if (p.toString().equals(mn)) - return p; - } - return null; - } - } - - public static enum Heading { - NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST; - - public static Heading convertFromRadians (double w) { - if (w < 0) { - w = w + 2 * Math.PI; - } - if (w < Math.PI / 8 && w >= 7 * Math.PI / 8) return EAST; - if (w >= Math.PI / 8 && w < 3 * Math.PI / 8) return NORTHEAST; - if (w >= 3 * Math.PI / 8 && w < 5 * Math.PI / 8) return NORTH; - if (w >= 5 * Math.PI / 8 && w < 7 * Math.PI / 8) return NORTHWEST; - if (w >= 7 * Math.PI / 8 && w < 9 * Math.PI / 8) return WEST; - if (w >= 9 * Math.PI / 8 && w < 11 * Math.PI / 8) return Heading.SOUTHWEST; - if (w >= 11 * Math.PI / 8 && w < 13 * Math.PI / 8) return SOUTH; - if (w >= 13 * Math.PI / 8 && w < 15 * Math.PI / 8) return SOUTHEAST; - return EAST; - - } - - public static double convertToRadians (Heading h) { - if (h == EAST) return 0; - if (h == NORTHEAST) return Math.PI / 4; - if (h == NORTH) return Math.PI / 2; - if (h == NORTHWEST) return 3 * Math.PI / 4; - if (h == WEST) return Math.PI; - if (h == SOUTHWEST) return 5 * Math.PI / 4; - if (h == SOUTH) return 3 * Math.PI / 2; - if (h == SOUTHEAST) return 7 * Math.PI / 4; - return 0; - } - }; - - public static class LocationRecording { - protected double m_x; - protected double m_y; - protected double m_w; - protected Heading m_heading; - - public double getX () { - return m_x; - } - - public double getY () { - return m_y; - } - - public Heading getHeading () { - return m_heading; - } - - public double getRotation () { - return m_w; - } - - public LocationRecording copy () { - LocationRecording l = new LocationRecording (); - l.m_x = m_x; - l.m_y = m_y; - l.m_w = m_w; - l.m_heading = m_heading; - return l; - } - } - - - private final ModelReference m_model; - - - Deque> m_locationHistory = new ArrayDeque<> (); - Deque> m_deadlineHistory = new ArrayDeque<> (); - - private String m_targetWaypoint = ""; - - private UtilityPreference m_utilityPreference = UtilityPreference.FAVOR_SAFETY; - - private boolean m_reconfiguring; - - public MissionState (ModelReference model) { - m_model = model; - } - - public ModelReference getModelReference () { - return m_model; - } - - public void setCurrentPose (double x, double y, double w) { - LocationRecording l = new LocationRecording (); - l.m_x = x; - l.m_y = y; - l.m_w = w; - l.m_heading = Heading.convertFromRadians (w); - synchronized (m_locationHistory) { - m_locationHistory.push (new TimeStamped(l)); - } - } - - public LocationRecording getCurrentPose () { - if (m_locationHistory.isEmpty ()) return null; - synchronized (m_locationHistory) { - return m_locationHistory.peek ().data.copy (); - } - } - - public LocationRecording getInitialPose () { - synchronized (m_locationHistory) { - if (m_locationHistory.isEmpty ()) return null; - return m_locationHistory.getLast ().data.copy (); - } - } - - public void setDeadline (long d) { - synchronized (m_deadlineHistory) { - m_deadlineHistory.push (new TimeStamped(d)); - } - } - - public Long getDeadline () { - synchronized (m_deadlineHistory) { - - TimeStamped peek = m_deadlineHistory.peek (); - return peek!=null?peek.data:null; - } - } - - public void setTargetWaypoint (String waypoint) { - m_targetWaypoint = waypoint; - } - - public String getTargetWaypoint () { - return m_targetWaypoint; - } - - - public MissionState copy () { - MissionState s = new MissionState (m_model); - s.m_locationHistory = new ArrayDeque<> (m_locationHistory); - s.m_deadlineHistory = new ArrayDeque<> (m_deadlineHistory); - s.m_reconfiguring = m_reconfiguring; - return s; - } - - public boolean isMissionStarted () { - // TODO: CHange this when mission start detection is implemented - return true || !"".equals(getTargetWaypoint ()); - } - - public boolean isReconfiguring() { - return m_reconfiguring; - } - - public void setReconfiguring(boolean r) { - m_reconfiguring = r; - } - - public UtilityPreference getUtilityPreference() { - return m_utilityPreference; - } - - public void setUtilityPreference(UtilityPreference utilityPreference) { - m_utilityPreference = utilityPreference; - } - -} +package org.sa.rainbow.brass.model.p2_cp3.mission; + +import java.text.SimpleDateFormat; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.Deque; +import java.util.List; +import java.util.TimeZone; + +import org.sa.rainbow.brass.model.instructions.SetLocalizationFidelityInstruction.LocalizationFidelity; +import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel; +import org.sa.rainbow.core.models.ModelReference; + +/** + * Created by schmerl on 12/27/2016. + */ +public class MissionState extends ClockedModel { + + // This should be in UTC + public static final SimpleDateFormat BRASS_DATE_FORMAT = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss'Z'"); + static { + BRASS_DATE_FORMAT.setTimeZone (TimeZone.getTimeZone ("UTC")); + } + + public static enum UtilityPreference { + FAVOR_SAFETY("favor-safety"), + FAVOR_TIMELINESS("favor-timeliness"), + FAVOR_EFFICIENCY("favor-efficiency"); + + private String mnemonic; + + private UtilityPreference(String mn) { + mnemonic = mn; + } + + @Override + public String toString() { + return mnemonic; + } + + public static UtilityPreference getValue(String mn) { + for (UtilityPreference p : UtilityPreference.values()) { + if (p.toString().equals(mn)) + return p; + } + return null; + } + } + + public static enum Heading { + NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST; + + public static Heading convertFromRadians (double w) { + if (w < 0) { + w = w + 2 * Math.PI; + } + if (w < Math.PI / 8 && w >= 7 * Math.PI / 8) return EAST; + if (w >= Math.PI / 8 && w < 3 * Math.PI / 8) return NORTHEAST; + if (w >= 3 * Math.PI / 8 && w < 5 * Math.PI / 8) return NORTH; + if (w >= 5 * Math.PI / 8 && w < 7 * Math.PI / 8) return NORTHWEST; + if (w >= 7 * Math.PI / 8 && w < 9 * Math.PI / 8) return WEST; + if (w >= 9 * Math.PI / 8 && w < 11 * Math.PI / 8) return Heading.SOUTHWEST; + if (w >= 11 * Math.PI / 8 && w < 13 * Math.PI / 8) return SOUTH; + if (w >= 13 * Math.PI / 8 && w < 15 * Math.PI / 8) return SOUTHEAST; + return EAST; + + } + + public static double convertToRadians (Heading h) { + if (h == EAST) return 0; + if (h == NORTHEAST) return Math.PI / 4; + if (h == NORTH) return Math.PI / 2; + if (h == NORTHWEST) return 3 * Math.PI / 4; + if (h == WEST) return Math.PI; + if (h == SOUTHWEST) return 5 * Math.PI / 4; + if (h == SOUTH) return 3 * Math.PI / 2; + if (h == SOUTHEAST) return 7 * Math.PI / 4; + return 0; + } + }; + + public static class LocationRecording { + protected double m_x; + protected double m_y; + protected double m_w; + protected Heading m_heading; + + public double getX () { + return m_x; + } + + public double getY () { + return m_y; + } + + public Heading getHeading () { + return m_heading; + } + + public double getRotation () { + return m_w; + } + + public LocationRecording copy () { + LocationRecording l = new LocationRecording (); + l.m_x = m_x; + l.m_y = m_y; + l.m_w = m_w; + l.m_heading = m_heading; + return l; + } + } + + + private final ModelReference m_model; + + + Deque> m_locationHistory = new ArrayDeque<> (); + Deque> m_deadlineHistory = new ArrayDeque<> (); + + private String m_targetWaypoint = ""; + + private UtilityPreference m_utilityPreference = UtilityPreference.FAVOR_SAFETY; + + private boolean m_reconfiguring; + + public MissionState (ModelReference model) { + m_model = model; + } + + public ModelReference getModelReference () { + return m_model; + } + + public void setCurrentPose (double x, double y, double w) { + LocationRecording l = new LocationRecording (); + l.m_x = x; + l.m_y = y; + l.m_w = w; + l.m_heading = Heading.convertFromRadians (w); + synchronized (m_locationHistory) { + m_locationHistory.push (new TimeStamped(l)); + } + } + + public LocationRecording getCurrentPose () { + if (m_locationHistory.isEmpty ()) return null; + synchronized (m_locationHistory) { + return m_locationHistory.peek ().data.copy (); + } + } + + public LocationRecording getInitialPose () { + synchronized (m_locationHistory) { + if (m_locationHistory.isEmpty ()) return null; + return m_locationHistory.getLast ().data.copy (); + } + } + + public void setDeadline (long d) { + synchronized (m_deadlineHistory) { + m_deadlineHistory.push (new TimeStamped(d)); + } + } + + public Long getDeadline () { + synchronized (m_deadlineHistory) { + + TimeStamped peek = m_deadlineHistory.peek (); + return peek!=null?peek.data:null; + } + } + + public void setTargetWaypoint (String waypoint) { + m_targetWaypoint = waypoint; + } + + public String getTargetWaypoint () { + return m_targetWaypoint; + } + + + public MissionState copy () { + MissionState s = new MissionState (m_model); + s.m_locationHistory = new ArrayDeque<> (m_locationHistory); + s.m_deadlineHistory = new ArrayDeque<> (m_deadlineHistory); + s.m_reconfiguring = m_reconfiguring; + return s; + } + + public boolean isMissionStarted () { + // TODO: CHange this when mission start detection is implemented + return true || !"".equals(getTargetWaypoint ()); + } + + public boolean isReconfiguring() { + return m_reconfiguring; + } + + public void setReconfiguring(boolean r) { + m_reconfiguring = r; + } + + public UtilityPreference getUtilityPreference() { + return m_utilityPreference; + } + + public void setUtilityPreference(UtilityPreference utilityPreference) { + m_utilityPreference = utilityPreference; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionStateLoadCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionStateLoadCmd.java index f16da8051..31491e359 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionStateLoadCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionStateLoadCmd.java @@ -1,58 +1,58 @@ -package org.sa.rainbow.brass.model.p2_cp3.mission; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; - -import java.io.InputStream; - -import static org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE; - -/** - * Created by schmerl on 12/28/2016. - */ -public class MissionStateLoadCmd extends AbstractLoadModelCmd { - private final String m_modelName; - private final InputStream m_stream; - private MissionStateModelInstance m_result; - - public MissionStateLoadCmd (IModelsManager mm, String resource, InputStream is, String source) { - super ("loadMissionState", mm, resource, is, source); - m_modelName = resource; - m_stream = is; - } - - @Override - public IModelInstance getResult () throws IllegalStateException { - return m_result; - } - public ModelReference getModelReference () { - return new ModelReference (m_modelName, MissionStateModelInstance.MISSION_STATE_TYPE); - } - - @Override - protected void subExecute () throws RainbowException { - if (m_stream == null) { - MissionState m = new MissionState (getModelReference ()); - m_result = new MissionStateModelInstance (m, getOriginalSource ()); - doPostExecute (); - } - } - - @Override - protected void subRedo () throws RainbowException { - doPostExecute (); - } - - @Override - protected void subUndo () throws RainbowException { - doPostUndo (); - } - - @Override - protected boolean checkModelValidForCommand (Object o) { - return true; - } -} +package org.sa.rainbow.brass.model.p2_cp3.mission; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; + +import java.io.InputStream; + +import static org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance.INSTRUCTION_GRAPH_TYPE; + +/** + * Created by schmerl on 12/28/2016. + */ +public class MissionStateLoadCmd extends AbstractLoadModelCmd { + private final String m_modelName; + private final InputStream m_stream; + private MissionStateModelInstance m_result; + + public MissionStateLoadCmd (IModelsManager mm, String resource, InputStream is, String source) { + super ("loadMissionState", mm, resource, is, source); + m_modelName = resource; + m_stream = is; + } + + @Override + public IModelInstance getResult () throws IllegalStateException { + return m_result; + } + public ModelReference getModelReference () { + return new ModelReference (m_modelName, MissionStateModelInstance.MISSION_STATE_TYPE); + } + + @Override + protected void subExecute () throws RainbowException { + if (m_stream == null) { + MissionState m = new MissionState (getModelReference ()); + m_result = new MissionStateModelInstance (m, getOriginalSource ()); + doPostExecute (); + } + } + + @Override + protected void subRedo () throws RainbowException { + doPostExecute (); + } + + @Override + protected void subUndo () throws RainbowException { + doPostUndo (); + } + + @Override + protected boolean checkModelValidForCommand (Object o) { + return true; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionStateModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionStateModelInstance.java index ea871f312..34ca46171 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionStateModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/MissionStateModelInstance.java @@ -1,70 +1,70 @@ -package org.sa.rainbow.brass.model.p2_cp3.mission; - -import org.sa.rainbow.core.error.RainbowCopyException; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -/** - * Created by schmerl on 12/27/2016. - */ -public class MissionStateModelInstance implements IModelInstance { - - public static final String MISSION_STATE_TYPE = "MissionState"; - private MissionState m_missionState; - private MissionCommandFactory m_commandFactory; - private String m_source; - - public MissionStateModelInstance (MissionState s, String source) { - setModelInstance (s); - setOriginalSource (source); - } - - @Override - public MissionState getModelInstance () { - return m_missionState; - } - - @Override - public void setModelInstance (MissionState model) { - m_missionState = model; - } - - @Override - public IModelInstance copyModelInstance (String newName) throws RainbowCopyException { - return new MissionStateModelInstance (getModelInstance ().copy (), getOriginalSource ()); - } - - @Override - public String getModelType () { - return MISSION_STATE_TYPE; - } - - @Override - public String getModelName () { - return getModelInstance ().getModelReference ().getModelName (); - } - - @Override - public MissionCommandFactory getCommandFactory () { - if (m_commandFactory == null) { - m_commandFactory = new MissionCommandFactory (this); - } - return m_commandFactory; - } - - @Override - public void setOriginalSource (String source) { - m_source = source; - } - - @Override - public String getOriginalSource () { - return m_source; - } - - @Override - public void dispose () throws RainbowException { - - } -} +package org.sa.rainbow.brass.model.p2_cp3.mission; + +import org.sa.rainbow.core.error.RainbowCopyException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +/** + * Created by schmerl on 12/27/2016. + */ +public class MissionStateModelInstance implements IModelInstance { + + public static final String MISSION_STATE_TYPE = "MissionState"; + private MissionState m_missionState; + private MissionCommandFactory m_commandFactory; + private String m_source; + + public MissionStateModelInstance (MissionState s, String source) { + setModelInstance (s); + setOriginalSource (source); + } + + @Override + public MissionState getModelInstance () { + return m_missionState; + } + + @Override + public void setModelInstance (MissionState model) { + m_missionState = model; + } + + @Override + public IModelInstance copyModelInstance (String newName) throws RainbowCopyException { + return new MissionStateModelInstance (getModelInstance ().copy (), getOriginalSource ()); + } + + @Override + public String getModelType () { + return MISSION_STATE_TYPE; + } + + @Override + public String getModelName () { + return getModelInstance ().getModelReference ().getModelName (); + } + + @Override + public MissionCommandFactory getCommandFactory () throws RainbowException { + if (m_commandFactory == null) { + m_commandFactory = new MissionCommandFactory (this); + } + return m_commandFactory; + } + + @Override + public void setOriginalSource (String source) { + m_source = source; + } + + @Override + public String getOriginalSource () { + return m_source; + } + + @Override + public void dispose () throws RainbowException { + + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SaveMissionCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SaveMissionCmd.java index 3903b119b..26056425a 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SaveMissionCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SaveMissionCmd.java @@ -1,62 +1,62 @@ -package org.sa.rainbow.brass.model.p2_cp3.mission; - -import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel.TimeStamped; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; - -import java.io.OutputStream; -import java.io.PrintStream; - -/** - * Created by schmerl on 12/27/2016. - */ -public class SaveMissionCmd extends AbstractSaveModelCmd { - public SaveMissionCmd (IModelsManager mm, String resource, OutputStream os, String source) { - super ("saveMissionState", mm, resource, os, source); - } - - @Override - public Object getResult () throws IllegalStateException { - return null; - } - - @Override - public ModelReference getModelReference () { - return new ModelReference ("", "MissionState"); - } - - @Override - protected void subExecute () throws RainbowException { - MissionState model = getModelContext ().getModelInstance (); - try (PrintStream ps = new PrintStream (getStream ())) { - for (TimeStamped l : model.m_locationHistory) { - ps.print ("("); - ps.print (l.data.getX ()); - ps.print (","); - ps.print (l.data.getY ()); - ps.print (","); - ps.print(l.data.getHeading().name()); - ps.print (")@"); - ps.print (l.timestamp); - ps.print ("\n"); - } - } - } - - @Override - protected void subRedo () throws RainbowException { - - } - - @Override - protected void subUndo () throws RainbowException { - - } - - @Override - protected boolean checkModelValidForCommand (MissionState missionState) { - return true; - } -} +package org.sa.rainbow.brass.model.p2_cp3.mission; + +import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel.TimeStamped; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; + +import java.io.OutputStream; +import java.io.PrintStream; + +/** + * Created by schmerl on 12/27/2016. + */ +public class SaveMissionCmd extends AbstractSaveModelCmd { + public SaveMissionCmd (IModelsManager mm, String resource, OutputStream os, String source) { + super ("saveMissionState", mm, resource, os, source); + } + + @Override + public Object getResult () throws IllegalStateException { + return null; + } + + @Override + public ModelReference getModelReference () { + return new ModelReference ("", "MissionState"); + } + + @Override + protected void subExecute () throws RainbowException { + MissionState model = getModelContext ().getModelInstance (); + try (PrintStream ps = new PrintStream (getStream ())) { + for (TimeStamped l : model.m_locationHistory) { + ps.print ("("); + ps.print (l.data.getX ()); + ps.print (","); + ps.print (l.data.getY ()); + ps.print (","); + ps.print(l.data.getHeading().name()); + ps.print (")@"); + ps.print (l.timestamp); + ps.print ("\n"); + } + } + } + + @Override + protected void subRedo () throws RainbowException { + + } + + @Override + protected void subUndo () throws RainbowException { + + } + + @Override + protected boolean checkModelValidForCommand (MissionState missionState) { + return true; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetCurrentLocationCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetCurrentLocationCmd.java index 3a12cd7fe..d3caef0b7 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetCurrentLocationCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetCurrentLocationCmd.java @@ -1,58 +1,58 @@ -package org.sa.rainbow.brass.model.p2_cp3.mission; - -import java.util.List; - -import org.sa.rainbow.brass.model.mission.MissionState.Heading; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -/** - * Created by schmerl on 12/27/2016. - */ -public class SetCurrentLocationCmd extends AbstractRainbowModelOperation { - private final double m_x; - private final double m_y; - private double m_w; - private Heading m_heading; - - public SetCurrentLocationCmd (MissionStateModelInstance model, String target, String x, - String y, String w) { - super ("setCurrentLocation", model, target, x, y, w); - m_x = Double.parseDouble (x); - m_y = Double.parseDouble (y); - m_w = Double.parseDouble (w); - } - - @Override - public MissionState.LocationRecording getResult () throws IllegalStateException { - return getModelContext ().getModelInstance ().getCurrentPose (); - } - - @Override - protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setCurrentLocation"); - } - - @Override - protected void subExecute () throws RainbowException { - getModelContext ().getModelInstance ().setCurrentPose (m_x, m_y, m_w); - } - - @Override - protected void subRedo () throws RainbowException { - getModelContext ().getModelInstance ().setCurrentPose (m_x, m_y, m_w); - } - - @Override - protected void subUndo () throws RainbowException { - getModelContext ().getModelInstance ().m_locationHistory.pop (); - } - - @Override - protected boolean checkModelValidForCommand (MissionState missionState) { - return missionState == getModelContext - ().getModelInstance (); - } -} +package org.sa.rainbow.brass.model.p2_cp3.mission; + +import java.util.List; + +import org.sa.rainbow.brass.model.mission.MissionState.Heading; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +/** + * Created by schmerl on 12/27/2016. + */ +public class SetCurrentLocationCmd extends AbstractRainbowModelOperation { + private final double m_x; + private final double m_y; + private double m_w; + private Heading m_heading; + + public SetCurrentLocationCmd (String commandName, MissionStateModelInstance model, String target, String x, + String y, String w) { + super (commandName, model, target, x, y, w); + m_x = Double.parseDouble (x); + m_y = Double.parseDouble (y); + m_w = Double.parseDouble (w); + } + + @Override + public MissionState.LocationRecording getResult () throws IllegalStateException { + return getModelContext ().getModelInstance ().getCurrentPose (); + } + + @Override + protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { + return generateEvents (messageFactory, getName()); + } + + @Override + protected void subExecute () throws RainbowException { + getModelContext ().getModelInstance ().setCurrentPose (m_x, m_y, m_w); + } + + @Override + protected void subRedo () throws RainbowException { + getModelContext ().getModelInstance ().setCurrentPose (m_x, m_y, m_w); + } + + @Override + protected void subUndo () throws RainbowException { + getModelContext ().getModelInstance ().m_locationHistory.pop (); + } + + @Override + protected boolean checkModelValidForCommand (MissionState missionState) { + return missionState == getModelContext + ().getModelInstance (); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetDeadlineCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetDeadlineCmd.java index 35eee5581..d54f0cc5f 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetDeadlineCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetDeadlineCmd.java @@ -11,8 +11,8 @@ public class SetDeadlineCmd extends AbstractRainbowModelOperation getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setDeadline"); + return generateEvents (messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetReconfiguringCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetReconfiguringCmd.java index 213d20f05..9331f06c2 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetReconfiguringCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetReconfiguringCmd.java @@ -1,57 +1,57 @@ -package org.sa.rainbow.brass.model.p2_cp3.mission; - -import java.util.List; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public class SetReconfiguringCmd extends AbstractRainbowModelOperation { - - private boolean m_reconfiguring; - private boolean m_old; - - public SetReconfiguringCmd(MissionStateModelInstance model, String target, String reconfiguring) { - super("setReconfiguring", model, target, reconfiguring); - try { - m_reconfiguring = Boolean.parseBoolean(reconfiguring); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - @Override - public Boolean getResult() throws IllegalStateException { - return m_reconfiguring; - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setReconfiguring"); - - } - - @Override - protected void subExecute() throws RainbowException { - m_old = getModelContext().getModelInstance().isReconfiguring(); - getModelContext().getModelInstance().setReconfiguring(m_reconfiguring); - } - - @Override - protected void subRedo() throws RainbowException { - subExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - getModelContext().getModelInstance().setReconfiguring(m_old); - } - - @Override - protected boolean checkModelValidForCommand(MissionState model) { - return true; - } - -} +package org.sa.rainbow.brass.model.p2_cp3.mission; + +import java.util.List; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class SetReconfiguringCmd extends AbstractRainbowModelOperation { + + private boolean m_reconfiguring; + private boolean m_old; + + public SetReconfiguringCmd(String commandName, MissionStateModelInstance model, String target, String reconfiguring) { + super(commandName, model, target, reconfiguring); + try { + m_reconfiguring = Boolean.parseBoolean(reconfiguring); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + @Override + public Boolean getResult() throws IllegalStateException { + return m_reconfiguring; + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents(messageFactory, getName()); + + } + + @Override + protected void subExecute() throws RainbowException { + m_old = getModelContext().getModelInstance().isReconfiguring(); + getModelContext().getModelInstance().setReconfiguring(m_reconfiguring); + } + + @Override + protected void subRedo() throws RainbowException { + subExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + getModelContext().getModelInstance().setReconfiguring(m_old); + } + + @Override + protected boolean checkModelValidForCommand(MissionState model) { + return true; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetTargetWaypointCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetTargetWaypointCmd.java index e079b8dc3..ab56957b5 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetTargetWaypointCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetTargetWaypointCmd.java @@ -11,8 +11,8 @@ public class SetTargetWaypointCmd extends AbstractRainbowModelOperation getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setTargetWaypoint"); + return generateEvents (messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetUtilityPreferenceCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetUtilityPreferenceCmd.java index 8d6f407d2..ca7e9be57 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetUtilityPreferenceCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/mission/SetUtilityPreferenceCmd.java @@ -1,25 +1,25 @@ -package org.sa.rainbow.brass.model.p2_cp3.mission; - -import org.sa.rainbow.brass.model.AbstractSimpleRainbowModelOperation; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.UtilityPreference; -import org.sa.rainbow.core.error.RainbowException; - -public class SetUtilityPreferenceCmd extends AbstractSimpleRainbowModelOperation { - - private UtilityPreference m_preference; - - public SetUtilityPreferenceCmd(MissionStateModelInstance model, - String target, String preference) { - super("setUtilityPreference", "setUtilityPreference", model, target, preference); - m_preference = UtilityPreference.getValue(preference); - if (m_preference == null) - m_preference = UtilityPreference.valueOf(preference); - } - - @Override - protected void subExecute() throws RainbowException { - getModelContext().getModelInstance().setUtilityPreference(m_preference); - setResult(m_preference); - } - -} +package org.sa.rainbow.brass.model.p2_cp3.mission; + +import org.sa.rainbow.brass.model.AbstractSimpleRainbowModelOperation; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.UtilityPreference; +import org.sa.rainbow.core.error.RainbowException; + +public class SetUtilityPreferenceCmd extends AbstractSimpleRainbowModelOperation { + + private UtilityPreference m_preference; + + public SetUtilityPreferenceCmd(String commandName, MissionStateModelInstance model, + String target, String preference) { + super(commandName, "setUtilityPreference", model, target, preference); + m_preference = UtilityPreference.getValue(preference); + if (m_preference == null) + m_preference = UtilityPreference.valueOf(preference); + } + + @Override + protected void subExecute() throws RainbowException { + getModelContext().getModelInstance().setUtilityPreference(m_preference); + setResult(m_preference); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/ClearModelProblemsCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/ClearModelProblemsCmd.java index 5fce0244e..0bef46559 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/ClearModelProblemsCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/ClearModelProblemsCmd.java @@ -1,21 +1,21 @@ -package org.sa.rainbow.brass.model.p2_cp3.rainbowState; - -import org.sa.rainbow.brass.model.AbstractSimpleRainbowModelOperation; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; - -public class ClearModelProblemsCmd - extends AbstractSimpleRainbowModelOperation { - - public ClearModelProblemsCmd(RainbowStateModelInstance model, - String target, String empty) { - super("clearModelProblems", "clearModelProblems", model, target, empty); - } - - @Override - protected void subExecute() throws RainbowException { - getModelContext().getModelInstance().clearModelProblems(); - setResult(getModelContext().getModelInstance().getProblems().isEmpty()); - } - -} +package org.sa.rainbow.brass.model.p2_cp3.rainbowState; + +import org.sa.rainbow.brass.model.AbstractSimpleRainbowModelOperation; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; + +public class ClearModelProblemsCmd + extends AbstractSimpleRainbowModelOperation { + + public ClearModelProblemsCmd(String commandName, RainbowStateModelInstance model, + String target, String empty) { + super(commandName, "clearModelProblems", model, target, empty); + } + + @Override + protected void subExecute() throws RainbowException { + getModelContext().getModelInstance().clearModelProblems(); + setResult(getModelContext().getModelInstance().getProblems().isEmpty()); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowState.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowState.java index 3b0416d89..7064f69ff 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowState.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowState.java @@ -1,73 +1,73 @@ -package org.sa.rainbow.brass.model.p2_cp3.rainbowState; - -import java.util.EnumSet; - -import org.sa.rainbow.core.models.ModelReference; - -public class RainbowState { - public static enum CP3ModelState { - TOO_DARK, - INSTRUCTION_GRAPH_FAILED, - OUT_OF_BATTERY, - LOW_ON_BATTERY, +package org.sa.rainbow.brass.model.p2_cp3.rainbowState; + +import java.util.EnumSet; + +import org.sa.rainbow.core.models.ModelReference; + +public class RainbowState { + public static enum CP3ModelState { + TOO_DARK, + INSTRUCTION_GRAPH_FAILED, + OUT_OF_BATTERY, + LOW_ON_BATTERY, ARCHITECTURE_ERROR, CONFIGURATION_ERROR, IS_OBSTRUCTED - } - - - - private ModelReference m_model; - private EnumSet m_problems; - private boolean m_planIssued; - public boolean m_waitForIG = true; - - public RainbowState(ModelReference model) { - m_model = model; - m_problems = EnumSet.noneOf(CP3ModelState.class); - } - - synchronized void setModelProblem(CP3ModelState problem) { - m_problems.add(problem); - } - - synchronized void removeModelProblem(CP3ModelState problem) { - m_problems.remove(problem); - } - - synchronized void clearModelProblems() { - m_problems.clear(); - } - - synchronized void setPlanIssued(boolean issued) { - m_planIssued = issued; - } - - synchronized public boolean isPlanIssued() { - return m_planIssued; - } - - public ModelReference getModelReference() { - return m_model; - } - - public synchronized boolean waitForIG() { - return m_waitForIG; - } - - synchronized public RainbowState copy() { - RainbowState rs = new RainbowState(getModelReference()); - rs.m_problems = EnumSet.copyOf(m_problems); - rs.m_planIssued = m_planIssued; - return rs; - } - - public EnumSet getProblems() { - return m_problems; - } - - - - - - -} + } + + + + private ModelReference m_model; + private EnumSet m_problems; + private boolean m_planIssued; + public boolean m_waitForIG = true; + + public RainbowState(ModelReference model) { + m_model = model; + m_problems = EnumSet.noneOf(CP3ModelState.class); + } + + synchronized void setModelProblem(CP3ModelState problem) { + m_problems.add(problem); + } + + synchronized void removeModelProblem(CP3ModelState problem) { + m_problems.remove(problem); + } + + synchronized void clearModelProblems() { + m_problems.clear(); + } + + synchronized void setPlanIssued(boolean issued) { + m_planIssued = issued; + } + + synchronized public boolean isPlanIssued() { + return m_planIssued; + } + + public ModelReference getModelReference() { + return m_model; + } + + public synchronized boolean waitForIG() { + return m_waitForIG; + } + + synchronized public RainbowState copy() { + RainbowState rs = new RainbowState(getModelReference()); + rs.m_problems = EnumSet.copyOf(m_problems); + rs.m_planIssued = m_planIssued; + return rs; + } + + public EnumSet getProblems() { + return m_problems; + } + + + + + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateCommandFactory.java index 8305deab5..ec5c68db2 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateCommandFactory.java @@ -1,53 +1,56 @@ -package org.sa.rainbow.brass.model.p2_cp3.rainbowState; - -import java.io.InputStream; - -import org.sa.rainbow.brass.model.p2_cp3.mission.SetUtilityPreferenceCmd; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class RainbowStateCommandFactory extends ModelCommandFactory{ - public RainbowStateCommandFactory( - RainbowStateModelInstance model) { - super(RainbowStateModelInstance.class, model); - } - - public static RainbowStateLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream - stream, String source) { - return new RainbowStateLoadCmd(mm, modelName, stream, source); - } - - @Override - protected void fillInCommandMap() { - m_commandMap.put("setPlanIssued".toLowerCase(), SetPlanIssuedCmd.class); - m_commandMap.put("setModelProblem".toLowerCase(), SetModelProblemCmd.class); - m_commandMap.put("removeModelProblem".toLowerCase(), RemoveModelProblemCmd.class); - m_commandMap.put("clearModelProblems".toLowerCase(), ClearModelProblemsCmd.class); - } - - @Override - public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { - return null; - } - - public SetPlanIssuedCmd setPlanIssued(boolean issued) { - return new SetPlanIssuedCmd((RainbowStateModelInstance )m_modelInstance, "", Boolean.toString(issued)); - } - - public SetModelProblemCmd setModelProblem(RainbowState.CP3ModelState problem) { - return new SetModelProblemCmd((RainbowStateModelInstance )m_modelInstance, "", problem.name()); - } - - public RemoveModelProblemCmd removeModelProblem(RainbowState.CP3ModelState problem) { - return new RemoveModelProblemCmd((RainbowStateModelInstance )m_modelInstance, "", problem.name()); - } - - public ClearModelProblemsCmd clearModelProblems() { - return new ClearModelProblemsCmd((RainbowStateModelInstance )m_modelInstance, "", ""); - } - - - -} +package org.sa.rainbow.brass.model.p2_cp3.rainbowState; + +import java.io.InputStream; + +import org.sa.rainbow.brass.model.p2_cp3.mission.SetUtilityPreferenceCmd; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class RainbowStateCommandFactory extends ModelCommandFactory{ + private static final String CLEAR_MODEL_PROBLEMS_CMD = "clearModelProblems"; + private static final String REMOVE_MODEL_PROBLEM_CMD = "removeModelProblem"; + private static final String SET_MODEL_PROBLEM_CMD = "setModelProblem"; + private static final String SET_PLAN_ISSUED_CMD = "setPlanIssued"; + + public RainbowStateCommandFactory( + RainbowStateModelInstance model) throws RainbowException { + super(RainbowStateModelInstance.class, model); + } + + @LoadOperation + public static RainbowStateLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream + stream, String source) { + return new RainbowStateLoadCmd(mm, modelName, stream, source); + } + + @Override + public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { + return null; + } + + @Operation(name=SET_PLAN_ISSUED_CMD) + public SetPlanIssuedCmd setPlanIssued(boolean issued) { + return new SetPlanIssuedCmd(SET_PLAN_ISSUED_CMD, (RainbowStateModelInstance )m_modelInstance, "", Boolean.toString(issued)); + } + + @Operation(name=SET_MODEL_PROBLEM_CMD) + public SetModelProblemCmd setModelProblem(RainbowState.CP3ModelState problem) { + return new SetModelProblemCmd(SET_MODEL_PROBLEM_CMD, (RainbowStateModelInstance )m_modelInstance, "", problem.name()); + } + + @Operation(name=REMOVE_MODEL_PROBLEM_CMD) + public RemoveModelProblemCmd removeModelProblem(RainbowState.CP3ModelState problem) { + return new RemoveModelProblemCmd(REMOVE_MODEL_PROBLEM_CMD, (RainbowStateModelInstance )m_modelInstance, "", problem.name()); + } + + @Operation(name=CLEAR_MODEL_PROBLEMS_CMD) + public ClearModelProblemsCmd clearModelProblems() { + return new ClearModelProblemsCmd(CLEAR_MODEL_PROBLEMS_CMD, (RainbowStateModelInstance )m_modelInstance, "", ""); + } + + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateLoadCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateLoadCmd.java index d5006c364..3df09e078 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateLoadCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateLoadCmd.java @@ -1,58 +1,58 @@ -package org.sa.rainbow.brass.model.p2_cp3.rainbowState; - -import java.io.InputStream; - -import org.sa.rainbow.brass.model.p2_cp3.clock.ClockModelInstance; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; - -public class RainbowStateLoadCmd extends AbstractLoadModelCmd { - - private String m_modelName; - private InputStream m_stream; - private RainbowStateModelInstance m_result; - - public RainbowStateLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { - super("loadRainbowState", mm, resource, is, source); - m_modelName = resource; - m_stream = is; - } - - @Override - public IModelInstance getResult() throws IllegalStateException { - return m_result; - } - - @Override - public ModelReference getModelReference() { - return new ModelReference(m_modelName, RainbowStateModelInstance.TYPE); - } - - @Override - protected void subExecute() throws RainbowException { - if (m_stream == null) { - RainbowState rs = new RainbowState(getModelReference()); - m_result = new RainbowStateModelInstance(rs, getOriginalSource()); - doPostExecute(); - } - } - - @Override - protected void subRedo() throws RainbowException { - doPostExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - doPostUndo(); - } - - @Override - protected boolean checkModelValidForCommand(Object model) { - return true; - } - -} +package org.sa.rainbow.brass.model.p2_cp3.rainbowState; + +import java.io.InputStream; + +import org.sa.rainbow.brass.model.p2_cp3.clock.ClockModelInstance; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; + +public class RainbowStateLoadCmd extends AbstractLoadModelCmd { + + private String m_modelName; + private InputStream m_stream; + private RainbowStateModelInstance m_result; + + public RainbowStateLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { + super("loadRainbowState", mm, resource, is, source); + m_modelName = resource; + m_stream = is; + } + + @Override + public IModelInstance getResult() throws IllegalStateException { + return m_result; + } + + @Override + public ModelReference getModelReference() { + return new ModelReference(m_modelName, RainbowStateModelInstance.TYPE); + } + + @Override + protected void subExecute() throws RainbowException { + if (m_stream == null) { + RainbowState rs = new RainbowState(getModelReference()); + m_result = new RainbowStateModelInstance(rs, getOriginalSource()); + doPostExecute(); + } + } + + @Override + protected void subRedo() throws RainbowException { + doPostExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + doPostUndo(); + } + + @Override + protected boolean checkModelValidForCommand(Object model) { + return true; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateModelInstance.java index b563bd62f..b7f426fcf 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RainbowStateModelInstance.java @@ -1,69 +1,69 @@ -package org.sa.rainbow.brass.model.p2_cp3.rainbowState; - -import org.sa.rainbow.core.error.RainbowCopyException; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class RainbowStateModelInstance implements IModelInstance { - - - - public static final String TYPE = "RainbowState"; - private RainbowState m_rainbowState; - private RainbowStateCommandFactory m_commandFactory; - private String m_source; - - public RainbowStateModelInstance(RainbowState rs, String source) { - setModelInstance(rs); - setOriginalSource(source); - } - - @Override - public RainbowState getModelInstance() { - return m_rainbowState; - } - - @Override - public void setModelInstance(RainbowState model) { - m_rainbowState = model; - } - - @Override - public IModelInstance copyModelInstance(String newName) throws RainbowCopyException { - return new RainbowStateModelInstance(m_rainbowState.copy (), getOriginalSource()); - } - - @Override - public String getModelType() { - return TYPE; - } - - @Override - public String getModelName() { - return getModelInstance().getModelReference().getModelName (); - } - - @Override - public RainbowStateCommandFactory getCommandFactory() { - if (m_commandFactory == null) - m_commandFactory = new RainbowStateCommandFactory(this); - return m_commandFactory; - } - - @Override - public void setOriginalSource(String source) { - m_source = source; - } - - @Override - public String getOriginalSource() { - return m_source; - } - - @Override - public void dispose() throws RainbowException { - - } - -} +package org.sa.rainbow.brass.model.p2_cp3.rainbowState; + +import org.sa.rainbow.core.error.RainbowCopyException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class RainbowStateModelInstance implements IModelInstance { + + + + public static final String TYPE = "RainbowState"; + private RainbowState m_rainbowState; + private RainbowStateCommandFactory m_commandFactory; + private String m_source; + + public RainbowStateModelInstance(RainbowState rs, String source) { + setModelInstance(rs); + setOriginalSource(source); + } + + @Override + public RainbowState getModelInstance() { + return m_rainbowState; + } + + @Override + public void setModelInstance(RainbowState model) { + m_rainbowState = model; + } + + @Override + public IModelInstance copyModelInstance(String newName) throws RainbowCopyException { + return new RainbowStateModelInstance(m_rainbowState.copy (), getOriginalSource()); + } + + @Override + public String getModelType() { + return TYPE; + } + + @Override + public String getModelName() { + return getModelInstance().getModelReference().getModelName (); + } + + @Override + public RainbowStateCommandFactory getCommandFactory() throws RainbowException { + if (m_commandFactory == null) + m_commandFactory = new RainbowStateCommandFactory(this); + return m_commandFactory; + } + + @Override + public void setOriginalSource(String source) { + m_source = source; + } + + @Override + public String getOriginalSource() { + return m_source; + } + + @Override + public void dispose() throws RainbowException { + + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RemoveModelProblemCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RemoveModelProblemCmd.java index a33bdea35..f2a087eab 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RemoveModelProblemCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/RemoveModelProblemCmd.java @@ -1,28 +1,28 @@ -package org.sa.rainbow.brass.model.p2_cp3.rainbowState; - -import java.util.EnumSet; - -import org.sa.rainbow.brass.model.AbstractSimpleRainbowModelOperation; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; - -public class RemoveModelProblemCmd - extends AbstractSimpleRainbowModelOperation, RainbowState> { - - private CP3ModelState m_problem; - - public RemoveModelProblemCmd(RainbowStateModelInstance model, - String target, String problem) { - super("removeModelProblem", "removeModelProblem", model, target, problem); - m_problem = CP3ModelState.valueOf(problem); - } - - @Override - protected void subExecute() throws RainbowException { - getModelContext().getModelInstance().removeModelProblem(m_problem); - setResult(EnumSet.copyOf(getModelContext().getModelInstance().getProblems())); - - } - -} +package org.sa.rainbow.brass.model.p2_cp3.rainbowState; + +import java.util.EnumSet; + +import org.sa.rainbow.brass.model.AbstractSimpleRainbowModelOperation; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; + +public class RemoveModelProblemCmd + extends AbstractSimpleRainbowModelOperation, RainbowState> { + + private CP3ModelState m_problem; + + public RemoveModelProblemCmd(String commandName, RainbowStateModelInstance model, + String target, String problem) { + super(commandName, "removeModelProblem", model, target, problem); + m_problem = CP3ModelState.valueOf(problem); + } + + @Override + protected void subExecute() throws RainbowException { + getModelContext().getModelInstance().removeModelProblem(m_problem); + setResult(EnumSet.copyOf(getModelContext().getModelInstance().getProblems())); + + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/SetModelProblemCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/SetModelProblemCmd.java index 4c6af1ed0..6c599cf58 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/SetModelProblemCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/SetModelProblemCmd.java @@ -1,27 +1,27 @@ -package org.sa.rainbow.brass.model.p2_cp3.rainbowState; - -import java.util.EnumSet; - -import org.sa.rainbow.brass.model.AbstractSimpleRainbowModelOperation; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotStateModelInstance; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; - -public class SetModelProblemCmd extends AbstractSimpleRainbowModelOperation, RainbowState> { - - private CP3ModelState m_problem; - - public SetModelProblemCmd(RainbowStateModelInstance model, String target, - String problem) { - super("setModelProblem", "setModelProblem", model, target, problem); - m_problem = CP3ModelState.valueOf(problem); - } - - @Override - protected void subExecute() throws RainbowException { - getModelContext().getModelInstance().setModelProblem(m_problem); - setResult(EnumSet.copyOf(getModelContext().getModelInstance().getProblems())); - } - -} +package org.sa.rainbow.brass.model.p2_cp3.rainbowState; + +import java.util.EnumSet; + +import org.sa.rainbow.brass.model.AbstractSimpleRainbowModelOperation; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotStateModelInstance; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; + +public class SetModelProblemCmd extends AbstractSimpleRainbowModelOperation, RainbowState> { + + private CP3ModelState m_problem; + + public SetModelProblemCmd(String commandName, RainbowStateModelInstance model, String target, + String problem) { + super(commandName, "setModelProblem", model, target, problem); + m_problem = CP3ModelState.valueOf(problem); + } + + @Override + protected void subExecute() throws RainbowException { + getModelContext().getModelInstance().setModelProblem(m_problem); + setResult(EnumSet.copyOf(getModelContext().getModelInstance().getProblems())); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/SetPlanIssuedCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/SetPlanIssuedCmd.java index 28d6c48c0..af14faee0 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/SetPlanIssuedCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/rainbowState/SetPlanIssuedCmd.java @@ -1,31 +1,31 @@ -package org.sa.rainbow.brass.model.p2_cp3.rainbowState; - -import java.util.List; - -import org.sa.rainbow.brass.model.AbstractSimpleRainbowModelOperation; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public class SetPlanIssuedCmd extends AbstractSimpleRainbowModelOperation { - - - private boolean m_issued; - - public SetPlanIssuedCmd(RainbowStateModelInstance model, String target, - String issued) { - super("setPlanIssued", "setPlanIssued", model, target, issued); - m_issued = Boolean.parseBoolean(issued); - } - - @Override - protected void subExecute() throws RainbowException { - getModelContext().getModelInstance().setPlanIssued(m_issued); - setResult(getModelContext().getModelInstance().isPlanIssued()); - } - - - -} +package org.sa.rainbow.brass.model.p2_cp3.rainbowState; + +import java.util.List; + +import org.sa.rainbow.brass.model.AbstractSimpleRainbowModelOperation; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class SetPlanIssuedCmd extends AbstractSimpleRainbowModelOperation { + + + private boolean m_issued; + + public SetPlanIssuedCmd(String commandName, RainbowStateModelInstance model, String target, + String issued) { + super(commandName, "setPlanIssued", model, target, issued); + m_issued = Boolean.parseBoolean(issued); + } + + @Override + protected void subExecute() throws RainbowException { + getModelContext().getModelInstance().setPlanIssued(m_issued); + setResult(getModelContext().getModelInstance().isPlanIssued()); + } + + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotState.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotState.java index 0aac69b33..b64b089d6 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotState.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotState.java @@ -1,163 +1,163 @@ -package org.sa.rainbow.brass.model.p2_cp3.robot; - -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.EnumSet; - -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.core.models.ModelReference; - -public class CP3RobotState extends RobotState { - - public static enum Sensors {KINECT, CAMERA, LIDAR, HEADLAMP; - public static Sensors valueOfIgnoreCase(String sensor) { - return valueOf(sensor.toUpperCase()); - } - } - - - Deque>> m_sensorHistory = new ArrayDeque<>(); - Deque>> m_sensorFailedHistory = new ArrayDeque<>(); - Deque> m_bumpState = new ArrayDeque<> (); - Deque> m_lightingHistory = new ArrayDeque<>(); - private volatile boolean m_everBumped = false;; - - - public CP3RobotState(ModelReference model) { - super(model); - setBumped(false); - - } - - - - public void setBumped(boolean bump) { - synchronized(m_bumpState) { - m_bumpState.push(new TimeStamped(bump)); - if (bump) m_everBumped = true; - } - } - - - public boolean everBumped() { - synchronized(m_bumpState) { - return m_everBumped; - } - } - - - public boolean bumpState() throws IllegalStateException { - synchronized(m_bumpState) { - TimeStamped peek = m_bumpState.peek(); - return peek.data; - } - } - - - public void setSensor(Sensors sensor, boolean on) { - synchronized (m_sensorHistory) { - TimeStamped> peek = m_sensorHistory.peek(); - - EnumSet currentState = peek!=null?peek.data:EnumSet.noneOf(Sensors.class); - EnumSet nextState = EnumSet.copyOf(currentState); - if (on && !currentState.contains(sensor)) { - nextState.add(sensor); - m_sensorHistory.push(new TimeStamped>(nextState)); - } - else if (!on && currentState.contains(sensor)) { - nextState.remove(sensor); - m_sensorHistory.push(new TimeStamped>(nextState)); - } - } - } - - public void setSensorFailed(Sensors sensor) { - synchronized (m_sensorFailedHistory) { - TimeStamped> peek = m_sensorFailedHistory.peek(); - EnumSet currentState = peek!=null?peek.data:EnumSet.noneOf(Sensors.class); - EnumSet nextState = EnumSet.copyOf(currentState); - if (!currentState.contains(sensor)) { - nextState.add(sensor); - m_sensorFailedHistory.push(new TimeStamped>(nextState)); - } - } - setSensor(sensor, false); - } - - public EnumSet getAvailableSensors() throws IllegalStateException { - synchronized (m_sensorFailedHistory) { - TimeStamped> peek = m_sensorFailedHistory.peek(); - EnumSet currentState = peek!=null?peek.data:EnumSet.noneOf(Sensors.class); - EnumSet available = EnumSet.allOf(Sensors.class); -// available.remove(Sensors.HEADLAMP); - available.removeAll(currentState); - return available; - } - } - - public EnumSet getFailedSensors() { - synchronized (m_sensorFailedHistory) { - TimeStamped> peek = m_sensorFailedHistory.peek(); - return peek != null?peek.data:EnumSet.noneOf(Sensors.class); - } - } - - public EnumSet getSensors() throws IllegalStateException { - synchronized(m_sensorHistory) { - TimeStamped> peek = m_sensorHistory.peek(); - return peek != null?EnumSet.copyOf(peek.data):EnumSet.noneOf(Sensors.class); - } - } - - - public boolean isKinectOn() throws IllegalStateException { - return getSensors().contains(Sensors.KINECT); - } - - - public boolean isLidarOn() throws IllegalStateException { - return getSensors().contains(Sensors.LIDAR); - } - - - public boolean isCameraOn() throws IllegalStateException { - return getSensors().contains(Sensors.CAMERA); - } - - - public boolean isHeadlampOn() throws IllegalStateException { - return getSensors().contains(Sensors.HEADLAMP); - } - - public void setIllumination(double ill) { - synchronized (m_lightingHistory) { - m_lightingHistory.push(new TimeStamped(ill)); - - } - } - - public double getIllumination() throws IllegalStateException { - synchronized (m_lightingHistory) { - TimeStamped peek = m_lightingHistory.peek(); - if (peek == null) throw new IllegalStateException ("No value for illumination has been set"); - return peek.data; - } - } - - @Override - public CP3RobotState copy() { - CP3RobotState c = new CP3RobotState(getModelReference()); - this.copyInto(c); - return c; - } - - @Override - protected void copyInto(RobotState r) { - super.copyInto(r); - CP3RobotState c = (CP3RobotState )r; - c.m_lightingHistory.addAll (m_lightingHistory); - c.m_sensorHistory.addAll(m_sensorHistory); - c.m_bumpState.addAll(m_bumpState); - } - -} +package org.sa.rainbow.brass.model.p2_cp3.robot; + +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.EnumSet; + +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.core.models.ModelReference; + +public class CP3RobotState extends RobotState { + + public static enum Sensors {KINECT, CAMERA, LIDAR, HEADLAMP; + public static Sensors valueOfIgnoreCase(String sensor) { + return valueOf(sensor.toUpperCase()); + } + } + + + Deque>> m_sensorHistory = new ArrayDeque<>(); + Deque>> m_sensorFailedHistory = new ArrayDeque<>(); + Deque> m_bumpState = new ArrayDeque<> (); + Deque> m_lightingHistory = new ArrayDeque<>(); + private volatile boolean m_everBumped = false;; + + + public CP3RobotState(ModelReference model) { + super(model); + setBumped(false); + + } + + + + public void setBumped(boolean bump) { + synchronized(m_bumpState) { + m_bumpState.push(new TimeStamped(bump)); + if (bump) m_everBumped = true; + } + } + + + public boolean everBumped() { + synchronized(m_bumpState) { + return m_everBumped; + } + } + + + public boolean bumpState() throws IllegalStateException { + synchronized(m_bumpState) { + TimeStamped peek = m_bumpState.peek(); + return peek.data; + } + } + + + public void setSensor(Sensors sensor, boolean on) { + synchronized (m_sensorHistory) { + TimeStamped> peek = m_sensorHistory.peek(); + + EnumSet currentState = peek!=null?peek.data:EnumSet.noneOf(Sensors.class); + EnumSet nextState = EnumSet.copyOf(currentState); + if (on && !currentState.contains(sensor)) { + nextState.add(sensor); + m_sensorHistory.push(new TimeStamped>(nextState)); + } + else if (!on && currentState.contains(sensor)) { + nextState.remove(sensor); + m_sensorHistory.push(new TimeStamped>(nextState)); + } + } + } + + public void setSensorFailed(Sensors sensor) { + synchronized (m_sensorFailedHistory) { + TimeStamped> peek = m_sensorFailedHistory.peek(); + EnumSet currentState = peek!=null?peek.data:EnumSet.noneOf(Sensors.class); + EnumSet nextState = EnumSet.copyOf(currentState); + if (!currentState.contains(sensor)) { + nextState.add(sensor); + m_sensorFailedHistory.push(new TimeStamped>(nextState)); + } + } + setSensor(sensor, false); + } + + public EnumSet getAvailableSensors() throws IllegalStateException { + synchronized (m_sensorFailedHistory) { + TimeStamped> peek = m_sensorFailedHistory.peek(); + EnumSet currentState = peek!=null?peek.data:EnumSet.noneOf(Sensors.class); + EnumSet available = EnumSet.allOf(Sensors.class); +// available.remove(Sensors.HEADLAMP); + available.removeAll(currentState); + return available; + } + } + + public EnumSet getFailedSensors() { + synchronized (m_sensorFailedHistory) { + TimeStamped> peek = m_sensorFailedHistory.peek(); + return peek != null?peek.data:EnumSet.noneOf(Sensors.class); + } + } + + public EnumSet getSensors() throws IllegalStateException { + synchronized(m_sensorHistory) { + TimeStamped> peek = m_sensorHistory.peek(); + return peek != null?EnumSet.copyOf(peek.data):EnumSet.noneOf(Sensors.class); + } + } + + + public boolean isKinectOn() throws IllegalStateException { + return getSensors().contains(Sensors.KINECT); + } + + + public boolean isLidarOn() throws IllegalStateException { + return getSensors().contains(Sensors.LIDAR); + } + + + public boolean isCameraOn() throws IllegalStateException { + return getSensors().contains(Sensors.CAMERA); + } + + + public boolean isHeadlampOn() throws IllegalStateException { + return getSensors().contains(Sensors.HEADLAMP); + } + + public void setIllumination(double ill) { + synchronized (m_lightingHistory) { + m_lightingHistory.push(new TimeStamped(ill)); + + } + } + + public double getIllumination() throws IllegalStateException { + synchronized (m_lightingHistory) { + TimeStamped peek = m_lightingHistory.peek(); + if (peek == null) throw new IllegalStateException ("No value for illumination has been set"); + return peek.data; + } + } + + @Override + public CP3RobotState copy() { + CP3RobotState c = new CP3RobotState(getModelReference()); + this.copyInto(c); + return c; + } + + @Override + protected void copyInto(RobotState r) { + super.copyInto(r); + CP3RobotState c = (CP3RobotState )r; + c.m_lightingHistory.addAll (m_lightingHistory); + c.m_sensorHistory.addAll(m_sensorHistory); + c.m_bumpState.addAll(m_bumpState); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateCommandFactory.java index c2f934797..1350f1fa1 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateCommandFactory.java @@ -1,61 +1,63 @@ -package org.sa.rainbow.brass.model.p2_cp3.robot; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.RobotStateCommandFactory; -import org.sa.rainbow.brass.model.robot.RobotStateLoadCmd; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; - -public class CP3RobotStateCommandFactory extends RobotStateCommandFactory { - - - public static CP3RobotStateLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream stream, String source) { - return new CP3RobotStateLoadCmd(mm, modelName, stream, source); - } - - public CP3RobotStateCommandFactory(CP3RobotStateModelInstance model) { - super(CP3RobotStateModelInstance.class, model); - } - - - @Override - public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { - try (FileOutputStream os = new FileOutputStream(location)) { - return new SaveCP3RobotStateCmd(null, location, os, m_modelInstance.getOriginalSource()); - } catch (IOException e) { - return null; - } - } - @Override - protected void fillInCommandMap() { - super.fillInCommandMap(); - m_commandMap.put("setBumped".toLowerCase(), SetBumpedCmd.class); - m_commandMap.put("setSensor".toLowerCase(), SetSensorCmd.class); - m_commandMap.put("setSensorFailed".toLowerCase(), SetSensorFailedCmd.class); - m_commandMap.put("setLighting".toLowerCase(), SetLightingCmd.class); - - } - - public SetBumpedCmd setBumpedCmd(boolean bumped) { - return new SetBumpedCmd((CP3RobotStateModelInstance )m_modelInstance, "", Boolean.toString(bumped)); - } - - public SetSensorCmd setSensorCmd(Sensors s, boolean on) { - return new SetSensorCmd((CP3RobotStateModelInstance )m_modelInstance, "", s.name(), Boolean.toString(on)); - } - - public SetLightingCmd setLightingCmd(double lighting) { - return new SetLightingCmd((CP3RobotStateModelInstance )m_modelInstance, "", Double.toString(lighting)); - } - - public SetSensorFailedCmd sesnSensorFailedCmd(Sensors sensor) { - return new SetSensorFailedCmd((CP3RobotStateModelInstance )m_modelInstance, sensor.name(), ""); - } -} +package org.sa.rainbow.brass.model.p2_cp3.robot; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.RobotStateCommandFactory; +import org.sa.rainbow.brass.model.robot.RobotStateLoadCmd; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; + +public class CP3RobotStateCommandFactory extends RobotStateCommandFactory { + + + private static final String SET_LIGHTING_CMD = "setLighting"; + private static final String SET_SENSOR_FAILED_CMD = "setSensorFailed"; + private static final String SET_SENSOR_CMD = "setSensor"; + private static final String SET_BUMPED_CMD = "setBumped"; + + @LoadOperation + public static CP3RobotStateLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream stream, String source) { + return new CP3RobotStateLoadCmd(mm, modelName, stream, source); + } + + public CP3RobotStateCommandFactory(CP3RobotStateModelInstance model) throws RainbowException { + super(CP3RobotStateModelInstance.class, model); + } + + + @Override + public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { + try (FileOutputStream os = new FileOutputStream(location)) { + return new SaveCP3RobotStateCmd(null, location, os, m_modelInstance.getOriginalSource()); + } catch (IOException e) { + return null; + } + } + + @Operation(name=SET_BUMPED_CMD) + public SetBumpedCmd setBumpedCmd(boolean bumped) { + return new SetBumpedCmd(SET_BUMPED_CMD, (CP3RobotStateModelInstance )m_modelInstance, "", Boolean.toString(bumped)); + } + + @Operation(name=SET_SENSOR_CMD) + public SetSensorCmd setSensorCmd(Sensors s, boolean on) { + return new SetSensorCmd(SET_SENSOR_CMD, (CP3RobotStateModelInstance )m_modelInstance, "", s.name(), Boolean.toString(on)); + } + + @Operation(name=SET_LIGHTING_CMD) + public SetLightingCmd setLightingCmd(double lighting) { + return new SetLightingCmd(SET_LIGHTING_CMD, (CP3RobotStateModelInstance )m_modelInstance, "", Double.toString(lighting)); + } + + @Operation(name=SET_SENSOR_FAILED_CMD) + public SetSensorFailedCmd sesnSensorFailedCmd(Sensors sensor) { + return new SetSensorFailedCmd(SET_SENSOR_FAILED_CMD, (CP3RobotStateModelInstance )m_modelInstance, sensor.name(), ""); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateLoadCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateLoadCmd.java index 26baeeb2c..291030df1 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateLoadCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateLoadCmd.java @@ -1,24 +1,24 @@ -package org.sa.rainbow.brass.model.p2_cp3.robot; - -import java.io.InputStream; - -import org.sa.rainbow.brass.model.robot.RobotStateLoadCmd; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelsManager; - -public class CP3RobotStateLoadCmd extends RobotStateLoadCmd { - - public CP3RobotStateLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { - super(mm, resource, is, source); - } - - @Override - protected void subExecute() throws RainbowException { - if (m_stream == null) { - CP3RobotState m = new CP3RobotState(getModelReference()); - m_result = new CP3RobotStateModelInstance(m, getOriginalSource()); - doPostExecute(); - } - } - -} +package org.sa.rainbow.brass.model.p2_cp3.robot; + +import java.io.InputStream; + +import org.sa.rainbow.brass.model.robot.RobotStateLoadCmd; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelsManager; + +public class CP3RobotStateLoadCmd extends RobotStateLoadCmd { + + public CP3RobotStateLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { + super(mm, resource, is, source); + } + + @Override + protected void subExecute() throws RainbowException { + if (m_stream == null) { + CP3RobotState m = new CP3RobotState(getModelReference()); + m_result = new CP3RobotStateModelInstance(m, getOriginalSource()); + doPostExecute(); + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateModelInstance.java index 41746768d..a1137efe6 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/CP3RobotStateModelInstance.java @@ -1,27 +1,28 @@ -package org.sa.rainbow.brass.model.p2_cp3.robot; - -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.RobotStateCommandFactory; -import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class CP3RobotStateModelInstance extends RobotStateModelInstance { - - private CP3RobotStateCommandFactory m_commandFactory; - - public CP3RobotStateModelInstance(CP3RobotState r, String source) { - super(r, source); - } - - @Override - public CP3RobotState getModelInstance() { - return (CP3RobotState) super.getModelInstance(); - } - - @Override - public ModelCommandFactory getCommandFactory() { - if (m_commandFactory == null) - m_commandFactory = new CP3RobotStateCommandFactory(this); - return m_commandFactory; - } -} +package org.sa.rainbow.brass.model.p2_cp3.robot; + +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.RobotStateCommandFactory; +import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class CP3RobotStateModelInstance extends RobotStateModelInstance { + + private CP3RobotStateCommandFactory m_commandFactory; + + public CP3RobotStateModelInstance(CP3RobotState r, String source) { + super(r, source); + } + + @Override + public CP3RobotState getModelInstance() { + return (CP3RobotState) super.getModelInstance(); + } + + @Override + public ModelCommandFactory getCommandFactory() throws RainbowException { + if (m_commandFactory == null) + m_commandFactory = new CP3RobotStateCommandFactory(this); + return m_commandFactory; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SaveCP3RobotStateCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SaveCP3RobotStateCmd.java index ec97f9801..a51ea8943 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SaveCP3RobotStateCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SaveCP3RobotStateCmd.java @@ -1,53 +1,53 @@ -package org.sa.rainbow.brass.model.p2_cp3.robot; - -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.EnumSet; -import java.util.Iterator; - -import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel.TimeStamped; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.SaveRobotStateCmd; -import org.sa.rainbow.core.models.IModelsManager; - -public class SaveCP3RobotStateCmd extends SaveRobotStateCmd { - - public SaveCP3RobotStateCmd(IModelsManager mm, String resource, OutputStream os, String source) { - super(mm, resource, os, source); - } - - @Override - protected void insertRobotState(PrintStream ps, RobotState model) { - super.insertRobotState(ps, model); - if (model instanceof CP3RobotState) { - CP3RobotState cp3 = (CP3RobotState )model; - ps.print(" bumpHistory : [\n"); - for (Iterator> iterator = cp3.m_bumpState.iterator(); iterator.hasNext();) { - TimeStamped entry = iterator.next(); - ps.print("{timestamp: " + entry.timestamp + ", bumped : " + entry.data + "}"); - if (iterator.hasNext()) ps.print(", "); - } - ps.print("]"); - - ps.print(" sensorHistory : [\n"); - for (Iterator>> iterator = cp3.m_sensorHistory.iterator(); iterator.hasNext();) { - TimeStamped> entry = iterator.next(); - ps.print("{timestamp: " + entry.timestamp + ", sensors : [" ); - EnumSet data = entry.data; - for (Iterator iterator2 = data.iterator(); iterator2.hasNext();) { - Sensors sensors = (Sensors) iterator2.next(); - ps.print(sensors.name()); - if (iterator2.hasNext()) ps.print(", "); - } - ps.print("]}"); - if (iterator.hasNext()) ps.print(", "); - } - ps.print("]"); - } - - } - -} +package org.sa.rainbow.brass.model.p2_cp3.robot; + +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.EnumSet; +import java.util.Iterator; + +import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel.TimeStamped; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.SaveRobotStateCmd; +import org.sa.rainbow.core.models.IModelsManager; + +public class SaveCP3RobotStateCmd extends SaveRobotStateCmd { + + public SaveCP3RobotStateCmd(IModelsManager mm, String resource, OutputStream os, String source) { + super(mm, resource, os, source); + } + + @Override + protected void insertRobotState(PrintStream ps, RobotState model) { + super.insertRobotState(ps, model); + if (model instanceof CP3RobotState) { + CP3RobotState cp3 = (CP3RobotState )model; + ps.print(" bumpHistory : [\n"); + for (Iterator> iterator = cp3.m_bumpState.iterator(); iterator.hasNext();) { + TimeStamped entry = iterator.next(); + ps.print("{timestamp: " + entry.timestamp + ", bumped : " + entry.data + "}"); + if (iterator.hasNext()) ps.print(", "); + } + ps.print("]"); + + ps.print(" sensorHistory : [\n"); + for (Iterator>> iterator = cp3.m_sensorHistory.iterator(); iterator.hasNext();) { + TimeStamped> entry = iterator.next(); + ps.print("{timestamp: " + entry.timestamp + ", sensors : [" ); + EnumSet data = entry.data; + for (Iterator iterator2 = data.iterator(); iterator2.hasNext();) { + Sensors sensors = (Sensors) iterator2.next(); + ps.print(sensors.name()); + if (iterator2.hasNext()) ps.print(", "); + } + ps.print("]}"); + if (iterator.hasNext()) ps.print(", "); + } + ps.print("]"); + } + + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetBumpedCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetBumpedCmd.java index fc77195ba..be61db4da 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetBumpedCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetBumpedCmd.java @@ -1,58 +1,58 @@ -package org.sa.rainbow.brass.model.p2_cp3.robot; - -import java.util.List; - -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; -/** - * This is a little tricky. Because of the way generics are set up, we can't - * use CP3RobotState directly, and so therefore we need to use use RobotState. - * This means we need to cast to CP3RobotState everywhere. The alternative is to - * duplicate the RobotState commands rather than reuse through inheritence. C'est la vie. - * - * @author schmerl - * - */ -public class SetBumpedCmd extends AbstractRainbowModelOperation { - - private boolean m_bumped; - - public SetBumpedCmd(CP3RobotStateModelInstance model, String target, String bumped) { - super("setBumped", model, target, bumped); - m_bumped = Boolean.getBoolean(bumped); - } - - @Override - public Boolean getResult() throws IllegalStateException { - return ((CP3RobotState )getModelContext().getModelInstance()).bumpState(); - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setBumped"); - } - - @Override - protected void subExecute() throws RainbowException { - ((CP3RobotState )getModelContext().getModelInstance()).setBumped(m_bumped); - } - - @Override - protected void subRedo() throws RainbowException { - subExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - - } - - @Override - protected boolean checkModelValidForCommand(RobotState model) { - return model == getModelContext().getModelInstance(); - } - -} +package org.sa.rainbow.brass.model.p2_cp3.robot; + +import java.util.List; + +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; +/** + * This is a little tricky. Because of the way generics are set up, we can't + * use CP3RobotState directly, and so therefore we need to use use RobotState. + * This means we need to cast to CP3RobotState everywhere. The alternative is to + * duplicate the RobotState commands rather than reuse through inheritence. C'est la vie. + * + * @author schmerl + * + */ +public class SetBumpedCmd extends AbstractRainbowModelOperation { + + private boolean m_bumped; + + public SetBumpedCmd(String commandName, CP3RobotStateModelInstance model, String target, String bumped) { + super(commandName, model, target, bumped); + m_bumped = Boolean.getBoolean(bumped); + } + + @Override + public Boolean getResult() throws IllegalStateException { + return ((CP3RobotState )getModelContext().getModelInstance()).bumpState(); + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents(messageFactory, getName()); + } + + @Override + protected void subExecute() throws RainbowException { + ((CP3RobotState )getModelContext().getModelInstance()).setBumped(m_bumped); + } + + @Override + protected void subRedo() throws RainbowException { + subExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + + } + + @Override + protected boolean checkModelValidForCommand(RobotState model) { + return model == getModelContext().getModelInstance(); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetLightingCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetLightingCmd.java index fec68929a..ac2355027 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetLightingCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetLightingCmd.java @@ -1,59 +1,59 @@ -package org.sa.rainbow.brass.model.p2_cp3.robot; - -import java.util.List; - -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; -/** - * This is a little tricky. Because of the way generics are set up, we can't - * use CP3RobotState directly, and so therefore we need to use use RobotState. - * This means we need to cast to CP3RobotState everywhere. The alternative is to - * duplicate the RobotState commands rather than reuse through inheritence. C'est la vie. - * - * @author schmerl - * - */ -public class SetLightingCmd extends AbstractRainbowModelOperation { - - private double m_lighting; - - public SetLightingCmd(CP3RobotStateModelInstance model, String target, String lighting) { - super("setLighting", model, target, lighting); - m_lighting = Double.valueOf(lighting); - } - - @Override - public Double getResult() throws IllegalStateException { - return ((CP3RobotState )getModelContext().getModelInstance()).getIllumination(); - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setLighting"); - } - - @Override - protected void subExecute() throws RainbowException { - ((CP3RobotState )getModelContext().getModelInstance()).setIllumination(m_lighting); - } - - @Override - protected void subRedo() throws RainbowException { - subExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - - } - - @Override - protected boolean checkModelValidForCommand(RobotState model) { - return model == getModelContext().getModelInstance(); - } - -} +package org.sa.rainbow.brass.model.p2_cp3.robot; + +import java.util.List; + +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; +/** + * This is a little tricky. Because of the way generics are set up, we can't + * use CP3RobotState directly, and so therefore we need to use use RobotState. + * This means we need to cast to CP3RobotState everywhere. The alternative is to + * duplicate the RobotState commands rather than reuse through inheritence. C'est la vie. + * + * @author schmerl + * + */ +public class SetLightingCmd extends AbstractRainbowModelOperation { + + private double m_lighting; + + public SetLightingCmd(String commandName, CP3RobotStateModelInstance model, String target, String lighting) { + super(commandName, model, target, lighting); + m_lighting = Double.valueOf(lighting); + } + + @Override + public Double getResult() throws IllegalStateException { + return ((CP3RobotState )getModelContext().getModelInstance()).getIllumination(); + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents(messageFactory, getName()); + } + + @Override + protected void subExecute() throws RainbowException { + ((CP3RobotState )getModelContext().getModelInstance()).setIllumination(m_lighting); + } + + @Override + protected void subRedo() throws RainbowException { + subExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + + } + + @Override + protected boolean checkModelValidForCommand(RobotState model) { + return model == getModelContext().getModelInstance(); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetSensorCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetSensorCmd.java index 3ce076d42..b643c24e1 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetSensorCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetSensorCmd.java @@ -1,55 +1,55 @@ -package org.sa.rainbow.brass.model.p2_cp3.robot; - -import java.util.EnumSet; -import java.util.List; - -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public class SetSensorCmd extends AbstractRainbowModelOperation, RobotState> { - - private Boolean m_on; - private Sensors m_sensor; - - public SetSensorCmd(CP3RobotStateModelInstance model, String target, String sensor, String on) { - super("setSensor", model, target, sensor, on); - m_sensor = Sensors.valueOf(sensor); - m_on = Boolean.valueOf(on); - } - - @Override - public EnumSet getResult() throws IllegalStateException { - return ((CP3RobotState) getModelContext().getModelInstance()).getSensors(); - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setSensor"); - } - - @Override - protected void subExecute() throws RainbowException { - ((CP3RobotState) getModelContext().getModelInstance()).setSensor(m_sensor, m_on); - } - - @Override - protected void subRedo() throws RainbowException { - subExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - - } - - @Override - protected boolean checkModelValidForCommand(RobotState model) { - return model == getModelContext().getModelInstance(); - } - -} +package org.sa.rainbow.brass.model.p2_cp3.robot; + +import java.util.EnumSet; +import java.util.List; + +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class SetSensorCmd extends AbstractRainbowModelOperation, RobotState> { + + private Boolean m_on; + private Sensors m_sensor; + + public SetSensorCmd(String commandName, CP3RobotStateModelInstance model, String target, String sensor, String on) { + super(commandName, model, target, sensor, on); + m_sensor = Sensors.valueOf(sensor); + m_on = Boolean.valueOf(on); + } + + @Override + public EnumSet getResult() throws IllegalStateException { + return ((CP3RobotState) getModelContext().getModelInstance()).getSensors(); + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents(messageFactory, getName()); + } + + @Override + protected void subExecute() throws RainbowException { + ((CP3RobotState) getModelContext().getModelInstance()).setSensor(m_sensor, m_on); + } + + @Override + protected void subRedo() throws RainbowException { + subExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + + } + + @Override + protected boolean checkModelValidForCommand(RobotState model) { + return model == getModelContext().getModelInstance(); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetSensorFailedCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetSensorFailedCmd.java index 5646351e2..e59805cf8 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetSensorFailedCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/p2_cp3/robot/SetSensorFailedCmd.java @@ -1,51 +1,51 @@ -package org.sa.rainbow.brass.model.p2_cp3.robot; - -import java.util.List; - -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public class SetSensorFailedCmd extends AbstractRainbowModelOperation { - - private Sensors m_sensor; - - public SetSensorFailedCmd(CP3RobotStateModelInstance model, String target, String param) { - super("setSensorFailed", model, target, param); - m_sensor = Sensors.valueOf(param); - } - - @Override - public Boolean getResult() throws IllegalStateException { - return true; - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setSensorFailed"); - } - - @Override - protected void subExecute() throws RainbowException { - ((CP3RobotState) getModelContext().getModelInstance()).setSensorFailed(m_sensor); - } - - @Override - protected void subRedo() throws RainbowException { - subExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - - } - - @Override - protected boolean checkModelValidForCommand(RobotState model) { - return true; - } - -} +package org.sa.rainbow.brass.model.p2_cp3.robot; + +import java.util.List; + +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class SetSensorFailedCmd extends AbstractRainbowModelOperation { + + private Sensors m_sensor; + + public SetSensorFailedCmd(String commandName, CP3RobotStateModelInstance model, String target, String param) { + super(commandName, model, target, param); + m_sensor = Sensors.valueOf(param); + } + + @Override + public Boolean getResult() throws IllegalStateException { + return true; + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents(messageFactory, getName()); + } + + @Override + protected void subExecute() throws RainbowException { + ((CP3RobotState) getModelContext().getModelInstance()).setSensorFailed(m_sensor); + } + + @Override + protected void subRedo() throws RainbowException { + subExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + + } + + @Override + protected boolean checkModelValidForCommand(RobotState model) { + return true; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotState.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotState.java index 7b95c3ea8..2f0c3d8d3 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotState.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotState.java @@ -1,68 +1,68 @@ -package org.sa.rainbow.brass.model.robot; - -import java.util.ArrayDeque; -import java.util.Deque; - -import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel; -import org.sa.rainbow.core.models.ModelReference; - -public class RobotState extends ClockedModel { - - Deque> m_chargeHistory = new ArrayDeque<>(); - Deque> m_speedHistory = new ArrayDeque<>(); - private ModelReference m_model; - public RobotState(ModelReference model) { - m_model = model; - } - - public ModelReference getModelReference() { - return m_model; - } - - public void setCharge(double charge) { - synchronized (m_chargeHistory) { - m_chargeHistory.push(new TimeStamped (charge)); - } - } - - public double getCharge() throws IllegalStateException { - synchronized (m_chargeHistory) { - TimeStamped peek = m_chargeHistory.peek(); - if (peek == null) throw new IllegalStateException("No value for charge has been set yet"); - return peek.data; - } - } - - public void setSpeed(double speed) { - synchronized (m_speedHistory) { - m_speedHistory.push(new TimeStamped (speed)); - } - } - - public double getSpeed() throws IllegalStateException { - synchronized (m_speedHistory) { - TimeStamped peek = m_speedHistory.peek(); - if (peek == null) - throw new IllegalStateException("No value for speed has been set yet"); - return peek.data; - } - } - - public RobotState copy() { - RobotState r = new RobotState(getModelReference()); - this.copyInto(r); - return r; - } - - protected void copyInto(RobotState r) { - r.m_chargeHistory.addAll(this.m_chargeHistory); - r.m_speedHistory.addAll(this.m_speedHistory); - } - - - - - - - -} +package org.sa.rainbow.brass.model.robot; + +import java.util.ArrayDeque; +import java.util.Deque; + +import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel; +import org.sa.rainbow.core.models.ModelReference; + +public class RobotState extends ClockedModel { + + Deque> m_chargeHistory = new ArrayDeque<>(); + Deque> m_speedHistory = new ArrayDeque<>(); + private ModelReference m_model; + public RobotState(ModelReference model) { + m_model = model; + } + + public ModelReference getModelReference() { + return m_model; + } + + public void setCharge(double charge) { + synchronized (m_chargeHistory) { + m_chargeHistory.push(new TimeStamped (charge)); + } + } + + public double getCharge() throws IllegalStateException { + synchronized (m_chargeHistory) { + TimeStamped peek = m_chargeHistory.peek(); + if (peek == null) throw new IllegalStateException("No value for charge has been set yet"); + return peek.data; + } + } + + public void setSpeed(double speed) { + synchronized (m_speedHistory) { + m_speedHistory.push(new TimeStamped (speed)); + } + } + + public double getSpeed() throws IllegalStateException { + synchronized (m_speedHistory) { + TimeStamped peek = m_speedHistory.peek(); + if (peek == null) + throw new IllegalStateException("No value for speed has been set yet"); + return peek.data; + } + } + + public RobotState copy() { + RobotState r = new RobotState(getModelReference()); + this.copyInto(r); + return r; + } + + protected void copyInto(RobotState r) { + r.m_chargeHistory.addAll(this.m_chargeHistory); + r.m_speedHistory.addAll(this.m_speedHistory); + } + + + + + + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateCommandFactory.java index 26e0920b6..7c0373a85 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateCommandFactory.java @@ -1,55 +1,56 @@ -package org.sa.rainbow.brass.model.robot; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class RobotStateCommandFactory extends ModelCommandFactory { - public RobotStateCommandFactory( - RobotStateModelInstance model) { - super(RobotStateModelInstance.class, model); - } - - protected RobotStateCommandFactory (Class> c, RobotStateModelInstance model) { - super (c, model); - } - - public static RobotStateLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream stream, String source) { - return new RobotStateLoadCmd(mm, modelName, stream, source); - } - - @Override - protected void fillInCommandMap() { - m_commandMap.put("setClockModel".toLowerCase(), SetClockModelCmd.class); - m_commandMap.put("setBatteryCharge".toLowerCase(), SetBatteryChargeCmd.class); - m_commandMap.put("setSpeed".toLowerCase(), SetSpeedCmd.class); - - } - - @Override - public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { - try (FileOutputStream os = new FileOutputStream(location)) { - return new SaveRobotStateCmd(null, location, os, m_modelInstance.getOriginalSource()); - } catch (IOException e) { - return null; - } - } - - public SetClockModelCmd setClockModelCmd(String clockReference) { - return new SetClockModelCmd(m_modelInstance, "", clockReference); - } - - public SetBatteryChargeCmd setBatteryChargeCmd(double charge) { - return new SetBatteryChargeCmd ((RobotStateModelInstance) m_modelInstance, "", Double.toString (charge)); - } - - public SetSpeedCmd setSpeedCmd(double speed) { - return new SetSpeedCmd((RobotStateModelInstance )m_modelInstance, "", Double.toString(speed)); - } -} +package org.sa.rainbow.brass.model.robot; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class RobotStateCommandFactory extends ModelCommandFactory { + private static final String SET_SPEED_CMD = "setSpeed"; + private static final String SET_BATTERY_CHARGE_CMD = "setBatteryCharge"; + private static final String SET_CLOCK_MODEL_CMD = "setClockModel"; + + public RobotStateCommandFactory( + RobotStateModelInstance model) throws RainbowException { + super(RobotStateModelInstance.class, model); + } + + protected RobotStateCommandFactory (Class> c, RobotStateModelInstance model) throws RainbowException { + super (c, model); + } + + @LoadOperation + public static RobotStateLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream stream, String source) { + return new RobotStateLoadCmd(mm, modelName, stream, source); + } + + @Override + public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { + try (FileOutputStream os = new FileOutputStream(location)) { + return new SaveRobotStateCmd(null, location, os, m_modelInstance.getOriginalSource()); + } catch (IOException e) { + return null; + } + } + + @Operation(name=SET_CLOCK_MODEL_CMD) + public SetClockModelCmd setClockModelCmd(String clockReference) { + return new SetClockModelCmd(SET_CLOCK_MODEL_CMD, m_modelInstance, "", clockReference); + } + + @Operation(name=SET_BATTERY_CHARGE_CMD) + public SetBatteryChargeCmd setBatteryChargeCmd(double charge) { + return new SetBatteryChargeCmd (SET_BATTERY_CHARGE_CMD, (RobotStateModelInstance) m_modelInstance, "", Double.toString (charge)); + } + + @Operation(name=SET_SPEED_CMD) + public SetSpeedCmd setSpeedCmd(double speed) { + return new SetSpeedCmd(SET_SPEED_CMD, (RobotStateModelInstance )m_modelInstance, "", Double.toString(speed)); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateLoadCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateLoadCmd.java index 18a712d9a..64943a2f7 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateLoadCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateLoadCmd.java @@ -1,60 +1,60 @@ -package org.sa.rainbow.brass.model.robot; - -import java.io.InputStream; - -import org.sa.rainbow.brass.model.mission.MissionState; -import org.sa.rainbow.brass.model.mission.MissionStateModelInstance; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; - -public class RobotStateLoadCmd extends AbstractLoadModelCmd { - - private String m_modelName; - protected InputStream m_stream; - protected RobotStateModelInstance m_result; - - public RobotStateLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { - super("loadRobotState", mm, resource, is, source); - m_modelName = resource; - m_stream = is; - } - - @Override - public IModelInstance getResult() throws IllegalStateException { - return m_result; - } - - @Override - public ModelReference getModelReference() { - return new ModelReference(m_modelName, RobotStateModelInstance.ROBOT_STATE_TYPE); - } - - @Override - protected void subExecute() throws RainbowException { - if (m_stream == null) { - RobotState m = new RobotState(getModelReference()); - m_result = new RobotStateModelInstance(m, getOriginalSource()); - doPostExecute(); - } - } - - @Override - protected void subRedo() throws RainbowException { - doPostExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - doPostUndo(); - - } - - @Override - protected boolean checkModelValidForCommand(Object model) { - return true; - } - -} +package org.sa.rainbow.brass.model.robot; + +import java.io.InputStream; + +import org.sa.rainbow.brass.model.mission.MissionState; +import org.sa.rainbow.brass.model.mission.MissionStateModelInstance; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; + +public class RobotStateLoadCmd extends AbstractLoadModelCmd { + + private String m_modelName; + protected InputStream m_stream; + protected RobotStateModelInstance m_result; + + public RobotStateLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { + super("loadRobotState", mm, resource, is, source); + m_modelName = resource; + m_stream = is; + } + + @Override + public IModelInstance getResult() throws IllegalStateException { + return m_result; + } + + @Override + public ModelReference getModelReference() { + return new ModelReference(m_modelName, RobotStateModelInstance.ROBOT_STATE_TYPE); + } + + @Override + protected void subExecute() throws RainbowException { + if (m_stream == null) { + RobotState m = new RobotState(getModelReference()); + m_result = new RobotStateModelInstance(m, getOriginalSource()); + doPostExecute(); + } + } + + @Override + protected void subRedo() throws RainbowException { + doPostExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + doPostUndo(); + + } + + @Override + protected boolean checkModelValidForCommand(Object model) { + return true; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateModelInstance.java index da2c2c575..169714ab9 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/RobotStateModelInstance.java @@ -1,67 +1,67 @@ -package org.sa.rainbow.brass.model.robot; - -import org.sa.rainbow.core.error.RainbowCopyException; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class RobotStateModelInstance implements IModelInstance { - - public static final String ROBOT_STATE_TYPE = "RobotState"; - private RobotState m_robotState; - private RobotStateCommandFactory m_commandFactory; - private String m_source; - - public RobotStateModelInstance(RobotState r, String source) { - setModelInstance(r); - setOriginalSource(source); - } - - @Override - public RobotState getModelInstance() { - return m_robotState; - } - - @Override - public void setModelInstance(RobotState model) { - m_robotState = model; - } - - @Override - public IModelInstance copyModelInstance(String newName) throws RainbowCopyException { - return new RobotStateModelInstance(getModelInstance().copy(), getOriginalSource()); - } - - @Override - public String getModelType() { - return ROBOT_STATE_TYPE; - } - - @Override - public String getModelName() { - return getModelInstance().getModelReference().getModelName(); - } - - @Override - public ModelCommandFactory getCommandFactory() { - if (m_commandFactory == null) - m_commandFactory = new RobotStateCommandFactory(this); - return m_commandFactory; - } - - @Override - public void setOriginalSource(String source) { - m_source = source; - } - - @Override - public String getOriginalSource() { - return m_source; - } - - @Override - public void dispose() throws RainbowException { - - } - -} +package org.sa.rainbow.brass.model.robot; + +import org.sa.rainbow.core.error.RainbowCopyException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class RobotStateModelInstance implements IModelInstance { + + public static final String ROBOT_STATE_TYPE = "RobotState"; + private RobotState m_robotState; + private RobotStateCommandFactory m_commandFactory; + private String m_source; + + public RobotStateModelInstance(RobotState r, String source) { + setModelInstance(r); + setOriginalSource(source); + } + + @Override + public RobotState getModelInstance() { + return m_robotState; + } + + @Override + public void setModelInstance(RobotState model) { + m_robotState = model; + } + + @Override + public IModelInstance copyModelInstance(String newName) throws RainbowCopyException { + return new RobotStateModelInstance(getModelInstance().copy(), getOriginalSource()); + } + + @Override + public String getModelType() { + return ROBOT_STATE_TYPE; + } + + @Override + public String getModelName() { + return getModelInstance().getModelReference().getModelName(); + } + + @Override + public ModelCommandFactory getCommandFactory() throws RainbowException { + if (m_commandFactory == null) + m_commandFactory = new RobotStateCommandFactory(this); + return m_commandFactory; + } + + @Override + public void setOriginalSource(String source) { + m_source = source; + } + + @Override + public String getOriginalSource() { + return m_source; + } + + @Override + public void dispose() throws RainbowException { + + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SaveRobotStateCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SaveRobotStateCmd.java index ad1c793f2..9cd8a6a04 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SaveRobotStateCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SaveRobotStateCmd.java @@ -1,65 +1,65 @@ -package org.sa.rainbow.brass.model.robot; - -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.Deque; -import java.util.Iterator; - -import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel.TimeStamped; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; - -public class SaveRobotStateCmd extends AbstractSaveModelCmd { - - public SaveRobotStateCmd(IModelsManager mm, String resource, OutputStream os, String source) { - super("saveRobotState", mm, resource, os, source); - } - - @Override - public Object getResult() throws IllegalStateException { - return null; - } - - @Override - protected void subExecute() throws RainbowException { - RobotState model = getModelContext().getModelInstance(); - try (PrintStream ps = new PrintStream(getStream ())) { - ps.print("{\n"); - insertRobotState(ps, model); - ps.print("}"); - } - } - - protected void insertRobotState(PrintStream ps, RobotState model) { - ps.print(" chargeHistory : [\n"); - for (Iterator> iterator = model.m_chargeHistory.iterator(); iterator.hasNext();) { - TimeStamped entry = iterator.next(); - ps.print("{timestamp: " + entry.timestamp + ", charge : " + entry.data + "}"); - if (iterator.hasNext()) ps.print(", "); - } - ps.print("]"); - - ps.print(" speedHistory : [\n"); - for (Iterator> iterator = model.m_speedHistory.iterator(); iterator.hasNext();) { - TimeStamped entry = iterator.next(); - ps.print("{timestamp: " + entry.timestamp + ", speed : " + entry.data + "}"); - if (iterator.hasNext()) ps.print(", "); - } - ps.print("]");; - } - - @Override - protected void subRedo() throws RainbowException { - } - - @Override - protected void subUndo() throws RainbowException { - } - - @Override - protected boolean checkModelValidForCommand(RobotState model) { - return true; - } - -} +package org.sa.rainbow.brass.model.robot; + +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.Deque; +import java.util.Iterator; + +import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel.TimeStamped; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; + +public class SaveRobotStateCmd extends AbstractSaveModelCmd { + + public SaveRobotStateCmd(IModelsManager mm, String resource, OutputStream os, String source) { + super("saveRobotState", mm, resource, os, source); + } + + @Override + public Object getResult() throws IllegalStateException { + return null; + } + + @Override + protected void subExecute() throws RainbowException { + RobotState model = getModelContext().getModelInstance(); + try (PrintStream ps = new PrintStream(getStream ())) { + ps.print("{\n"); + insertRobotState(ps, model); + ps.print("}"); + } + } + + protected void insertRobotState(PrintStream ps, RobotState model) { + ps.print(" chargeHistory : [\n"); + for (Iterator> iterator = model.m_chargeHistory.iterator(); iterator.hasNext();) { + TimeStamped entry = iterator.next(); + ps.print("{timestamp: " + entry.timestamp + ", charge : " + entry.data + "}"); + if (iterator.hasNext()) ps.print(", "); + } + ps.print("]"); + + ps.print(" speedHistory : [\n"); + for (Iterator> iterator = model.m_speedHistory.iterator(); iterator.hasNext();) { + TimeStamped entry = iterator.next(); + ps.print("{timestamp: " + entry.timestamp + ", speed : " + entry.data + "}"); + if (iterator.hasNext()) ps.print(", "); + } + ps.print("]");; + } + + @Override + protected void subRedo() throws RainbowException { + } + + @Override + protected void subUndo() throws RainbowException { + } + + @Override + protected boolean checkModelValidForCommand(RobotState model) { + return true; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetBatteryChargeCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetBatteryChargeCmd.java index d247bc16b..a9773652b 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetBatteryChargeCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetBatteryChargeCmd.java @@ -13,8 +13,8 @@ public class SetBatteryChargeCmd extends AbstractRainbowModelOperation getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setBatteryCharge"); + return generateEvents (messageFactory, getName()); } @Override diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetClockModelCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetClockModelCmd.java index 13661000e..0e5264cdb 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetClockModelCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetClockModelCmd.java @@ -1,14 +1,14 @@ -package org.sa.rainbow.brass.model.robot; - -import org.sa.rainbow.core.models.IModelInstance; - -public class SetClockModelCmd extends org.sa.rainbow.brass.model.p2_cp3.clock.SetClockModelCmd { - - public SetClockModelCmd(IModelInstance model, String target, String clockReference) { - super(model, target, clockReference); - } - - - - -} +package org.sa.rainbow.brass.model.robot; + +import org.sa.rainbow.core.models.IModelInstance; + +public class SetClockModelCmd extends org.sa.rainbow.brass.model.p2_cp3.clock.SetClockModelCmd { + + public SetClockModelCmd(String commandName, IModelInstance model, String target, String clockReference) { + super(commandName, model, target, clockReference); + } + + + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetSpeedCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetSpeedCmd.java index 97c7248c8..3ce76f2ac 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetSpeedCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/model/robot/SetSpeedCmd.java @@ -1,55 +1,55 @@ -package org.sa.rainbow.brass.model.robot; - -import java.util.List; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public class SetSpeedCmd extends AbstractRainbowModelOperation { - - private double m_speed; - - public SetSpeedCmd(IModelInstance model, String target, String speed) { - super("setSpeed", model, target, speed); - m_speed = Double.parseDouble(speed); - } - - @Override - public Double getResult() throws IllegalStateException { - return getModelContext ().getModelInstance ().getSpeed (); - - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "setSpeed"); - - } - - @Override - protected void subExecute() throws RainbowException { - getModelContext ().getModelInstance ().setSpeed (m_speed); - - } - - @Override - protected void subRedo() throws RainbowException { - subExecute (); - - } - - @Override - protected void subUndo() throws RainbowException { - - } - - @Override - protected boolean checkModelValidForCommand(RobotState model) { - return model == getModelContext ().getModelInstance (); - - } - -} +package org.sa.rainbow.brass.model.robot; + +import java.util.List; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class SetSpeedCmd extends AbstractRainbowModelOperation { + + private double m_speed; + + public SetSpeedCmd(String commandName, IModelInstance model, String target, String speed) { + super(commandName, model, target, speed); + m_speed = Double.parseDouble(speed); + } + + @Override + public Double getResult() throws IllegalStateException { + return getModelContext ().getModelInstance ().getSpeed (); + + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents (messageFactory, getName()); + + } + + @Override + protected void subExecute() throws RainbowException { + getModelContext ().getModelInstance ().setSpeed (m_speed); + + } + + @Override + protected void subRedo() throws RainbowException { + subExecute (); + + } + + @Override + protected void subUndo() throws RainbowException { + + } + + @Override + protected boolean checkModelValidForCommand(RobotState model) { + return model == getModelContext ().getModelInstance (); + + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CP1BRASSAdaptationPlanner.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CP1BRASSAdaptationPlanner.java index 00aa05ff3..bf9109d96 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CP1BRASSAdaptationPlanner.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CP1BRASSAdaptationPlanner.java @@ -1,346 +1,431 @@ -package org.sa.rainbow.brass.p3_cp1.adaptation; - -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; - -import org.sa.rainbow.brass.PropertiesConnector; -import org.sa.rainbow.brass.adaptation.BrassPlan; -import org.sa.rainbow.brass.adaptation.NewInstructionGraph; -import org.sa.rainbow.brass.adaptation.PrismConnectorAPI; -import org.sa.rainbow.brass.adaptation.PrismPolicy; -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.brass.das.BRASSHttpConnector; -import org.sa.rainbow.brass.das.IBRASSConnector.DASPhase2StatusT; -import org.sa.rainbow.brass.das.IBRASSConnector.Phases; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.p3_cp1.model.CP1ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.Heading; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.brass.plan.p2.MapTranslator; -import org.sa.rainbow.brass.p3_cp1.plan.DecisionEngineCP1; -import org.sa.rainbow.brass.p3_cp1.plan.PolicyToIGCP1; -import org.sa.rainbow.core.AbstractRainbowRunnable; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.RainbowConstants; -import org.sa.rainbow.core.adaptation.AdaptationTree; -import org.sa.rainbow.core.adaptation.DefaultAdaptationTreeWalker; -import org.sa.rainbow.core.adaptation.IAdaptationManager; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; -import org.sa.rainbow.core.ports.IModelsManagerPort; -import org.sa.rainbow.core.ports.IRainbowAdaptationEnqueuePort; -import org.sa.rainbow.core.ports.IRainbowReportingPort; -import org.sa.rainbow.core.ports.RainbowPortFactory; - -public class CP1BRASSAdaptationPlanner extends AbstractRainbowRunnable implements IAdaptationManager { - - public static final String NAME = "BRASS Adaptation Planner"; - // The thread "sleep" time. runAction will be called every 10 seconds in this - // case - public static final int SLEEP_TIME = 10000 /* ms */; - private IModelsManagerPort m_modelsManagerPort; - private IModelChangeBusSubscriberPort m_modelChangePort; - private CP1ModelAccessor m_models; - private SimpleConfigurationStore m_configurationStore; - private ModelReference m_modelRef; - private IRainbowAdaptationEnqueuePort m_adaptationEnqueuePort; - private boolean m_executingPlan = false; - private boolean m_adaptationEnabled = true; - private boolean m_errorDetected = false; - private boolean m_inLastResort = false; - private boolean m_reportAdapted; - - /** - * Default Constructor with name for the thread. - */ - public CP1BRASSAdaptationPlanner() { - super(NAME); - String per = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); - if (per != null) { - setSleepTime(Long.parseLong(per)); - } else { - setSleepTime(SLEEP_TIME); - } - } - - @Override - public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { - super.initialize(port); - initConnectors(); - try { - DecisionEngineCP1.init(Rainbow.instance().allProperties()); - DecisionEngineCP1.m_real_observed_battery_ratio=0.9; - DecisionEngineCP1.setMap(m_models.getEnvMapModel().getModelInstance()); - m_configurationStore = new SimpleConfigurationStore(Rainbow.instance().allProperties()); - m_configurationStore.populate(); - DecisionEngineCP1.setConfigurationProvider(m_configurationStore); - } catch (Exception e) { - e.printStackTrace(); - throw new RainbowConnectionException("Cannot initialize DecisionEngine", e); - } - } - - private void initConnectors() throws RainbowConnectionException { - // Create port to query models manager - m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort(); - m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort(); - m_models = new CP1ModelAccessor(m_modelsManagerPort); - // If you want to listen to changes, then you need to create a modelChangePort - // and write a subscriber to it. - // See org.sa.rainbow.stitch.AdaptationManger for an example of this - - } - - @Override - public void dispose() { - // TODO Auto-generated method stub - - } - - @Override - public void setModelToManage(ModelReference modelRef) { - m_modelRef = modelRef; - // Create a port to send any plans on (AdaptationTree) that will be - // sent to an executor - m_adaptationEnqueuePort = RainbowPortFactory.createAdaptationEnqueuePort(modelRef); - - } - - @Override - public void markStrategyExecuted(AdaptationTree plan) { - // Insert code here to record when a plan has been executed by the execution - // manager - // Possible things to do: - // (a) keep a history of plan success - // (b) start listening to model events to generate new plans again - - AdaptationResultsVisitor v = new AdaptationResultsVisitor(plan); - plan.visit(v); - if (m_reportAdapted) { - if (v.m_allOk) { - BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.ADAPTED.name(), - "Finished adapting the system"); - } else { - BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.ADAPTED_FAILED.name(), - "Something in the adaptation plan failed to execute."); - } - m_reportAdapted = false; - } - try { - // Wait for IG to come to Analyzer - Thread.sleep(5000); - } catch (InterruptedException e) { - } - m_executingPlan = false; - } - - @Override - public void setEnabled(boolean enabled) { - m_adaptationEnabled = enabled; - - } - - @Override - public boolean isEnabled() { - return m_adaptationEnabled; - - } - - @Override - protected void log(String txt) { - m_reportingPort.info(RainbowComponentT.ADAPTATION_MANAGER, txt); - - } - - @Override - protected void runAction() { - InstructionGraphProgress igModel = m_models.getInstructionGraphModel().getModelInstance(); - if (igModel.getInstructions().isEmpty() || m_models.getRainbowStateModel().getModelInstance().waitForIG()) - return; - if (m_adaptationEnabled && !m_executingPlan) { - if (reallyHasError()) { - BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.ADAPTING.name(), - "Detected a problem"); - - m_errorDetected = false; - m_reportingPort.info(getComponentType(), "Determining an appropriate adaptation"); - // DecisionEngineCP3.setMap(m_models.getEnvMapModel().getModelInstance()); - - EnvMap envMap = m_models.getEnvMapModel().getModelInstance(); // This means that the obstruction will - // only persist for this plan - IInstruction ci = igModel.getCurrentInstruction(); - LocationRecording cp = m_models.getMissionStateModel().getModelInstance().getCurrentPose(); - String srcLabel = null; - String tgtLabel = null; - if (ci instanceof MoveAbsHInstruction) { - MoveAbsHInstruction mi = (MoveAbsHInstruction) ci; - srcLabel = envMap.getNextNodeId(); - boolean obstructed = m_models.getRainbowStateModel().getModelInstance().getProblems() - .contains(CP3ModelState.IS_OBSTRUCTED); - srcLabel = envMap.insertNode(srcLabel, mi.getSourceWaypoint(), mi.getTargetWaypoint(), cp.getX(), - cp.getY(), obstructed); - tgtLabel = mi.getTargetWaypoint(); - } else { - List remainingInstructions = igModel.getRemainingInstructions(); - for (Iterator iterator = remainingInstructions.iterator(); iterator.hasNext() - && !(ci instanceof MoveAbsHInstruction);) { - ci = (IInstruction) iterator.next(); - } - if (ci != null) { - MoveAbsHInstruction mi = (MoveAbsHInstruction) ci; - srcLabel = mi.getSourceWaypoint(); - tgtLabel = mi.getTargetWaypoint(); - } else { - m_reportingPort.error(getComponentType(), - "There are no move instructions left -- the last instruction in an instruction graph for BRASS should always be a move"); - } - } - - DecisionEngineCP1.setMap(envMap); - String tgt = m_models.getMissionStateModel().getModelInstance().getTargetWaypoint(); - log("Generating candidate paths from " + srcLabel + " to " + tgt); - - DecisionEngineCP1.generateCandidates(srcLabel, tgt, true); - log("---> found " + DecisionEngineCP1.m_candidates.size()); - - try { - DecisionEngineCP1.scoreCandidates(envMap, - Math.round(m_models.getRobotStateModel().getModelInstance().getCharge()), - Heading.convertFromRadians( - m_models.getMissionStateModel().getModelInstance().getCurrentPose().getRotation()) - .ordinal()); - PrismPolicy pp = null; - if (!DecisionEngineCP1.m_scoreboard.isEmpty()) { - pp = new PrismPolicy(DecisionEngineCP1.selectPolicy()); - pp.readPolicy(); - } - - if (DecisionEngineCP1.m_scoreboard.isEmpty() || pp.getPlan() == null || pp.getPlan().isEmpty()) { - // BRASSHttpConnector.instance ().reportStatus (DASStatusT.MISSION_ABORTED, - // "Could not find a valid adaptation... trying again."); - log("Could not find a valid adaptation..."); - - MapTranslator.exportMapTranslation( - Rainbow.instance().getProperty(PropertiesConnector.PRISM_MODEL_PROPKEY)); - PrismConnectorAPI.instance() - .loadModel(Rainbow.instance().getProperty(PropertiesConnector.PRISM_MODEL_PROPKEY)); - String m_consts = MapTranslator.INITIAL_ROBOT_CONF_CONST + "=-1," - + MapTranslator.INITIAL_ROBOT_LOCATION_CONST + "=" - + String.valueOf(envMap.getNodeId(srcLabel)) + "," - + MapTranslator.TARGET_ROBOT_LOCATION_CONST + "=" - + String.valueOf(envMap.getNodeId(tgt)) + "," - + MapTranslator.INITIAL_ROBOT_BATTERY_CONST + "=" - + String.valueOf( - Math.round(m_models.getRobotStateModel().getModelInstance().getCharge())) - + "," + MapTranslator.INITIAL_ROBOT_HEADING_CONST + "=2"; - - log("Generating last resort plan for " + m_consts); - String result; - result = PrismConnectorAPI.instance().modelCheckFromFileS( - Rainbow.instance().getProperty(PropertiesConnector.PRISM_MODEL_PROPKEY), - Rainbow.instance().getProperty(PropertiesConnector.PRISM_PROPERTIES_PROPKEY), - /* - * Rainbow.instance ().getProperty - * (PropertiesConnector.PRISM_ADV_EXPORT_PROPKEY) - */"lastResortPolicy", 0, m_consts); - pp = new PrismPolicy("lastResortPolicy.adv"); - pp.readPolicy(); - if (pp.getPlan() == null || pp.getPlan().isEmpty()) { - log("Could not find last resort plan -- marking task as FAILED"); - BrassPlan ct = new CompletedTask(m_models, false); - AdaptationTree at = new AdaptationTree<>(ct); - m_executingPlan = true; - BRASSHttpConnector.instance(Phases.Phase2).reportStatus( - DASPhase2StatusT.ADAPTED_FAILED.name(), - "Could not find an alternate (even last resort) plan to complete task: " + tgt); - m_adaptationEnqueuePort.offerAdaptation(at, new Object[] {}); - return; - } - m_inLastResort = true; - log("Found last resort plan: " + pp.getPlan().toString()); - } - - String plan = pp.getPlan().toString(); - m_reportingPort.info(getComponentType(), "Planner chooses the plan " + plan); - PolicyToIGCP1 translator = new PolicyToIGCP1(pp, envMap); - String translate = translator.translate(m_configurationStore); - - BrassPlan nig = new NewInstructionGraph(m_models, translate); - AdaptationTree at = new AdaptationTree<>(nig); - m_executingPlan = true; - m_models.getRainbowStateModel().getModelInstance().m_waitForIG = true; - m_reportAdapted = true; - m_adaptationEnqueuePort.offerAdaptation(at, new Object[] {}); - } catch (Exception e) { - e.printStackTrace(); - m_reportingPort.error(getComponentType(), "Failed to find a plan " + e.getMessage()); - } - } else if (m_models.getRainbowStateModel().getModelInstance().getProblems() - .contains(CP3ModelState.OUT_OF_BATTERY)) { - m_reportingPort.error(getComponentType(), - "Cannot find a plan that magically gives us more power -- we are out of battery"); - BRASSHttpConnector.instance(Phases.Phase2).reportDone(true, "Ran out of power"); - } else if (!m_models.getRainbowStateModel().getModelInstance().waitForIG() - && m_models.getInstructionGraphModel().getModelInstance() - .getInstructionGraphState() == IGExecutionStateT.FINISHED_SUCCESS) { - log("Planner detected successful completion of instruction graph"); - log("Reporting that we completed successfully"); - CompletedTask ct = new CompletedTask(m_models, true); - AdaptationTree at = new AdaptationTree<>(ct); - m_executingPlan = true; - m_models.getRainbowStateModel().getModelInstance().m_waitForIG = true; - m_adaptationEnqueuePort.offerAdaptation(at, new Object[] {}); - } else if (m_inLastResort && m_models.getInstructionGraphModel().getModelInstance() - .getInstructionGraphState() == IGExecutionStateT.FINISHED_FAILED) { - CompletedTask ct = new CompletedTask(m_models, false); - AdaptationTree at = new AdaptationTree<>(ct); - m_executingPlan = true; - m_adaptationEnqueuePort.offerAdaptation(at, new Object[] {}); - } - - } - - } - - private boolean reallyHasError() { - EnumSet realErrors = EnumSet.of(CP3ModelState.LOW_ON_BATTERY, CP3ModelState.IS_OBSTRUCTED, - CP3ModelState.INSTRUCTION_GRAPH_FAILED); - for (CP3ModelState state : realErrors) { - if (m_models.getRainbowStateModel().getModelInstance().getProblems().contains(state)) - return true; - } - return false; - } - - @Override - public RainbowComponentT getComponentType() { - return RainbowComponentT.ADAPTATION_MANAGER; - - } - - public static String DUMMY_ALTERNATE_IG = "P(V(1, do MoveAbs (19.5,69,1) then 2),V(2, do MoveAbs (19.5,59,1) then 3)::V(3, do Move (42.5, 59, 0) then 4)::V(4, end)::nil)"; - - private class AdaptationResultsVisitor extends DefaultAdaptationTreeWalker { - - public AdaptationResultsVisitor(AdaptationTree adt) { - super(adt); - } - - boolean m_allOk = true; - - @Override - protected void evaluate(BrassPlan adaptation) { - m_allOk &= adaptation.getOutcome(); - } - - } - -} +package org.sa.rainbow.brass.p3_cp1.adaptation; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.brass.PropertiesConnector; +import org.sa.rainbow.brass.adaptation.BrassPlan; +import org.sa.rainbow.brass.adaptation.NewInstructionGraph; +import org.sa.rainbow.brass.adaptation.PrismConnectorAPI; +import org.sa.rainbow.brass.adaptation.PrismPolicy; +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.brass.das.BRASSHttpConnector; +import org.sa.rainbow.brass.das.IBRASSConnector.DASPhase2StatusT; +import org.sa.rainbow.brass.das.IBRASSConnector.Phases; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.p3_cp1.model.CP1ModelAccessor; +import org.sa.rainbow.brass.p3_cp1.model.power.PowerModelCommandFactory; +import org.sa.rainbow.brass.p3_cp1.model.power.UpdatePowerModelCmd; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.Heading; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.brass.plan.p2.MapTranslator; +import org.sa.rainbow.brass.p3_cp1.plan.DecisionEngineCP1; +import org.sa.rainbow.brass.p3_cp1.plan.PolicyToIGCP1; +import org.sa.rainbow.core.AbstractRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.adaptation.AdaptationTree; +import org.sa.rainbow.core.adaptation.DefaultAdaptationTreeWalker; +import org.sa.rainbow.core.adaptation.IAdaptationManager; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IRainbowAdaptationEnqueuePort; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; + +public class CP1BRASSAdaptationPlanner extends AbstractRainbowRunnable implements IAdaptationManager { + + public static final String NAME = "BRASS Adaptation Planner"; + // The thread "sleep" time. runAction will be called every 10 seconds in this + // case + public static final int SLEEP_TIME = 10000 /* ms */; + private IModelsManagerPort m_modelsManagerPort; + private IModelChangeBusSubscriberPort m_modelChangePort; + private CP1ModelAccessor m_models; + private SimpleConfigurationStore m_configurationStore; + private ModelReference m_modelRef; + private IRainbowAdaptationEnqueuePort m_adaptationEnqueuePort; + private boolean m_executingPlan = false; + private boolean m_adaptationEnabled = true; + private boolean m_errorDetected = false; + private boolean m_inLastResort = false; + private boolean m_reportAdapted; + + + + /** + * Default Constructor with name for the thread. + */ + public CP1BRASSAdaptationPlanner() { + super(NAME); + String per = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (per != null) { + setSleepTime(Long.parseLong(per)); + } else { + setSleepTime(SLEEP_TIME); + } + } + + @Override + public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize(port); + initConnectors(); + try { + DecisionEngineCP1.init(Rainbow.instance().allProperties()); + DecisionEngineCP1.m_real_observed_battery_ratio=0.9; + DecisionEngineCP1.setMap(m_models.getEnvMapModel().getModelInstance()); + m_configurationStore = new SimpleConfigurationStore(Rainbow.instance().allProperties()); + m_configurationStore.populate(); + DecisionEngineCP1.setConfigurationProvider(m_configurationStore); + } catch (Exception e) { + e.printStackTrace(); + throw new RainbowConnectionException("Cannot initialize DecisionEngine", e); + } + } + + private void initConnectors() throws RainbowConnectionException { + // Create port to query models manager + m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort(); + m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort(); + m_modelChangePort.subscribe((message) -> { + String operation = (String )message.getProperty(IModelChangeBusPort.COMMAND_PROP); + return (PowerModelCommandFactory.UPDATE_POWER_MODEL_CMD.equals(operation)); + }, (model, message) -> { + synchronized(CP1BRASSAdaptationPlanner.this) { + this.notifyAll(); + } + }); + m_models = new CP1ModelAccessor(m_modelsManagerPort); + // If you want to listen to changes, then you need to create a modelChangePort + // and write a subscriber to it. + // See org.sa.rainbow.stitch.AdaptationManger for an example of this + + } + + @Override + public void dispose() { + // TODO Auto-generated method stub + + } + + @Override + public void setModelToManage(ModelReference modelRef) { + m_modelRef = modelRef; + // Create a port to send any plans on (AdaptationTree) that will be + // sent to an executor + m_adaptationEnqueuePort = RainbowPortFactory.createAdaptationEnqueuePort(modelRef); + + } + + @Override + public void markStrategyExecuted(AdaptationTree plan) { + // Insert code here to record when a plan has been executed by the execution + // manager + // Possible things to do: + // (a) keep a history of plan success + // (b) start listening to model events to generate new plans again + + AdaptationResultsVisitor v = new AdaptationResultsVisitor(plan); + try { + plan.visit(v); + } catch (RainbowException e1) { + // TODO Auto-generated catch block + log(e1.getMessage()); + } + if (m_reportAdapted) { + if (v.m_allOk) { + BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.ADAPTED.name(), + "Finished adapting the system"); + } else { + BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.ADAPTED_FAILED.name(), + "Something in the adaptation plan failed to execute."); + } + m_reportAdapted = false; + } + try { + // Wait for IG to come to Analyzer + Thread.sleep(5000); + } catch (InterruptedException e) { + } + m_executingPlan = false; + } + + @Override + public void setEnabled(boolean enabled) { + m_adaptationEnabled = enabled; + + } + + @Override + public boolean isEnabled() { + return m_adaptationEnabled; + + } + + @Override + protected void log(String txt) { + m_reportingPort.info(RainbowComponentT.ADAPTATION_MANAGER, txt); + + } + + protected void waitForPowerModel() { + // Be careful with this -- stops the thread entirely + synchronized (this) { + try { + this.wait(); + } catch (InterruptedException e) { + } + } + } + + protected void triggerOnlineLearning() { + log("Triggering online learning"); + boolean learningHasStarted = BRASSHttpConnector.instance(Phases.Phase2).requestOnlineLearning(); + if (learningHasStarted) { + log("Waiting for new power model"); + waitForPowerModel(); + log("Received new power model"); + } + else { + log("NOT waiting for new power model"); + } + } + + @Override + protected void runAction() { + InstructionGraphProgress igModel = m_models.getInstructionGraphModel().getModelInstance(); + if (igModel.getInstructions().isEmpty() || m_models.getRainbowStateModel().getModelInstance().waitForIG()) + return; + if (m_adaptationEnabled && !m_executingPlan) { + if (reallyHasError()) { + BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.ADAPTING.name(), + "Detected a problem"); + cancelInstructions(); + + // Trigger online learning and wait for the model to be updated + triggerOnlineLearning(); + m_errorDetected = false; + m_reportingPort.info(getComponentType(), "Determining an appropriate adaptation"); + // DecisionEngineCP3.setMap(m_models.getEnvMapModel().getModelInstance()); + + EnvMap envMap = m_models.getEnvMapModel().getModelInstance(); // This means that the obstruction will + // only persist for this plan + IInstruction ci = igModel.getCurrentInstruction(); + LocationRecording cp = m_models.getMissionStateModel().getModelInstance().getCurrentPose(); + String srcLabel = null; + String tgtLabel = null; + if (ci instanceof MoveAbsHInstruction) { + MoveAbsHInstruction mi = (MoveAbsHInstruction) ci; + srcLabel = envMap.getNextNodeId(); + boolean obstructed = m_models.getRainbowStateModel().getModelInstance().getProblems() + .contains(CP3ModelState.IS_OBSTRUCTED); + m_reportingPort.info(getComponentType(), MessageFormat.format("Inserting obstruction btw {0} and {0}", mi.getSourceWaypoint(), mi.getTargetWaypoint())); + srcLabel = envMap.insertNode(srcLabel, mi.getSourceWaypoint(), mi.getTargetWaypoint(), cp.getX(), + cp.getY(), obstructed); + tgtLabel = mi.getTargetWaypoint(); + } else { + List remainingInstructions = igModel.getRemainingInstructions(); + for (Iterator iterator = remainingInstructions.iterator(); iterator.hasNext() + && !(ci instanceof MoveAbsHInstruction);) { + ci = iterator.next(); + } + if (ci != null) { + MoveAbsHInstruction mi = (MoveAbsHInstruction) ci; + srcLabel = mi.getSourceWaypoint(); + tgtLabel = mi.getTargetWaypoint(); + } else { + m_reportingPort.error(getComponentType(), + "There are no move instructions left -- the last instruction in an instruction graph for BRASS should always be a move"); + } + } + + DecisionEngineCP1.setMap(envMap); + String tgt = m_models.getMissionStateModel().getModelInstance().getTargetWaypoint(); + log("Generating candidate paths from " + srcLabel + " to " + tgt); + + DecisionEngineCP1.generateCandidates(srcLabel, tgt, true); + log("---> found " + DecisionEngineCP1.m_candidates.size()); + + try { + DecisionEngineCP1.scoreCandidates(envMap, + Math.round(m_models.getRobotStateModel().getModelInstance().getCharge()), + Heading.convertFromRadians( + m_models.getMissionStateModel().getModelInstance().getCurrentPose().getRotation()) + .ordinal()); + PrismPolicy pp = null; + if (!DecisionEngineCP1.m_scoreboard.isEmpty()) { + pp = new PrismPolicy(DecisionEngineCP1.selectPolicy()); + pp.readPolicy(); + } + + if (DecisionEngineCP1.m_scoreboard.isEmpty() || pp.getPlan() == null || pp.getPlan().isEmpty()) { + // BRASSHttpConnector.instance ().reportStatus (DASStatusT.MISSION_ABORTED, + // "Could not find a valid adaptation... trying again."); + log("Could not find a valid adaptation..."); + + MapTranslator.exportMapTranslation( + Rainbow.instance().getProperty(PropertiesConnector.PRISM_MODEL_PROPKEY)); + PrismConnectorAPI.instance() + .loadModel(Rainbow.instance().getProperty(PropertiesConnector.PRISM_MODEL_PROPKEY)); + String m_consts = MapTranslator.INITIAL_ROBOT_CONF_CONST + "=-1," + + MapTranslator.INITIAL_ROBOT_LOCATION_CONST + "=" + + String.valueOf(envMap.getNodeId(srcLabel)) + "," + + MapTranslator.TARGET_ROBOT_LOCATION_CONST + "=" + + String.valueOf(envMap.getNodeId(tgt)) + "," + + MapTranslator.INITIAL_ROBOT_BATTERY_CONST + "=" + + String.valueOf( + Math.round(m_models.getRobotStateModel().getModelInstance().getCharge())) + + "," + MapTranslator.INITIAL_ROBOT_HEADING_CONST + "=2"; + + log("Generating last resort plan for " + m_consts); + String result; + result = PrismConnectorAPI.instance().modelCheckFromFileS( + Rainbow.instance().getProperty(PropertiesConnector.PRISM_MODEL_PROPKEY), + Rainbow.instance().getProperty(PropertiesConnector.PRISM_PROPERTIES_PROPKEY), + /* + * Rainbow.instance ().getProperty + * (PropertiesConnector.PRISM_ADV_EXPORT_PROPKEY) + */"lastResortPolicy", 0, m_consts); + pp = new PrismPolicy("lastResortPolicy.adv"); + pp.readPolicy(); + if (pp.getPlan() == null || pp.getPlan().isEmpty()) { + log("Could not find last resort plan -- marking task as FAILED"); + BrassPlan ct = new CompletedTask(m_models, false); + AdaptationTree at = new AdaptationTree<>(ct); + m_executingPlan = true; + BRASSHttpConnector.instance(Phases.Phase2).reportStatus( + DASPhase2StatusT.ADAPTED_FAILED.name(), + "Could not find an alternate (even last resort) plan to complete task: " + tgt); + m_adaptationEnqueuePort.offerAdaptation(at, new Object[] {}); + return; + } + m_inLastResort = true; + log("Found last resort plan: " + pp.getPlan().toString()); + } + + String plan = pp.getPlan().toString(); + m_reportingPort.info(getComponentType(), "Planner chooses the plan " + plan); + PolicyToIGCP1 translator = new PolicyToIGCP1(pp, envMap); + + ArrayList planArray = pp.getPlan(); + ArrayList planToTA = new ArrayList(planArray.size()); + ArrayList planToReport = new ArrayList<>(planArray.size()); + for (String cmd : planArray) { + if (cmd.contains("_to_")) { + Pattern p = Pattern.compile("([^_]*)_to_(.*)"); + Matcher m = p.matcher(cmd); + if (m.matches()) { + planToTA.add(m.group(2)); + planToReport.add(m.group(2)); + } + + } else { + planToReport.add(cmd); + } + } + BRASSHttpConnector.instance(Phases.Phase2).reportNewPlan(planToTA); + + String translate = translator.translate(m_configurationStore); + + BrassPlan nig = new NewInstructionGraph(m_models, translate); + AdaptationTree at = new AdaptationTree<>(nig); + m_executingPlan = true; + m_models.getRainbowStateModel().getModelInstance().m_waitForIG = true; + m_reportAdapted = true; + m_adaptationEnqueuePort.offerAdaptation(at, new Object[] {}); + } catch (Exception e) { + e.printStackTrace(); + m_reportingPort.error(getComponentType(), "Failed to find a plan " + e.getMessage()); + } + } else if (m_models.getRainbowStateModel().getModelInstance().getProblems() + .contains(CP3ModelState.OUT_OF_BATTERY)) { + m_reportingPort.error(getComponentType(), + "Cannot find a plan that magically gives us more power -- we are out of battery"); + BRASSHttpConnector.instance(Phases.Phase2).reportDone(true, "Ran out of power"); + } else if (!m_models.getRainbowStateModel().getModelInstance().waitForIG() + && m_models.getInstructionGraphModel().getModelInstance() + .getInstructionGraphState() == IGExecutionStateT.FINISHED_SUCCESS) { + log("Planner detected successful completion of instruction graph"); + log("Reporting that we completed successfully"); + CompletedTask ct = new CompletedTask(m_models, true); + AdaptationTree at = new AdaptationTree<>(ct); + m_executingPlan = true; + m_models.getRainbowStateModel().getModelInstance().m_waitForIG = true; + m_adaptationEnqueuePort.offerAdaptation(at, new Object[] {}); + } else if (m_inLastResort && m_models.getInstructionGraphModel().getModelInstance() + .getInstructionGraphState() == IGExecutionStateT.FINISHED_FAILED) { + CompletedTask ct = new CompletedTask(m_models, false); + AdaptationTree at = new AdaptationTree<>(ct); + m_executingPlan = true; + m_adaptationEnqueuePort.offerAdaptation(at, new Object[] {}); + } + + } + + } + + protected void cancelInstructions() { + m_reportingPort.info(getComponentType(), "Canceling the current set of instructions."); + CancelInstructionsTask cancelTask = new CancelInstructionsTask(m_models); + AdaptationTree at = new AdaptationTree<>(cancelTask); + m_adaptationEnqueuePort.offerAdaptation(at, new Object[0]); + } + + private boolean reallyHasError() { + EnumSet realErrors = EnumSet.of(CP3ModelState.LOW_ON_BATTERY, CP3ModelState.IS_OBSTRUCTED, + CP3ModelState.INSTRUCTION_GRAPH_FAILED); + for (CP3ModelState state : realErrors) { + if (m_models.getRainbowStateModel().getModelInstance().getProblems().contains(state)) + return true; + } + return false; + } + + @Override + public RainbowComponentT getComponentType() { + return RainbowComponentT.ADAPTATION_MANAGER; + + } + + public static String DUMMY_ALTERNATE_IG = "P(V(1, do MoveAbs (19.5,69,1) then 2),V(2, do MoveAbs (19.5,59,1) then 3)::V(3, do Move (42.5, 59, 0) then 4)::V(4, end)::nil)"; + + private class AdaptationResultsVisitor extends DefaultAdaptationTreeWalker { + + public AdaptationResultsVisitor(AdaptationTree adt) { + super(adt); + } + + boolean m_allOk = true; + + @Override + protected void evaluate(BrassPlan adaptation) { + m_allOk &= adaptation.getOutcome(); + } + + } + + @Override + public ModelReference getManagedModel() { + return m_modelRef; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CancelInstructionsTask.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CancelInstructionsTask.java new file mode 100644 index 000000000..88938fbf7 --- /dev/null +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CancelInstructionsTask.java @@ -0,0 +1,34 @@ +package org.sa.rainbow.brass.p3_cp1.adaptation; + +import org.sa.rainbow.brass.adaptation.BrassPlan; +import org.sa.rainbow.brass.p3_cp1.model.CP1ModelAccessor; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; + +public class CancelInstructionsTask extends BrassPlan { + + private CP1ModelAccessor m_models; + private boolean m_outcome; + + public CancelInstructionsTask(CP1ModelAccessor models) { + m_models = models; + } + + @Override + public Object evaluate(Object[] argsIn) { + IAdaptationExecutor executor = (IAdaptationExecutor) Rainbow.instance().getRainbowMaster().adaptationExecutors().get(m_models.getRainbowStateModel().getModelInstance().getModelReference().toString()); + IRainbowOperation cancel = m_models.getInstructionGraphModel().getCommandFactory().cancelInstructionsCmd(); + OperationResult result = executor.getOperationPublishingPort().publishOperation(cancel); + m_outcome = result.result == Result.SUCCESS; + return m_outcome; + } + + @Override + public boolean getOutcome() { + return m_outcome; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CompletedTask.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CompletedTask.java index bedda2014..a77fcf549 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CompletedTask.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/adaptation/CompletedTask.java @@ -1,47 +1,53 @@ -package org.sa.rainbow.brass.p3_cp1.adaptation; - -import org.sa.rainbow.brass.adaptation.BrassPlan; -import org.sa.rainbow.brass.p3_cp1.model.CP1ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.adaptation.IAdaptationExecutor; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; -import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; - -public class CompletedTask extends BrassPlan { - - private CP1ModelAccessor m_models; - private Boolean m_successOrOtherwise; - private boolean m_outcome; - - public CompletedTask(CP1ModelAccessor models, boolean success) { - m_models = models; - m_successOrOtherwise = success; - - } - - - - @Override - public Object evaluate(Object[] argsIn) { - IAdaptationExecutor executor = Rainbow.instance().getRainbowMaster().strategyExecutor(m_models.getRainbowStateModel().getModelInstance().getModelReference().toString()); - IRainbowOperation op = null; - if (m_successOrOtherwise) { - op = m_models.getRainbowStateModel().getCommandFactory().removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); - } - else { - op = m_models.getRainbowStateModel().getCommandFactory().setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); - } - OperationResult result = executor.getOperationPublishingPort().publishOperation(op); - m_outcome = result.result == Result.SUCCESS; - return m_outcome; - } - - - @Override - public boolean getOutcome() { - return m_outcome; - } - -} +package org.sa.rainbow.brass.p3_cp1.adaptation; + +import org.sa.rainbow.brass.adaptation.BrassPlan; +import org.sa.rainbow.brass.p3_cp1.model.CP1ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; + +public class CompletedTask extends BrassPlan { + + private CP1ModelAccessor m_models; + private Boolean m_successOrOtherwise; + private boolean m_outcome; + + public CompletedTask(CP1ModelAccessor models, boolean success) { + m_models = models; + m_successOrOtherwise = success; + + } + + + + @Override + public Object evaluate(Object[] argsIn) { + try { + IAdaptationExecutor executor = (IAdaptationExecutor) Rainbow.instance().getRainbowMaster().adaptationExecutors().get(m_models.getRainbowStateModel().getModelInstance().getModelReference().toString()); + IRainbowOperation op = null; + if (m_successOrOtherwise) { + op = m_models.getRainbowStateModel().getCommandFactory().removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); + } + else { + op = m_models.getRainbowStateModel().getCommandFactory().setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); + } + OperationResult result = executor.getOperationPublishingPort().publishOperation(op); + m_outcome = result.result == Result.SUCCESS; + } catch (RainbowException e) { + e.printStackTrace(); + m_outcome = false; + } + return m_outcome; + } + + + @Override + public boolean getOutcome() { + return m_outcome; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/BRASSMissionAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/BRASSMissionAnalyzer.java index c07c5bc48..4180ca7ef 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/BRASSMissionAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/BRASSMissionAnalyzer.java @@ -1,170 +1,181 @@ -package org.sa.rainbow.brass.p3_cp1.analysis; - -import java.util.Arrays; - -import org.sa.rainbow.brass.das.BRASSHttpConnector; -import org.sa.rainbow.brass.das.IBRASSConnector.Phases; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.InsertNodeCmd; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RemoveModelProblemCmd; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.SetModelProblemCmd; -import org.sa.rainbow.core.IRainbowRunnable; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowConstants; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IRainbowReportingPort; - -/** - * Created by schmerl on 12/13/2016. Analyzes the current situation and triggers - * adaptation if necessary - */ -public class BRASSMissionAnalyzer extends P2CP1Analyzer { - - public static final String NAME = "BRASS Mission Evaluator"; - - private boolean m_reportedReady = false; - private boolean m_wasOK; - - private boolean m_awaitingNewIG; - - private boolean m_reportedCompleted; - - public BRASSMissionAnalyzer() { - super(NAME); - String per = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); - if (per != null) { - setSleepTime(Long.parseLong(per)); - } else { - setSleepTime(IRainbowRunnable.LONG_SLEEP_TIME); - } - } - - @Override - public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { - super.initialize(port); - log("Initialized missions analyzer"); - } - - @Override - protected void runAction() { - MissionState ms = getModels().getMissionStateModel().getModelInstance(); - if (!m_reportedReady && ms.getInitialPose() != null) { - m_reportedReady = true; - BRASSHttpConnector.instance(Phases.Phase2).setClock(getModels().getMissionStateModel().getModelInstance()); - BRASSHttpConnector.instance(Phases.Phase2).reportReady(true); - m_wasOK = true; - } - if (getModels().getRainbowStateModel().getModelInstance().waitForIG()) { - m_wasOK = true; - return; - } - // Do the periodic analysis on the models of interest - InstructionGraphModelInstance ig = getModels().getInstructionGraphModel(); - - - if (ms.isMissionStarted() && ms.getInitialPose() != null) { - - boolean currentOK = ig.getModelInstance().getCurrentOK(); -// if (ig.getModelInstance().getInstructionGraphState() == IGExecutionStateT.FINISHED_SUCCESS && !m_reportedCompleted) { -// m_reportedCompleted = true; -// m_awaitingNewIG = true; -// SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory().setModelProblem(CP3ModelState.MISSION_COMPLETED); -// return; -// } - if (!currentOK && m_wasOK && !getModels().getRainbowStateModel().getModelInstance().waitForIG()) { - m_wasOK = false; - m_reportingPort.info(getComponentType(), "Instruction graph failed...updating map model"); - SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() - .setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); - SetModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() - .setModelProblem(CP3ModelState.IS_OBSTRUCTED); - m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); - m_awaitingNewIG = true; - } - else if (currentOK && !emptyInstructions(ig.getModelInstance()) && getModels().getRainbowStateModel().getModelInstance() - .getProblems().contains(RainbowState.CP3ModelState.IS_OBSTRUCTED)) { - // New IG resumed after robot obstructed - log("New instruction model was detected. Reseting models to ok"); - m_reportingPort.info(getComponentType(), "New instruction graph detected"); - m_awaitingNewIG = false; - getModels().getRainbowStateModel().getModelInstance().m_waitForIG = false; - // Clear robot obstructed flag - RemoveModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() - .removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); - RemoveModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() - .removeModelProblem(CP3ModelState.IS_OBSTRUCTED); - m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); - - } - } - - -// if (getModels().getInstructionGraphModel() == null) -// return; -// InstructionGraphProgress igModel = getModels().getInstructionGraphModel().getModelInstance(); -// boolean currentOK = igModel.getCurrentOK(); - -// org.sa.rainbow.brass.model.p2_cp3.mission.MissionState missionState = getModels().getMissionStateModel() -// .getModelInstance(); -// EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); -// if (missionState.getCurrentPose() == null) { -// m_awaitingPose = true; -// } else if (missionState.getCurrentPose() != null && m_awaitingPose) { -// m_awaitingPose = false; -// BRASSHttpConnector.instance(Phases.Phase2).reportReady(true); -// -// } else if (!currentOK && igModel.getExecutingInstruction() != null && !m_awaitingNewIG) { -// // Current IG failed -// m_reportingPort.info(getComponentType(), "Instruction graph failed...updating map model"); -// // BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.PERTURBATION_DETECTED, -// // "Obstruction to path detected"); -// // // Get current robot position -// // org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording pose -// // = missionState -// // .getCurrentPose(); -// // -// // // Get source and target positions of the failing instruction -// // IInstruction currentInst = igModel.getCurrentInstruction(); -// // -// // // The current instruction is of type MoveAbsH -// // insertNodeIntoMap(pose, currentInst); -// SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() -// .setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); -// SetModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() -// .setModelProblem(CP3ModelState.IS_OBSTRUCTED); -// m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); -// m_awaitingNewIG = true; -// } else if (currentOK && !emptyInstructions(igModel) && getModels().getRainbowStateModel().getModelInstance() -// .getProblems().contains(RainbowState.CP3ModelState.IS_OBSTRUCTED)) { -// // New IG resumed after robot obstructed -// log("New instruction model was detected. Reseting models to ok"); -// m_reportingPort.info(getComponentType(), "New instruction graph detected"); -// m_awaitingNewIG = false; -// getModels().getRainbowStateModel().getModelInstance().m_waitForIG = false; -// // Clear robot obstructed flag -// -// RemoveModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() -// .removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); -// RemoveModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() -// .removeModelProblem(CP3ModelState.IS_OBSTRUCTED); -// m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); -// -// } - - } - - boolean emptyInstructions(InstructionGraphProgress igProgress) { - return igProgress.getInstructions() == null || igProgress.getInstructions().isEmpty(); - } - -} +package org.sa.rainbow.brass.p3_cp1.analysis; + +import java.util.Arrays; + +import org.sa.rainbow.brass.das.BRASSHttpConnector; +import org.sa.rainbow.brass.das.IBRASSConnector.Phases; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.InsertNodeCmd; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RemoveModelProblemCmd; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.SetModelProblemCmd; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IRainbowReportingPort; + +/** + * Created by schmerl on 12/13/2016. Analyzes the current situation and triggers + * adaptation if necessary + */ +public class BRASSMissionAnalyzer extends P2CP1Analyzer { + + public static final String NAME = "BRASS Mission Evaluator"; + + private boolean m_reportedReady = false; + private boolean m_wasOK; + + private boolean m_awaitingNewIG; + + private boolean m_reportedCompleted; + + public BRASSMissionAnalyzer() { + super(NAME); + String per = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (per != null) { + setSleepTime(Long.parseLong(per)); + } else { + setSleepTime(IRainbowRunnable.LONG_SLEEP_TIME); + } + } + + @Override + public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize(port); + log("Initialized missions analyzer"); + } + + @Override + protected void runAction() { + MissionState ms = getModels().getMissionStateModel().getModelInstance(); + if (!m_reportedReady && ms.getInitialPose() != null) { + m_reportedReady = true; + BRASSHttpConnector.instance(Phases.Phase2).setClock(getModels().getMissionStateModel().getModelInstance()); + BRASSHttpConnector.instance(Phases.Phase2).reportReady(true); + m_wasOK = true; + } + if (getModels().getRainbowStateModel().getModelInstance().waitForIG()) { + m_wasOK = true; + return; + } + // Do the periodic analysis on the models of interest + InstructionGraphModelInstance ig = getModels().getInstructionGraphModel(); + + + if (ms.isMissionStarted() && ms.getInitialPose() != null) { + + boolean currentOK = ig.getModelInstance().getCurrentOK(); +// if (ig.getModelInstance().getInstructionGraphState() == IGExecutionStateT.FINISHED_SUCCESS && !m_reportedCompleted) { +// m_reportedCompleted = true; +// m_awaitingNewIG = true; +// SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory().setModelProblem(CP3ModelState.MISSION_COMPLETED); +// return; +// } + if (!currentOK && m_wasOK && !getModels().getRainbowStateModel().getModelInstance().waitForIG()) { + try { + m_wasOK = false; + m_reportingPort.info(getComponentType(), "Instruction graph failed...updating map model"); + SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() + .setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); + SetModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() + .setModelProblem(CP3ModelState.IS_OBSTRUCTED); + m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); + m_awaitingNewIG = true; + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + else if (currentOK && !emptyInstructions(ig.getModelInstance()) && getModels().getRainbowStateModel().getModelInstance() + .getProblems().contains(RainbowState.CP3ModelState.IS_OBSTRUCTED)) { + // New IG resumed after robot obstructed + try { + log("New instruction model was detected. Reseting models to ok"); + m_reportingPort.info(getComponentType(), "New instruction graph detected"); + m_awaitingNewIG = false; + getModels().getRainbowStateModel().getModelInstance().m_waitForIG = false; + // Clear robot obstructed flag + RemoveModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() + .removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); + RemoveModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() + .removeModelProblem(CP3ModelState.IS_OBSTRUCTED); + m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + } + + +// if (getModels().getInstructionGraphModel() == null) +// return; +// InstructionGraphProgress igModel = getModels().getInstructionGraphModel().getModelInstance(); +// boolean currentOK = igModel.getCurrentOK(); + +// org.sa.rainbow.brass.model.p2_cp3.mission.MissionState missionState = getModels().getMissionStateModel() +// .getModelInstance(); +// EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); +// if (missionState.getCurrentPose() == null) { +// m_awaitingPose = true; +// } else if (missionState.getCurrentPose() != null && m_awaitingPose) { +// m_awaitingPose = false; +// BRASSHttpConnector.instance(Phases.Phase2).reportReady(true); +// +// } else if (!currentOK && igModel.getExecutingInstruction() != null && !m_awaitingNewIG) { +// // Current IG failed +// m_reportingPort.info(getComponentType(), "Instruction graph failed...updating map model"); +// // BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.PERTURBATION_DETECTED, +// // "Obstruction to path detected"); +// // // Get current robot position +// // org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording pose +// // = missionState +// // .getCurrentPose(); +// // +// // // Get source and target positions of the failing instruction +// // IInstruction currentInst = igModel.getCurrentInstruction(); +// // +// // // The current instruction is of type MoveAbsH +// // insertNodeIntoMap(pose, currentInst); +// SetModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() +// .setModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); +// SetModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() +// .setModelProblem(CP3ModelState.IS_OBSTRUCTED); +// m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); +// m_awaitingNewIG = true; +// } else if (currentOK && !emptyInstructions(igModel) && getModels().getRainbowStateModel().getModelInstance() +// .getProblems().contains(RainbowState.CP3ModelState.IS_OBSTRUCTED)) { +// // New IG resumed after robot obstructed +// log("New instruction model was detected. Reseting models to ok"); +// m_reportingPort.info(getComponentType(), "New instruction graph detected"); +// m_awaitingNewIG = false; +// getModels().getRainbowStateModel().getModelInstance().m_waitForIG = false; +// // Clear robot obstructed flag +// +// RemoveModelProblemCmd cmd1 = getModels().getRainbowStateModel().getCommandFactory() +// .removeModelProblem(CP3ModelState.INSTRUCTION_GRAPH_FAILED); +// RemoveModelProblemCmd cmd2 = getModels().getRainbowStateModel().getCommandFactory() +// .removeModelProblem(CP3ModelState.IS_OBSTRUCTED); +// m_modelUSPort.updateModel(Arrays.asList(new IRainbowOperation[] { cmd1, cmd2 }), true); +// +// } + + } + + boolean emptyInstructions(InstructionGraphProgress igProgress) { + return igProgress.getInstructions() == null || igProgress.getInstructions().isEmpty(); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/EnergyConsumptionAnalyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/EnergyConsumptionAnalyzer.java index b23a7b33a..cdf043e93 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/EnergyConsumptionAnalyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/EnergyConsumptionAnalyzer.java @@ -1,143 +1,165 @@ -package org.sa.rainbow.brass.p3_cp1.analysis; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.sa.rainbow.brass.confsynthesis.Configuration; -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.brass.model.instructions.ChargeInstruction; -import org.sa.rainbow.brass.model.instructions.ForwardInstruction; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.instructions.SetConfigInstruction; -import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; -import org.sa.rainbow.brass.model.map.BatteryPredictor; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.EnvMapModelInstance; -import org.sa.rainbow.brass.model.map.MapTranslator; -import org.sa.rainbow.brass.model.mission.MissionStateModelInstance; -import org.sa.rainbow.brass.model.mission.MissionState.Heading; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; -import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IRainbowReportingPort; -import org.sa.rainbow.core.util.Pair; - -public class EnergyConsumptionAnalyzer extends P2CP1Analyzer { - public static final String NAME = "BRASS Accuracy Evaluator"; - private IInstruction m_prevAnalyzedAndPassedInstruction; - private SimpleConfigurationStore m_powerModel; - - public EnergyConsumptionAnalyzer() { - super(NAME); - } - - @Override - public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { - super.initialize(port); -// m_powerModel = new SimpleConfigurationStore(Rainbow.instance().allProperties()); - m_powerModel = getModels().getPowerModel().getModelInstance(); - m_powerModel.populate(); - } - - @Override - protected void runAction() { - if (getModels().getInstructionGraphModel() == null) - return; - // Need to work out how to wait for planner in CP1 -- is it - if (getModels().getRainbowStateModel().getModelInstance().waitForIG()) - return; - InstructionGraphProgress igModel = getModels().getInstructionGraphModel().getModelInstance(); - IInstruction currentInstruction = igModel.getCurrentInstruction(); - if (currentInstruction == m_prevAnalyzedAndPassedInstruction) - return; - - if (!(currentInstruction instanceof ChargeInstruction)) { - List remainingInstructions = igModel.getRemainingInstructions(); - double batteryCharge = -1; - try { - batteryCharge = getModels().getRobotStateModel().getModelInstance().getCharge(); - if (batteryCharge <= 0) { - IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() - .setModelProblem(CP3ModelState.OUT_OF_BATTERY); - m_modelUSPort.updateModel(op); - return; - } - } catch (IllegalStateException e) { - // Don't have battery information yet - return; - } - - // We need to break the instructions into chunks that are segmented by charge - // and then ask - // is there enough energy to get to each charge instruction or the target? - String tgtWP = getModels().getMissionStateModel().getModelInstance().getTargetWaypoint(); - List> segments = InstructionGraphProgress - .segmentByInstructionType(remainingInstructions, ChargeInstruction.class); - Iterator> it = segments.iterator(); - boolean first = true; - boolean hasEnoughEnergy = true; - EnergyConsumptionPredictor predictor = new EnergyConsumptionPredictor( - getModels().getEnvMapModel().getModelInstance(), - getModels().getMissionStateModel().getModelInstance(), m_powerModel); - predictor.setConfig(getModels().getRobotStateModel().getModelInstance().getConfigId()); - try { - while (it.hasNext()) { - if (first) { - first = false; - hasEnoughEnergy &= predictor.getPlanEnergyConsumption(currentInstruction, it.next(), - tgtWP) < batteryCharge; - } else { - hasEnoughEnergy &= predictor.getPlanEnergyConsumption(null, it.next(), - tgtWP) < MapTranslator.ROBOT_BATTERY_RANGE_MAX; - } - } - } catch (NullPointerException e) { - log("Could not yet analyze the instruction graph -- could be waypoints have not been set up"); - m_reportingPort.error(RainbowComponentT.ANALYSIS, e.getMessage(), e, LOGGER); - return; - } - // double planEnergyConsumption = hasEnoughEnergy(currentInstruction, - // remainingInstructions); - // boolean hasEnoughEnergy = batteryCharge >= planEnergyConsumption; - // log("Current charge = " + batteryCharge + ", needed charge = " + - // planEnergyConsumption); - if (hasEnoughEnergy) { - // Keep track of the latest instruction that we have analyzed the accuracy - // property, - // and it passed - m_prevAnalyzedAndPassedInstruction = currentInstruction; - } - boolean knowAboutLowBattery = getModels().getRainbowStateModel().getModelInstance().getProblems() - .contains(CP3ModelState.LOW_ON_BATTERY); - if (hasEnoughEnergy && knowAboutLowBattery) { - IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() - .removeModelProblem(CP3ModelState.LOW_ON_BATTERY); - m_modelUSPort.updateModel(op); - } else if (!hasEnoughEnergy && !knowAboutLowBattery) { - log("Do not have enough battery."); - LocationRecording pose = getModels().getMissionStateModel().getModelInstance().getCurrentPose(); - insertNodeIntoMap(pose, currentInstruction); - IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() - .setModelProblem(CP3ModelState.LOW_ON_BATTERY); - m_modelUSPort.updateModel(op); - - } - } else if (getModels().getRainbowStateModel().getModelInstance().getProblems() - .contains(CP3ModelState.LOW_ON_BATTERY)) { - IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() - .removeModelProblem(CP3ModelState.LOW_ON_BATTERY); - m_modelUSPort.updateModel(op); - } - } - -} +package org.sa.rainbow.brass.p3_cp1.analysis; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.sa.rainbow.brass.confsynthesis.Configuration; +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.brass.model.instructions.ChargeInstruction; +import org.sa.rainbow.brass.model.instructions.ForwardInstruction; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.InstructionGraphModelInstance; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.instructions.SetConfigInstruction; +import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; +import org.sa.rainbow.brass.model.map.BatteryPredictor; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.EnvMapModelInstance; +import org.sa.rainbow.brass.model.map.MapTranslator; +import org.sa.rainbow.brass.model.mission.MissionStateModelInstance; +import org.sa.rainbow.brass.model.mission.MissionState.Heading; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; +import org.sa.rainbow.brass.model.p2_cp3.rainbowState.RainbowState.CP3ModelState; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.util.Pair; + +public class EnergyConsumptionAnalyzer extends P2CP1Analyzer { + public static final String NAME = "BRASS Accuracy Evaluator"; + private IInstruction m_prevAnalyzedAndPassedInstruction; + private SimpleConfigurationStore m_powerModel; + + public EnergyConsumptionAnalyzer() { + super(NAME); + } + + @Override + public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize(port); +// m_powerModel = new SimpleConfigurationStore(Rainbow.instance().allProperties()); + m_powerModel = getModels().getPowerModel().getModelInstance(); + m_powerModel.populate(); + } + + @Override + protected void runAction() { + if (getModels().getInstructionGraphModel() == null) + return; + // Need to work out how to wait for planner in CP1 -- is it + if (getModels().getRainbowStateModel().getModelInstance().waitForIG()) + return; + InstructionGraphProgress igModel = getModels().getInstructionGraphModel().getModelInstance(); + IInstruction currentInstruction = igModel.getCurrentInstruction(); + if (currentInstruction == m_prevAnalyzedAndPassedInstruction) + return; + + if (!(currentInstruction instanceof ChargeInstruction)) { + log("Analyzing energy consumption"); + List remainingInstructions = igModel.getRemainingInstructions(); + double batteryCharge = -1; + try { + try { + batteryCharge = getModels().getRobotStateModel().getModelInstance().getCharge(); + if (batteryCharge <= 0) { + IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() + .setModelProblem(CP3ModelState.OUT_OF_BATTERY); + m_modelUSPort.updateModel(op); + return; + } + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } catch (IllegalStateException e) { + // Don't have battery information yet + return; + } + + // We need to break the instructions into chunks that are segmented by charge + // and then ask + // is there enough energy to get to each charge instruction or the target? + String tgtWP = getModels().getMissionStateModel().getModelInstance().getTargetWaypoint(); + List> segments = InstructionGraphProgress + .segmentByInstructionType(remainingInstructions, ChargeInstruction.class); + Iterator> it = segments.iterator(); + boolean first = true; + boolean hasEnoughEnergy = true; + EnergyConsumptionPredictor predictor = new EnergyConsumptionPredictor( + getModels().getEnvMapModel().getModelInstance(), + getModels().getMissionStateModel().getModelInstance(), m_powerModel); + predictor.setConfig(getModels().getRobotStateModel().getModelInstance().getConfigId()); + try { + while (it.hasNext()) { + if (first) { + first = false; + hasEnoughEnergy &= predictor.getPlanEnergyConsumption(currentInstruction, it.next(), + tgtWP) < batteryCharge; + } else { + hasEnoughEnergy &= predictor.getPlanEnergyConsumption(null, it.next(), + tgtWP) < MapTranslator.ROBOT_BATTERY_RANGE_MAX; + } + } + } catch (NullPointerException e) { + log("Could not yet analyze the instruction graph -- could be waypoints have not been set up"); + m_reportingPort.error(RainbowComponentT.ANALYSIS, e.getMessage(), e, LOGGER); + return; + } + // double planEnergyConsumption = hasEnoughEnergy(currentInstruction, + // remainingInstructions); + // boolean hasEnoughEnergy = batteryCharge >= planEnergyConsumption; + // log("Current charge = " + batteryCharge + ", needed charge = " + + // planEnergyConsumption); + if (hasEnoughEnergy) { + // Keep track of the latest instruction that we have analyzed the accuracy + // property, + // and it passed + m_prevAnalyzedAndPassedInstruction = currentInstruction; + } + boolean knowAboutLowBattery = getModels().getRainbowStateModel().getModelInstance().getProblems() + .contains(CP3ModelState.LOW_ON_BATTERY); + if (hasEnoughEnergy && knowAboutLowBattery) { + try { + IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() + .removeModelProblem(CP3ModelState.LOW_ON_BATTERY); + m_modelUSPort.updateModel(op); + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } else if (!hasEnoughEnergy && !knowAboutLowBattery) { + try { + log("Do not have enough battery."); + LocationRecording pose = getModels().getMissionStateModel().getModelInstance().getCurrentPose(); + insertNodeIntoMap(pose, currentInstruction); + IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() + .setModelProblem(CP3ModelState.LOW_ON_BATTERY); + m_modelUSPort.updateModel(op); + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + } else if (getModels().getRainbowStateModel().getModelInstance().getProblems() + .contains(CP3ModelState.LOW_ON_BATTERY)) { + try { + IRainbowOperation op = getModels().getRainbowStateModel().getCommandFactory() + .removeModelProblem(CP3ModelState.LOW_ON_BATTERY); + m_modelUSPort.updateModel(op); + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/EnergyConsumptionPredictor.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/EnergyConsumptionPredictor.java index a7ac48b7d..892c98a5f 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/EnergyConsumptionPredictor.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/EnergyConsumptionPredictor.java @@ -1,319 +1,319 @@ -package org.sa.rainbow.brass.p3_cp1.analysis; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.sa.rainbow.brass.confsynthesis.Configuration; -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.brass.model.instructions.ChargeInstruction; -import org.sa.rainbow.brass.model.instructions.ForwardInstruction; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.instructions.SetConfigInstruction; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.MapTranslator; -import org.sa.rainbow.brass.model.mission.MissionState.Heading; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.core.util.Pair; - -public class EnergyConsumptionPredictor { - private static final int GOAL_RADIUS = 50; // centimeters //TODO - - private EnvMap m_envMap; - private MissionState m_missionState; - private String m_config; - - private SimpleConfigurationStore m_powerModel; - - public EnergyConsumptionPredictor(EnvMap e, MissionState m, SimpleConfigurationStore powerModel) { - m_envMap = e; - m_missionState = m; - m_powerModel = powerModel; - } - - public void setConfig(String config) { - m_config = config; - } - - // TODO check the signature - public double getEnergyConsumption(Configuration config, double time) { - if(config == null) { - throw new IllegalArgumentException("The configuration cannot be null"); - } - - double powerLoad = config.getEnergyDischargeRate(); - - if(powerLoad <= 0.0) { - throw new IllegalArgumentException("The power load has to be greater than 0"); - } - - if(time == 0.0) { - throw new IllegalArgumentException("There are no more tasks to do"); - } - - if(time < 0.0) { - throw new IllegalArgumentException("The time to complete tasks cannot be negative"); - } - - - return this.getEnergyConsumption(powerLoad, time); - } - - /** - * Get the energy consumed in a given time period. - * - * @param powerLoad - * @param time - * @return - */ - public double getEnergyConsumption(double powerLoad, double time) { - if(powerLoad <= 0.0) { - throw new IllegalArgumentException("The power load has to be greater than 0"); - } - - if(time == 0.0) { - throw new IllegalArgumentException("There are no more tasks to do"); - } - - if(time < 0.0) { - throw new IllegalArgumentException("The time to complete tasks cannot be negative"); - } - - double energy = powerLoad * time; - return energy; - } - - /** - * Check if the task can be completed based on the energyConsumption that will be consumed and the current energyConsumption. - * - * @param curEnergy - * @param energyConsumed - * @return - */ - public boolean canCompleteTask(double curEnergy, double energyConsumed) { - if(curEnergy < 0.0) { - throw new IllegalArgumentException("The current energy cannot be less than 0"); - } - - if(curEnergy == 0.0) { - throw new IllegalArgumentException("The battery is empty"); - } - - if(energyConsumed <= 0.0) { - throw new IllegalArgumentException("The energy consumed has to be greater than 0"); - } - - return curEnergy >= energyConsumed; - } - - /** - * Checks if the instructions can be completed with the remaining energy - */ - public double getPlanEnergyConsumption (IInstruction currentInstruction, List remainingInstructions, String tgtWP) { - double planEnergyConsumption = getExpectedIGEnergyConsumption(currentInstruction, remainingInstructions, tgtWP); - return planEnergyConsumption; - } - - private double getExpectedIGEnergyConsumption(IInstruction currentInstruction, List remainingInstructions, String tgtWP) { - double totalEnergy = 0; - - // Goal location - double goalX = m_envMap.getNodeX(m_missionState.getTargetWaypoint()); - double goalY = m_envMap.getNodeY(m_missionState.getTargetWaypoint()); - if (goalX == Double.NEGATIVE_INFINITY || goalY == Double.NEGATIVE_INFINITY) return 0; - - double sourceX = m_missionState.getCurrentPose().getX(); - double sourceY = m_missionState.getCurrentPose().getY(); - double sourceW = m_missionState.getCurrentPose().getRotation(); - - List allInstructions = new ArrayList<>(); - if (currentInstruction != null) allInstructions.add(currentInstruction); - allInstructions.addAll(remainingInstructions); - int i = 0; - for (IInstruction instruction : allInstructions) { - double instEnergy = 0; - - // Special case: for the last instruction, only calculate the energy required to get - // within a certain radius from the goal location - if (i == allInstructions.size() - 1 && instruction instanceof MoveAbsHInstruction && (((MoveAbsHInstruction )instruction).getTargetWaypoint().equals(tgtWP))) { - // For MoveAbsH, use the target location that is GOAL_RADIUS from the goal, and is nearest the source - Pair targetLocation = getNearestTargetLocation(sourceX, sourceY, goalX, goalY, GOAL_RADIUS); - double targetX = targetLocation.firstValue(); - double targetY = targetLocation.secondValue(); - - MoveAbsHInstruction moveAbsH = (MoveAbsHInstruction) instruction; - String newMoveAbsH = - MessageFormat.format ( - "MoveAbsH({0,number,##.##}, {1,number,##.##}, {2,number,##.##}, {3,number,##.###})", - targetX, targetY, moveAbsH.getSpeed (), moveAbsH.getTargetW ()); -// String.format("MoveAbsH(%d, %d, %d, %d)", targetX, targetY, moveAbsH.getSpeed(), moveAbsH.getTargetW()); - MoveAbsHInstruction moveAbsHCopy = - new MoveAbsHInstruction(moveAbsH.getInstructionLabel(), newMoveAbsH, moveAbsH.getNextInstructionLabel()); - instEnergy = getMoveAbsHEnergyConsumption(moveAbsHCopy, sourceX, sourceY, sourceW, m_config); - - } else if (i == allInstructions.size() - 1 && instruction instanceof ForwardInstruction) { - // For Forward, use the distance that is GOAL_RADIUS shorter than the original distance - ForwardInstruction forward = (ForwardInstruction) instruction; - String newForward = MessageFormat.format ("Forward({0,number,##.##}, {1,number,##.##})", - forward.getDistance () - GOAL_RADIUS, forward.getSpeed ()); -// String.format("Forward(%d, %d)", forward.getDistance() - GOAL_RADIUS, forward.getSpeed()); - ForwardInstruction forwardCopy = - new ForwardInstruction(forward.getInstructionLabel(), newForward, forward.getNextInstructionLabel()); - instEnergy = getForwardEnergyConsumption(forwardCopy, sourceX, sourceY, sourceW, m_config); - - } else if (instruction instanceof MoveAbsHInstruction) { - MoveAbsHInstruction moveAbsH = (MoveAbsHInstruction) instruction; - instEnergy = getMoveAbsHEnergyConsumption(moveAbsH, sourceX, sourceY, sourceW, m_config); - - // Update source pose for the next instruction - sourceX = moveAbsH.getTargetX();; - sourceY = moveAbsH.getTargetY(); - sourceW = moveAbsH.getTargetW(); - } else if (instruction instanceof ForwardInstruction) { - ForwardInstruction forward = (ForwardInstruction) instruction; - instEnergy = getForwardEnergyConsumption(forward, sourceX, sourceY, sourceW, m_config); - - // Update source pose for the next instruction - sourceX = sourceX + forward.getDistance() * Math.cos(sourceW);; - sourceY = sourceY + forward.getDistance() * Math.sin(sourceW); - } else if (instruction instanceof ChargeInstruction) { - // This should not happen because we should segment on Charges - // double energyGain = bp.batteryCharge(charge.getChargingTime()); - // Charge should be refilling the battery, and so totalEnergy consumed - // should be reset to 0 (i.e., after this instruction we have - - } - else if (instruction instanceof SetConfigInstruction) { - SetConfigInstruction configI = (SetConfigInstruction) instruction; - m_config = configI.getConfig(); - } else { - // This instruction doesn't consume or produce energy - instEnergy = 0; - } - - totalEnergy += instEnergy; - i++; - } - - return totalEnergy; - } - - /** - * Finds the nearest (x, y) location to the source location that is a given distance away from the goal. - */ - private Pair getNearestTargetLocation(double sourceX, double sourceY, - double goalX, double goalY, double buffer) { - double lowerBoundX = goalX - buffer; - double upperBoundX = goalX + buffer; - double lowerBoundY = goalY - buffer; - double upperBoundY = goalY + buffer; - - List targetXs = new ArrayList<>(); - List targetYs = new ArrayList<>(); - targetXs.add(goalX); - targetYs.add(upperBoundY); - targetXs.add(upperBoundX); - targetYs.add(goalY); - targetXs.add(goalX); - targetYs.add(lowerBoundY); - targetXs.add(lowerBoundX); - targetYs.add(goalY); - - List manhattanDistances = new ArrayList<>(); - manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(0), targetXs.get(0))); - manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(1), targetXs.get(1))); - manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(2), targetXs.get(2))); - manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(3), targetXs.get(3))); - int minIndex = manhattanDistances.indexOf(Collections.min(manhattanDistances)); - double targetX = targetXs.get(minIndex); - double targetY = targetYs.get(minIndex); - Pair targetLocation = new Pair(targetX, targetY); - return targetLocation; - } - - private double getManhattanDistance(double sourceX, double sourceY, double targetX, double targetY) { - return Math.abs(sourceX - targetX) + Math.abs(sourceY - targetY); - } - - /** - * Calculates the energy consumption of MoveAbs(x, y, v, w) - */ - private double getMoveAbsHEnergyConsumption(MoveAbsHInstruction moveAbsH, double sourceX, double sourceY, double sourceW, String config) { - double targetX = moveAbsH.getTargetX(); - double targetY = moveAbsH.getTargetY(); - double targetW = moveAbsH.getTargetW(); - double moveSpeed = moveAbsH.getSpeed(); - double rotateSpeed = MapTranslator.ROBOT_ROTATIONAL_SPEED_VALUE; - - - double moveAbsHEnergy = getMovementEnergyConsumption (false, sourceX, sourceY, sourceW, targetX, targetY, - targetW, - moveSpeed, rotateSpeed, config); - return moveAbsHEnergy; - } - - /** - * Calculates the energy consumption of Forward(d, v) - */ - private double getForwardEnergyConsumption(ForwardInstruction forward, double sourceX, double sourceY, double sourceW, String config) { - double distance = forward.getDistance(); - double speed = forward.getSpeed(); - // Approximate target location - // Assume that the current location is close to the location where this Forward command was issued - // TODO: ensure this - double targetX = sourceX + distance * Math.cos(sourceW); - double targetY = sourceY + distance * Math.sin(sourceW); - double forwardEnergy = getMovementEnergyConsumption(false, sourceX, sourceY, sourceW, targetX, targetY, sourceW, - speed, 0, config); - return forwardEnergy; - } - - /** - * Calculates the energy consumption of a movement - */ - private double getMovementEnergyConsumption(boolean isManhattanDistance, - double sourceX, double sourceY, double sourceW, - double targetX, double targetY, double targetW, - double moveSpeed, double rotateSpeed, String config) { - String moveSpeedStr; - - if (moveSpeed == (double )MapTranslator.ROBOT_HALF_SPEED_VALUE) { - moveSpeedStr = MapTranslator.ROBOT_HALF_SPEED_CONST; - } else if (moveSpeed == (double )MapTranslator.ROBOT_FULL_SPEED_VALUE) { - moveSpeedStr = MapTranslator.ROBOT_FULL_SPEED_CONST; - } else { - moveSpeedStr = MapTranslator.ROBOT_HALF_SPEED_CONST; - } - - double distance; - if (isManhattanDistance) { - // Manhattan distance - distance = Math.abs(sourceX - targetX) + Math.abs(sourceY - targetY); - } else { - // Euclidean distance - distance = Math.sqrt(Math.pow(sourceX - targetX, 2) + Math.pow(sourceY - targetY, 2)); - } - - // Energy consumed by straight move - Configuration configuration = m_powerModel.getConfiguration(config); - double moveEnergy = - getEnergyConsumption(configuration, distance/configuration.getSpeed()); - - double instEnergy = moveEnergy; - - boolean rotating = Heading.convertFromRadians(sourceW) != Heading.convertFromRadians(targetW); - - // Energy consumed by rotation, if any - if (rotating) { - double abs = Math.abs(sourceW - targetW); - abs = (abs > Math.PI) ? 2 * Math.PI - abs : abs; - double rotateTime = abs / rotateSpeed; - double rotateEnergy = getEnergyConsumption(configuration, rotateTime); - instEnergy += rotateEnergy; - } - - return instEnergy; - } - +package org.sa.rainbow.brass.p3_cp1.analysis; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.sa.rainbow.brass.confsynthesis.Configuration; +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.brass.model.instructions.ChargeInstruction; +import org.sa.rainbow.brass.model.instructions.ForwardInstruction; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.instructions.SetConfigInstruction; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.MapTranslator; +import org.sa.rainbow.brass.model.mission.MissionState.Heading; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.core.util.Pair; + +public class EnergyConsumptionPredictor { + private static final int GOAL_RADIUS = 50; // centimeters //TODO + + private EnvMap m_envMap; + private MissionState m_missionState; + private String m_config; + + private SimpleConfigurationStore m_powerModel; + + public EnergyConsumptionPredictor(EnvMap e, MissionState m, SimpleConfigurationStore powerModel) { + m_envMap = e; + m_missionState = m; + m_powerModel = powerModel; + } + + public void setConfig(String config) { + m_config = config; + } + + // TODO check the signature + public double getEnergyConsumption(Configuration config, double time) { + if(config == null) { + throw new IllegalArgumentException("The configuration cannot be null"); + } + + double powerLoad = config.getEnergyDischargeRate(); + + if(powerLoad <= 0.0) { + throw new IllegalArgumentException("The power load has to be greater than 0"); + } + + if(time == 0.0) { + throw new IllegalArgumentException("There are no more tasks to do"); + } + + if(time < 0.0) { + throw new IllegalArgumentException("The time to complete tasks cannot be negative"); + } + + + return this.getEnergyConsumption(powerLoad, time); + } + + /** + * Get the energy consumed in a given time period. + * + * @param powerLoad + * @param time + * @return + */ + public double getEnergyConsumption(double powerLoad, double time) { + if(powerLoad <= 0.0) { + throw new IllegalArgumentException("The power load has to be greater than 0"); + } + + if(time == 0.0) { + throw new IllegalArgumentException("There are no more tasks to do"); + } + + if(time < 0.0) { + throw new IllegalArgumentException("The time to complete tasks cannot be negative"); + } + + double energy = powerLoad * time; + return energy; + } + + /** + * Check if the task can be completed based on the energyConsumption that will be consumed and the current energyConsumption. + * + * @param curEnergy + * @param energyConsumed + * @return + */ + public boolean canCompleteTask(double curEnergy, double energyConsumed) { + if(curEnergy < 0.0) { + throw new IllegalArgumentException("The current energy cannot be less than 0"); + } + + if(curEnergy == 0.0) { + throw new IllegalArgumentException("The battery is empty"); + } + + if(energyConsumed <= 0.0) { + throw new IllegalArgumentException("The energy consumed has to be greater than 0"); + } + + return curEnergy >= energyConsumed; + } + + /** + * Checks if the instructions can be completed with the remaining energy + */ + public double getPlanEnergyConsumption (IInstruction currentInstruction, List remainingInstructions, String tgtWP) { + double planEnergyConsumption = getExpectedIGEnergyConsumption(currentInstruction, remainingInstructions, tgtWP); + return planEnergyConsumption; + } + + private double getExpectedIGEnergyConsumption(IInstruction currentInstruction, List remainingInstructions, String tgtWP) { + double totalEnergy = 0; + + // Goal location + double goalX = m_envMap.getNodeX(m_missionState.getTargetWaypoint()); + double goalY = m_envMap.getNodeY(m_missionState.getTargetWaypoint()); + if (goalX == Double.NEGATIVE_INFINITY || goalY == Double.NEGATIVE_INFINITY) return 0; + + double sourceX = m_missionState.getCurrentPose().getX(); + double sourceY = m_missionState.getCurrentPose().getY(); + double sourceW = m_missionState.getCurrentPose().getRotation(); + + List allInstructions = new ArrayList<>(); + if (currentInstruction != null) allInstructions.add(currentInstruction); + allInstructions.addAll(remainingInstructions); + int i = 0; + for (IInstruction instruction : allInstructions) { + double instEnergy = 0; + + // Special case: for the last instruction, only calculate the energy required to get + // within a certain radius from the goal location + if (i == allInstructions.size() - 1 && instruction instanceof MoveAbsHInstruction && (((MoveAbsHInstruction )instruction).getTargetWaypoint().equals(tgtWP))) { + // For MoveAbsH, use the target location that is GOAL_RADIUS from the goal, and is nearest the source + Pair targetLocation = getNearestTargetLocation(sourceX, sourceY, goalX, goalY, GOAL_RADIUS); + double targetX = targetLocation.firstValue(); + double targetY = targetLocation.secondValue(); + + MoveAbsHInstruction moveAbsH = (MoveAbsHInstruction) instruction; + String newMoveAbsH = + MessageFormat.format ( + "MoveAbsH({0,number,##.##}, {1,number,##.##}, {2,number,##.##}, {3,number,##.###})", + targetX, targetY, moveAbsH.getSpeed (), moveAbsH.getTargetW ()); +// String.format("MoveAbsH(%d, %d, %d, %d)", targetX, targetY, moveAbsH.getSpeed(), moveAbsH.getTargetW()); + MoveAbsHInstruction moveAbsHCopy = + new MoveAbsHInstruction(moveAbsH.getInstructionLabel(), newMoveAbsH, moveAbsH.getNextInstructionLabel()); + instEnergy = getMoveAbsHEnergyConsumption(moveAbsHCopy, sourceX, sourceY, sourceW, m_config); + + } else if (i == allInstructions.size() - 1 && instruction instanceof ForwardInstruction) { + // For Forward, use the distance that is GOAL_RADIUS shorter than the original distance + ForwardInstruction forward = (ForwardInstruction) instruction; + String newForward = MessageFormat.format ("Forward({0,number,##.##}, {1,number,##.##})", + forward.getDistance () - GOAL_RADIUS, forward.getSpeed ()); +// String.format("Forward(%d, %d)", forward.getDistance() - GOAL_RADIUS, forward.getSpeed()); + ForwardInstruction forwardCopy = + new ForwardInstruction(forward.getInstructionLabel(), newForward, forward.getNextInstructionLabel()); + instEnergy = getForwardEnergyConsumption(forwardCopy, sourceX, sourceY, sourceW, m_config); + + } else if (instruction instanceof MoveAbsHInstruction) { + MoveAbsHInstruction moveAbsH = (MoveAbsHInstruction) instruction; + instEnergy = getMoveAbsHEnergyConsumption(moveAbsH, sourceX, sourceY, sourceW, m_config); + + // Update source pose for the next instruction + sourceX = moveAbsH.getTargetX();; + sourceY = moveAbsH.getTargetY(); + sourceW = moveAbsH.getTargetW(); + } else if (instruction instanceof ForwardInstruction) { + ForwardInstruction forward = (ForwardInstruction) instruction; + instEnergy = getForwardEnergyConsumption(forward, sourceX, sourceY, sourceW, m_config); + + // Update source pose for the next instruction + sourceX = sourceX + forward.getDistance() * Math.cos(sourceW);; + sourceY = sourceY + forward.getDistance() * Math.sin(sourceW); + } else if (instruction instanceof ChargeInstruction) { + // This should not happen because we should segment on Charges + // double energyGain = bp.batteryCharge(charge.getChargingTime()); + // Charge should be refilling the battery, and so totalEnergy consumed + // should be reset to 0 (i.e., after this instruction we have + + } + else if (instruction instanceof SetConfigInstruction) { + SetConfigInstruction configI = (SetConfigInstruction) instruction; + m_config = configI.getConfig(); + } else { + // This instruction doesn't consume or produce energy + instEnergy = 0; + } + + totalEnergy += instEnergy; + i++; + } + + return totalEnergy; + } + + /** + * Finds the nearest (x, y) location to the source location that is a given distance away from the goal. + */ + private Pair getNearestTargetLocation(double sourceX, double sourceY, + double goalX, double goalY, double buffer) { + double lowerBoundX = goalX - buffer; + double upperBoundX = goalX + buffer; + double lowerBoundY = goalY - buffer; + double upperBoundY = goalY + buffer; + + List targetXs = new ArrayList<>(); + List targetYs = new ArrayList<>(); + targetXs.add(goalX); + targetYs.add(upperBoundY); + targetXs.add(upperBoundX); + targetYs.add(goalY); + targetXs.add(goalX); + targetYs.add(lowerBoundY); + targetXs.add(lowerBoundX); + targetYs.add(goalY); + + List manhattanDistances = new ArrayList<>(); + manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(0), targetXs.get(0))); + manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(1), targetXs.get(1))); + manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(2), targetXs.get(2))); + manhattanDistances.add(getManhattanDistance(sourceX, sourceY, targetXs.get(3), targetXs.get(3))); + int minIndex = manhattanDistances.indexOf(Collections.min(manhattanDistances)); + double targetX = targetXs.get(minIndex); + double targetY = targetYs.get(minIndex); + Pair targetLocation = new Pair(targetX, targetY); + return targetLocation; + } + + private double getManhattanDistance(double sourceX, double sourceY, double targetX, double targetY) { + return Math.abs(sourceX - targetX) + Math.abs(sourceY - targetY); + } + + /** + * Calculates the energy consumption of MoveAbs(x, y, v, w) + */ + private double getMoveAbsHEnergyConsumption(MoveAbsHInstruction moveAbsH, double sourceX, double sourceY, double sourceW, String config) { + double targetX = moveAbsH.getTargetX(); + double targetY = moveAbsH.getTargetY(); + double targetW = moveAbsH.getTargetW(); + double moveSpeed = moveAbsH.getSpeed(); + double rotateSpeed = MapTranslator.ROBOT_ROTATIONAL_SPEED_VALUE; + + + double moveAbsHEnergy = getMovementEnergyConsumption (false, sourceX, sourceY, sourceW, targetX, targetY, + targetW, + moveSpeed, rotateSpeed, config); + return moveAbsHEnergy; + } + + /** + * Calculates the energy consumption of Forward(d, v) + */ + private double getForwardEnergyConsumption(ForwardInstruction forward, double sourceX, double sourceY, double sourceW, String config) { + double distance = forward.getDistance(); + double speed = forward.getSpeed(); + // Approximate target location + // Assume that the current location is close to the location where this Forward command was issued + // TODO: ensure this + double targetX = sourceX + distance * Math.cos(sourceW); + double targetY = sourceY + distance * Math.sin(sourceW); + double forwardEnergy = getMovementEnergyConsumption(false, sourceX, sourceY, sourceW, targetX, targetY, sourceW, + speed, 0, config); + return forwardEnergy; + } + + /** + * Calculates the energy consumption of a movement + */ + private double getMovementEnergyConsumption(boolean isManhattanDistance, + double sourceX, double sourceY, double sourceW, + double targetX, double targetY, double targetW, + double moveSpeed, double rotateSpeed, String config) { + String moveSpeedStr; + + if (moveSpeed == (double )MapTranslator.ROBOT_HALF_SPEED_VALUE) { + moveSpeedStr = MapTranslator.ROBOT_HALF_SPEED_CONST; + } else if (moveSpeed == (double )MapTranslator.ROBOT_FULL_SPEED_VALUE) { + moveSpeedStr = MapTranslator.ROBOT_FULL_SPEED_CONST; + } else { + moveSpeedStr = MapTranslator.ROBOT_HALF_SPEED_CONST; + } + + double distance; + if (isManhattanDistance) { + // Manhattan distance + distance = Math.abs(sourceX - targetX) + Math.abs(sourceY - targetY); + } else { + // Euclidean distance + distance = Math.sqrt(Math.pow(sourceX - targetX, 2) + Math.pow(sourceY - targetY, 2)); + } + + // Energy consumed by straight move + Configuration configuration = m_powerModel.getConfiguration(config); + double moveEnergy = + getEnergyConsumption(configuration, distance/configuration.getSpeed()); + + double instEnergy = moveEnergy; + + boolean rotating = Heading.convertFromRadians(sourceW) != Heading.convertFromRadians(targetW); + + // Energy consumed by rotation, if any + if (rotating) { + double abs = Math.abs(sourceW - targetW); + abs = (abs > Math.PI) ? 2 * Math.PI - abs : abs; + double rotateTime = abs / rotateSpeed; + double rotateEnergy = getEnergyConsumption(configuration, rotateTime); + instEnergy += rotateEnergy; + } + + return instEnergy; + } + } \ No newline at end of file diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/MapResetter.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/MapResetter.java new file mode 100644 index 000000000..b6712be89 --- /dev/null +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/MapResetter.java @@ -0,0 +1,60 @@ +package org.sa.rainbow.brass.p3_cp1.analysis; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress.IGExecutionStateT; +import org.sa.rainbow.brass.model.map.EnvMapLoadCmd; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.util.Util; + +public class MapResetter extends P2CP1Analyzer { + + private static final String NAME = "Map Resetter"; + private boolean m_isReset = false; + private File m_modelPath; + + public MapResetter() { + super(NAME); + setSleepTime(3000); + } + + @Override + public void initialize(IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize(port); + String path = Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_PATH_PREFIX + "5"); + m_modelPath = null; + if (path != null) { + m_modelPath = new File(path); + if (!m_modelPath.isAbsolute()) { + m_modelPath = Util.getRelativeToPath(Rainbow.instance().getTargetPath(), path); + } + + } + } + + @Override + protected void runAction() { + IGExecutionStateT state = getModels().getInstructionGraphModel().getModelInstance().getInstructionGraphState(); + if (state == IGExecutionStateT.FINISHED_SUCCESS && !m_isReset) { + log("Resetting map because it is the end of a task"); + try { + getModels().getEnvMapModel().getModelInstance().reload(); + log("Map reloaded"); + } catch (IllegalStateException e) { + m_reportingPort.error(getComponentType(), "Failed to reload environment", e); + e.printStackTrace(); + } + } else if (state != IGExecutionStateT.FINISHED_SUCCESS && m_isReset) { + m_isReset = false; + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/P2CP1Analyzer.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/P2CP1Analyzer.java index 50f67b02a..333cf63dc 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/P2CP1Analyzer.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/analysis/P2CP1Analyzer.java @@ -1,92 +1,92 @@ -package org.sa.rainbow.brass.p3_cp1.analysis; - -import org.sa.rainbow.brass.analyses.P2Analyzer; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.InsertNodeCmd; -import org.sa.rainbow.brass.p3_cp1.model.CP1ModelAccessor; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; -import org.sa.rainbow.core.error.RainbowConnectionException; - -public abstract class P2CP1Analyzer extends P2Analyzer { - public P2CP1Analyzer(String name) { - super(name); - } - - private CP1ModelAccessor m_modelAccessor; - - @Override - public void initializeConnections() throws RainbowConnectionException { - super.initializeConnections(); - m_modelAccessor = new CP1ModelAccessor(m_modelsManagerPort); - } - - protected CP1ModelAccessor getModels () { - return m_modelAccessor; - } - - private MoveAbsHInstruction getPreviousMoveAbsH(MoveAbsHInstruction currentMoveAbsH) { - int j = Integer.valueOf (currentMoveAbsH.getInstructionLabel ()) - 1; - for (int i = j; i > 0; i--) { - String label = String.valueOf (i); - IInstruction instruction = getModels().getInstructionGraphModel().getModelInstance().getInstruction (label); - - if (instruction instanceof MoveAbsHInstruction) return (MoveAbsHInstruction )instruction; - } - - // No previous MoveAbsH instruction - return null; - } - - protected void insertNodeIntoMap(LocationRecording pose, IInstruction currentInst) { - if (currentInst instanceof MoveAbsHInstruction) { - MoveAbsHInstruction currentMoveAbsH = (MoveAbsHInstruction )currentInst; - MoveAbsHInstruction prevMoveAbsH = getPreviousMoveAbsH (currentMoveAbsH); - - double sourceX; - double sourceY; - double targetX = currentMoveAbsH.getTargetX (); - double targetY = currentMoveAbsH.getTargetY (); - - if (prevMoveAbsH != null) { - sourceX = prevMoveAbsH.getTargetX (); - sourceY = prevMoveAbsH.getTargetY (); - } - else { - // The current instruction is the first MoveAbsH instruction in IG - // Use the initial pose as the source pose - LocationRecording initialPose = getModels().getMissionStateModel().getModelInstance().getInitialPose (); - sourceX = initialPose.getX (); - sourceY = initialPose.getY (); - } - - // Find the corresponding environment map nodes of the source and target positions - // Node naming assumption: node's label is lX where X is the order in which the node is added - EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); - int numNodes = envMap.getNodeCount () + 1; - String n = "l" + numNodes; - String na = envMap.getNode (sourceX, sourceY).getLabel (); - String nb = envMap.getNode (targetX, targetY).getLabel (); - - // Update the environment map - String rx = Double.toString (pose.getX ()); - String ry = Double.toString (pose.getY ()); - - InsertNodeCmd insertNodeCmd = getModels().getEnvMapModel().getCommandFactory ().insertNodeCmd (n, na, nb, - rx, ry, "false"); - log ("Inserting node '" + n + "' at (" + rx + ", " + ry + ") between " + na + " and " - + nb); - - SetExecutionFailedCmd resetFailedCmd = getModels().getInstructionGraphModel().getCommandFactory () - .setExecutionFailedCmd ("false"); - - - // Send the commands -- different models, so can't bundle them - m_modelUSPort.updateModel (resetFailedCmd); - m_modelUSPort.updateModel (insertNodeCmd); - } - } - -} +package org.sa.rainbow.brass.p3_cp1.analysis; + +import org.sa.rainbow.brass.analyses.P2Analyzer; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.instructions.SetExecutionFailedCmd; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.InsertNodeCmd; +import org.sa.rainbow.brass.p3_cp1.model.CP1ModelAccessor; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState.LocationRecording; +import org.sa.rainbow.core.error.RainbowConnectionException; + +public abstract class P2CP1Analyzer extends P2Analyzer { + public P2CP1Analyzer(String name) { + super(name); + } + + private CP1ModelAccessor m_modelAccessor; + + @Override + public void initializeConnections() throws RainbowConnectionException { + super.initializeConnections(); + m_modelAccessor = new CP1ModelAccessor(m_modelsManagerPort); + } + + protected CP1ModelAccessor getModels () { + return m_modelAccessor; + } + + private MoveAbsHInstruction getPreviousMoveAbsH(MoveAbsHInstruction currentMoveAbsH) { + int j = Integer.valueOf (currentMoveAbsH.getInstructionLabel ()) - 1; + for (int i = j; i > 0; i--) { + String label = String.valueOf (i); + IInstruction instruction = getModels().getInstructionGraphModel().getModelInstance().getInstruction (label); + + if (instruction instanceof MoveAbsHInstruction) return (MoveAbsHInstruction )instruction; + } + + // No previous MoveAbsH instruction + return null; + } + + protected void insertNodeIntoMap(LocationRecording pose, IInstruction currentInst) { + if (currentInst instanceof MoveAbsHInstruction) { + MoveAbsHInstruction currentMoveAbsH = (MoveAbsHInstruction )currentInst; + MoveAbsHInstruction prevMoveAbsH = getPreviousMoveAbsH (currentMoveAbsH); + + double sourceX; + double sourceY; + double targetX = currentMoveAbsH.getTargetX (); + double targetY = currentMoveAbsH.getTargetY (); + + if (prevMoveAbsH != null) { + sourceX = prevMoveAbsH.getTargetX (); + sourceY = prevMoveAbsH.getTargetY (); + } + else { + // The current instruction is the first MoveAbsH instruction in IG + // Use the initial pose as the source pose + LocationRecording initialPose = getModels().getMissionStateModel().getModelInstance().getInitialPose (); + sourceX = initialPose.getX (); + sourceY = initialPose.getY (); + } + + // Find the corresponding environment map nodes of the source and target positions + // Node naming assumption: node's label is lX where X is the order in which the node is added + EnvMap envMap = getModels().getEnvMapModel().getModelInstance(); + int numNodes = envMap.getNodeCount () + 1; + String n = "l" + numNodes; + String na = envMap.getNode (sourceX, sourceY).getLabel (); + String nb = envMap.getNode (targetX, targetY).getLabel (); + + // Update the environment map + String rx = Double.toString (pose.getX ()); + String ry = Double.toString (pose.getY ()); + + InsertNodeCmd insertNodeCmd = getModels().getEnvMapModel().getCommandFactory ().insertNodeCmd (n, na, nb, + rx, ry, "false"); + log ("Inserting node '" + n + "' at (" + rx + ", " + ry + ") between " + na + " and " + + nb); + + SetExecutionFailedCmd resetFailedCmd = getModels().getInstructionGraphModel().getCommandFactory () + .setExecutionFailedCmd ("false"); + + + // Send the commands -- different models, so can't bundle them + m_modelUSPort.updateModel (resetFailedCmd); + m_modelUSPort.updateModel (insertNodeCmd); + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/MissionStateGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/MissionStateGauge.java index 0621ccfb2..3aadb016b 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/MissionStateGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/MissionStateGauge.java @@ -1,126 +1,126 @@ -package org.sa.rainbow.brass.p3_cp1.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.brass.model.map.BatteryPredictor; -import org.sa.rainbow.brass.model.map.MapTranslator; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.translator.probes.IProbeIdentifier; - -/** - * Created by schmerl on 12/28/2016. - */ -public class MissionStateGauge extends RegularPatternGauge { - private static final String NAME = "Mission State Gauge"; - protected static final String LOC = "LocationRecording"; - - protected static final String LOC_PATTERN = "topic: /amcl_pose/pose/pose.*position.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z.*\\norientation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z: (.*)\\n.*w: (.*)(.*)"; - protected String last_x; - protected String last_y; - private String last_w; - - /** - * Main Constructor the Gauge that is hardwired to the Probe. - * - * @param id - * the unique ID of the Gauge - * @param beaconPeriod - * the liveness beacon period of the Gauge - * @param gaugeDesc - * the type-name description of the Gauge - * @param modelDesc - * the type-name description of the Model the Gauge updates - * @param setupParams - * the list of setup parameters with their values - * @param mappings - * the list of Gauge Value to Model Property mappings - */ - public MissionStateGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern (LOC, Pattern.compile (LOC_PATTERN, Pattern.DOTALL)); - } - - @Override - protected void doMatch (String matchName, Matcher m) { - String group = m.group (1); - int restGroup = 0; - if (LOC.equals (matchName)) { - String x = group.trim (); - String y = m.group (2).trim (); - - String a = m.group (3).trim (); - String b = m.group (4).trim (); - String c = m.group (5).trim (); - String d = m.group (6).trim (); - restGroup = 7; - - String w = yawFromQuarternion (a, b, c, d); - - if (locationDifferent (x, y, w)) { - IRainbowOperation op = m_commands.get ("location"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], x); - pMap.put (op.getParameters ()[1], y); - pMap.put (op.getParameters ()[2], w); - issueCommand (op, pMap); - } - } - if (m.groupCount () == restGroup) { - String rest = m.group (restGroup); - if (!rest.isEmpty () && rest.indexOf ("topic:") != -1) { - log ("Gauge had more: " + rest.substring (rest.indexOf ("topic:"))); - } - } - } - - @Override - public void reportFromProbe(IProbeIdentifier probe, String data) { - // TODO Auto-generated method stub - super.reportFromProbe(probe, data); - } - - private boolean numberCheck (String[] vals) { - for (String s : vals) { - try { - Double.parseDouble (s); - } - catch (NumberFormatException e) { - return false; - } - } - return true; - } - - // Converstino to yaw from http://www.chrobotics.com/library/understanding-quaternions - private String yawFromQuarternion (String a, String b, String c, String d) { - double A = Double.parseDouble (a); - double B = Double.parseDouble (b); - double C = Double.parseDouble (c); - double D = Double.parseDouble (d); - - double w = Math.atan ((2 * (A * B + C * D)) / (A * A - B * B - C * C + D * D)); - return Double.toString (w); - - } - - private boolean locationDifferent (String x, String y, String w) { - boolean different = !x.equals (last_x) || !y.equals (last_y) || !w.equals (last_w); - if (different) { - last_x = x; - last_y = y; - last_w = w; - } - return different; - } -} +package org.sa.rainbow.brass.p3_cp1.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.brass.model.map.BatteryPredictor; +import org.sa.rainbow.brass.model.map.MapTranslator; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.translator.probes.IProbeIdentifier; + +/** + * Created by schmerl on 12/28/2016. + */ +public class MissionStateGauge extends RegularPatternGauge { + private static final String NAME = "Mission State Gauge"; + protected static final String LOC = "LocationRecording"; + + protected static final String LOC_PATTERN = "topic: /amcl_pose/pose/pose.*position.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z.*\\norientation.*\\n.*x: (.*)\\n.*y: (.*)\\n.*z: (.*)\\n.*w: (.*)(.*)"; + protected String last_x; + protected String last_y; + private String last_w; + + /** + * Main Constructor the Gauge that is hardwired to the Probe. + * + * @param id + * the unique ID of the Gauge + * @param beaconPeriod + * the liveness beacon period of the Gauge + * @param gaugeDesc + * the type-name description of the Gauge + * @param modelDesc + * the type-name description of the Model the Gauge updates + * @param setupParams + * the list of setup parameters with their values + * @param mappings + * the list of Gauge Value to Model Property mappings + */ + public MissionStateGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern (LOC, Pattern.compile (LOC_PATTERN, Pattern.DOTALL)); + } + + @Override + protected void doMatch (String matchName, Matcher m) { + String group = m.group (1); + int restGroup = 0; + if (LOC.equals (matchName)) { + String x = group.trim (); + String y = m.group (2).trim (); + + String a = m.group (3).trim (); + String b = m.group (4).trim (); + String c = m.group (5).trim (); + String d = m.group (6).trim (); + restGroup = 7; + + String w = yawFromQuarternion (a, b, c, d); + + if (locationDifferent (x, y, w)) { + IRainbowOperation op = m_commands.get ("location"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], x); + pMap.put (op.getParameters ()[1], y); + pMap.put (op.getParameters ()[2], w); + issueCommand (op, pMap); + } + } + if (m.groupCount () == restGroup) { + String rest = m.group (restGroup); + if (!rest.isEmpty () && rest.indexOf ("topic:") != -1) { + log ("Gauge had more: " + rest.substring (rest.indexOf ("topic:"))); + } + } + } + + @Override + public void reportFromProbe(IProbeIdentifier probe, String data) { + // TODO Auto-generated method stub + super.reportFromProbe(probe, data); + } + + private boolean numberCheck (String[] vals) { + for (String s : vals) { + try { + Double.parseDouble (s); + } + catch (NumberFormatException e) { + return false; + } + } + return true; + } + + // Converstino to yaw from http://www.chrobotics.com/library/understanding-quaternions + private String yawFromQuarternion (String a, String b, String c, String d) { + double A = Double.parseDouble (a); + double B = Double.parseDouble (b); + double C = Double.parseDouble (c); + double D = Double.parseDouble (d); + + double w = Math.atan ((2 * (A * B + C * D)) / (A * A - B * B - C * C + D * D)); + return Double.toString (w); + + } + + private boolean locationDifferent (String x, String y, String w) { + boolean different = !x.equals (last_x) || !y.equals (last_y) || !w.equals (last_w); + if (different) { + last_x = x; + last_y = y; + last_w = w; + } + return different; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/PowerModelChangeGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/PowerModelChangeGauge.java index 9c0e1f13c..289c9be53 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/PowerModelChangeGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/PowerModelChangeGauge.java @@ -1,52 +1,52 @@ -package org.sa.rainbow.brass.p3_cp1.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.AbstractGaugeWithProbes; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.translator.probes.IProbeIdentifier; - -public class PowerModelChangeGauge extends AbstractGaugeWithProbes { - - private static final String NAME = "PowerModelGauge"; - - public PowerModelChangeGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, - TypedAttribute modelDesc, List setupParams, - Map mappings) throws RainbowException { - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - } - - private String m_newFile = null; - - - @Override - public void reportFromProbe(IProbeIdentifier probe, String data) { - super.reportFromProbe(probe, data); - synchronized (this) { - m_newFile = data; - } - } - - @Override - protected void runAction() { - super.runAction(); - String newFile = null; - synchronized (this) { - if (m_newFile != null) { - newFile = m_newFile; - m_newFile = null; - } - } - if (newFile != null) { - IRainbowOperation op = m_commands.get("update"); - Map pMap = new HashMap<>(); - pMap.put(op.getParameters()[0], newFile); - issueCommand(op, pMap); - } - } -} +package org.sa.rainbow.brass.p3_cp1.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.AbstractGaugeWithProbes; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.translator.probes.IProbeIdentifier; + +public class PowerModelChangeGauge extends AbstractGaugeWithProbes { + + private static final String NAME = "PowerModelGauge"; + + public PowerModelChangeGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, + TypedAttribute modelDesc, List setupParams, + Map mappings) throws RainbowException { + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + } + + private String m_newFile = null; + + + @Override + public void reportFromProbe(IProbeIdentifier probe, String data) { + super.reportFromProbe(probe, data); + synchronized (this) { + m_newFile = data; + } + } + + @Override + protected void runAction() { + super.runAction(); + String newFile = null; + synchronized (this) { + if (m_newFile != null) { + newFile = m_newFile; + m_newFile = null; + } + } + if (newFile != null) { + IRainbowOperation op = m_commands.get("update"); + Map pMap = new HashMap<>(); + pMap.put(op.getParameters()[0], newFile); + issueCommand(op, pMap); + } + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/RobotStateGauge.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/RobotStateGauge.java index 635a0c38b..f9ff9147f 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/RobotStateGauge.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/gauges/RobotStateGauge.java @@ -1,70 +1,70 @@ -package org.sa.rainbow.brass.p3_cp1.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -public class RobotStateGauge extends RegularPatternGauge { - private static final String NAME = "Robot State Gauge"; - protected static final String CHARGE = "BatteryCharge"; - protected static final String SPEED = "Speed"; - protected static final String CONFIG = "Config"; - - protected static final String CHARGE_PATTERN = "topic: /mobile_base/commands/charge_level.*\\n.*data: (.*)"; - protected static final String CONFIG_PATTERN = "cp1 configuration: (.*)"; - private double last_charge = 0; - private String last_config = ""; - - public RobotStateGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern(CHARGE, Pattern.compile(CHARGE_PATTERN, Pattern.DOTALL)); - addPattern(CONFIG, Pattern.compile(CONFIG_PATTERN)); - } - - @Override - protected void doMatch(String matchName, Matcher m) { - if (CHARGE.equals (matchName)) { - double charge = Double.parseDouble(m.group(1).trim()); - - if (chargeDifferent (charge)) { - IRainbowOperation op = m_commands.get ("charge"); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], Double.toString (charge)); - issueCommand (op, pMap); - } - } - else if (CONFIG.equals(matchName)) { - String config = m.group(1).trim(); - - if (!last_config.equals(config)) { - last_config = config; - IRainbowOperation op = m_commands.get("config"); - Map pMap = new HashMap<>(); - pMap.put(op.getParameters()[0], config); - issueCommand(op, pMap); - } - } - } - - private boolean chargeDifferent (double charge) { - if (Math.round (last_charge) != Math.round (charge)) { - last_charge = charge; - return true; - } - return false; - } - - protected boolean shouldProcess() { - return !isRainbowAdapting(); - }; -} +package org.sa.rainbow.brass.p3_cp1.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +public class RobotStateGauge extends RegularPatternGauge { + private static final String NAME = "Robot State Gauge"; + protected static final String CHARGE = "BatteryCharge"; + protected static final String SPEED = "Speed"; + protected static final String CONFIG = "Config"; + + protected static final String CHARGE_PATTERN = "topic: /mobile_base/commands/charge_level.*\\n.*data: (.*)"; + protected static final String CONFIG_PATTERN = "cp1 configuration: (.*)"; + private double last_charge = 0; + private String last_config = ""; + + public RobotStateGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern(CHARGE, Pattern.compile(CHARGE_PATTERN, Pattern.DOTALL)); + addPattern(CONFIG, Pattern.compile(CONFIG_PATTERN)); + } + + @Override + protected void doMatch(String matchName, Matcher m) { + if (CHARGE.equals (matchName)) { + double charge = Double.parseDouble(m.group(1).trim()); + + if (chargeDifferent (charge)) { + IRainbowOperation op = m_commands.get ("charge"); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], Double.toString (charge)); + issueCommand (op, pMap); + } + } + else if (CONFIG.equals(matchName)) { + String config = m.group(1).trim(); + + if (!last_config.equals(config)) { + last_config = config; + IRainbowOperation op = m_commands.get("config"); + Map pMap = new HashMap<>(); + pMap.put(op.getParameters()[0], config); + issueCommand(op, pMap); + } + } + } + + private boolean chargeDifferent (double charge) { + if (Math.round (last_charge) != Math.round (charge)) { + last_charge = charge; + return true; + } + return false; + } + + protected boolean shouldProcess() { + return !isRainbowAdapting(); + }; +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/CP1ModelAccessor.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/CP1ModelAccessor.java index 1bee61c9d..bf379d241 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/CP1ModelAccessor.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/CP1ModelAccessor.java @@ -1,38 +1,38 @@ -package org.sa.rainbow.brass.p3_cp1.model; - -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.brass.model.P2ModelAccessor; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; -import org.sa.rainbow.brass.p3_cp1.model.power.CP1PowerModelInstance; -import org.sa.rainbow.brass.p3_cp1.model.robot.CP1RobotStateModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.ports.IModelsManagerPort; - -public class CP1ModelAccessor extends P2ModelAccessor{ - private CP1RobotStateModelInstance m_robotStateModel; - private CP1PowerModelInstance m_powerModel; - - public CP1ModelAccessor (IModelsManagerPort mmp) { - super(mmp); - } - - public CP1RobotStateModelInstance getRobotStateModel() { - if (m_robotStateModel == null) { - CP1RobotStateModelInstance modelInstance = (CP1RobotStateModelInstance) m_modelsManagerPort.getModelInstance( - new ModelReference("Robot", RobotStateModelInstance.ROBOT_STATE_TYPE)); - m_robotStateModel = modelInstance; - } - return m_robotStateModel; - } - - public CP1PowerModelInstance getPowerModel() { - if (m_powerModel == null) { - CP1PowerModelInstance modelInstance = (CP1PowerModelInstance )m_modelsManagerPort.getModelInstance(new ModelReference("Power", CP1PowerModelInstance.POWER_MODEL_TYPE)); - m_powerModel = modelInstance; - } - return m_powerModel; - } - - -} +package org.sa.rainbow.brass.p3_cp1.model; + +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.brass.model.P2ModelAccessor; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; +import org.sa.rainbow.brass.p3_cp1.model.power.CP1PowerModelInstance; +import org.sa.rainbow.brass.p3_cp1.model.robot.CP1RobotStateModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.IModelsManagerPort; + +public class CP1ModelAccessor extends P2ModelAccessor{ + private CP1RobotStateModelInstance m_robotStateModel; + private CP1PowerModelInstance m_powerModel; + + public CP1ModelAccessor (IModelsManagerPort mmp) { + super(mmp); + } + + public CP1RobotStateModelInstance getRobotStateModel() { + if (m_robotStateModel == null) { + CP1RobotStateModelInstance modelInstance = (CP1RobotStateModelInstance) m_modelsManagerPort.getModelInstance( + new ModelReference("Robot", RobotStateModelInstance.ROBOT_STATE_TYPE)); + m_robotStateModel = modelInstance; + } + return m_robotStateModel; + } + + public CP1PowerModelInstance getPowerModel() { + if (m_powerModel == null) { + CP1PowerModelInstance modelInstance = (CP1PowerModelInstance )m_modelsManagerPort.getModelInstance(new ModelReference("Power", CP1PowerModelInstance.POWER_MODEL_TYPE)); + m_powerModel = modelInstance; + } + return m_powerModel; + } + + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/CP1PowerModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/CP1PowerModelInstance.java index 6908f0f50..1d109bdf6 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/CP1PowerModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/CP1PowerModelInstance.java @@ -1,78 +1,78 @@ -package org.sa.rainbow.brass.p3_cp1.model.power; - -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.core.error.RainbowCopyException; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class CP1PowerModelInstance implements IModelInstance { - - public static final String POWER_MODEL_TYPE = "PowerModel"; - private SimpleConfigurationStore m_powerModel; - private ModelReference m_modelReference; - private PowerModelCommandFactory m_commandFactory; - private String m_source; - - public CP1PowerModelInstance(SimpleConfigurationStore pm, String source) { - setModelInstance(pm); - setOriginalSource(source); - } - - @Override - public SimpleConfigurationStore getModelInstance() { - return m_powerModel; - } - - @Override - public void setModelInstance(SimpleConfigurationStore model) { - m_powerModel = model; - } - - @Override - public IModelInstance copyModelInstance(String newName) throws RainbowCopyException { - return new CP1PowerModelInstance(m_powerModel.copy(), getOriginalSource()); - } - - @Override - public String getModelType() { - return POWER_MODEL_TYPE; - } - - @Override - public String getModelName() { - return getModelReference().getModelName(); - } - - @Override - public ModelCommandFactory getCommandFactory() { - if (m_commandFactory == null) - m_commandFactory = new PowerModelCommandFactory(this); - return m_commandFactory; - } - - @Override - public void setOriginalSource(String source) { - m_source = source; - } - - @Override - public String getOriginalSource() { - return m_source; - } - - @Override - public void dispose() throws RainbowException { - - } - - public ModelReference getModelReference() { - return m_modelReference; - } - - public void setModelReference(ModelReference modelReference) { - m_modelReference = modelReference; - } - -} +package org.sa.rainbow.brass.p3_cp1.model.power; + +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.core.error.RainbowCopyException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class CP1PowerModelInstance implements IModelInstance { + + public static final String POWER_MODEL_TYPE = "PowerModel"; + private SimpleConfigurationStore m_powerModel; + private ModelReference m_modelReference; + private PowerModelCommandFactory m_commandFactory; + private String m_source; + + public CP1PowerModelInstance(SimpleConfigurationStore pm, String source) { + setModelInstance(pm); + setOriginalSource(source); + } + + @Override + public SimpleConfigurationStore getModelInstance() { + return m_powerModel; + } + + @Override + public void setModelInstance(SimpleConfigurationStore model) { + m_powerModel = model; + } + + @Override + public IModelInstance copyModelInstance(String newName) throws RainbowCopyException { + return new CP1PowerModelInstance(m_powerModel.copy(), getOriginalSource()); + } + + @Override + public String getModelType() { + return POWER_MODEL_TYPE; + } + + @Override + public String getModelName() { + return getModelReference().getModelName(); + } + + @Override + public ModelCommandFactory getCommandFactory() throws RainbowException { + if (m_commandFactory == null) + m_commandFactory = new PowerModelCommandFactory(this); + return m_commandFactory; + } + + @Override + public void setOriginalSource(String source) { + m_source = source; + } + + @Override + public String getOriginalSource() { + return m_source; + } + + @Override + public void dispose() throws RainbowException { + + } + + public ModelReference getModelReference() { + return m_modelReference; + } + + public void setModelReference(ModelReference modelReference) { + m_modelReference = modelReference; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/LoadPowerModelCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/LoadPowerModelCmd.java index b50a0ef7d..597a67807 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/LoadPowerModelCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/LoadPowerModelCmd.java @@ -1,60 +1,60 @@ -package org.sa.rainbow.brass.p3_cp1.model.power; - -import java.io.InputStream; - -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; - -public class LoadPowerModelCmd extends AbstractLoadModelCmd { - - private String m_modelName; - private InputStream m_stream; - private CP1PowerModelInstance m_result; - - public LoadPowerModelCmd(ModelsManager mm, String modelName, InputStream stream, String source) { - super("loadPowerModel", mm, modelName, stream, source); - m_modelName = modelName; - m_stream = stream; - } - - @Override - public CP1PowerModelInstance getResult() throws IllegalStateException { - return m_result; - } - - @Override - public ModelReference getModelReference() { - return new ModelReference(m_modelName, CP1PowerModelInstance.POWER_MODEL_TYPE); - } - - @Override - protected void subExecute() throws RainbowException { -// if (m_stream == null) { - SimpleConfigurationStore store = new SimpleConfigurationStore(Rainbow.instance().allProperties()); - m_result = new CP1PowerModelInstance(store, getOriginalSource()); - m_result.setModelReference(getModelReference()); - doPostExecute(); -// } - } - - @Override - protected void subRedo() throws RainbowException { - doPostExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - doPostUndo(); - } - - @Override - protected boolean checkModelValidForCommand(Object model) { - return true; - } - -} +package org.sa.rainbow.brass.p3_cp1.model.power; + +import java.io.InputStream; + +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; + +public class LoadPowerModelCmd extends AbstractLoadModelCmd { + + private String m_modelName; + private InputStream m_stream; + private CP1PowerModelInstance m_result; + + public LoadPowerModelCmd(ModelsManager mm, String modelName, InputStream stream, String source) { + super("loadPowerModel", mm, modelName, stream, source); + m_modelName = modelName; + m_stream = stream; + } + + @Override + public CP1PowerModelInstance getResult() throws IllegalStateException { + return m_result; + } + + @Override + public ModelReference getModelReference() { + return new ModelReference(m_modelName, CP1PowerModelInstance.POWER_MODEL_TYPE); + } + + @Override + protected void subExecute() throws RainbowException { +// if (m_stream == null) { + SimpleConfigurationStore store = new SimpleConfigurationStore(Rainbow.instance().allProperties()); + m_result = new CP1PowerModelInstance(store, getOriginalSource()); + m_result.setModelReference(getModelReference()); + doPostExecute(); +// } + } + + @Override + protected void subRedo() throws RainbowException { + doPostExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + doPostUndo(); + } + + @Override + protected boolean checkModelValidForCommand(Object model) { + return true; + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/PowerModelCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/PowerModelCommandFactory.java index 6b45cb42a..8548d4998 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/PowerModelCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/PowerModelCommandFactory.java @@ -1,39 +1,40 @@ -package org.sa.rainbow.brass.p3_cp1.model.power; - -import java.io.InputStream; - -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class PowerModelCommandFactory extends ModelCommandFactory { - - public static LoadPowerModelCmd loadCommand(ModelsManager mm, - String modelName, - InputStream stream, - String source) { - return new LoadPowerModelCmd(mm, modelName, stream, source); - } - - public PowerModelCommandFactory( - CP1PowerModelInstance model) { - super(CP1PowerModelInstance.class, model); - } - - @Override - protected void fillInCommandMap() { - m_commandMap.put("updatePowerModel".toLowerCase(), UpdatePowerModelCmd.class); - } - - @Override - public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { - return null; - } - - public UpdatePowerModelCmd updatePowerModelCmd(String newFileName) { - return new UpdatePowerModelCmd((CP1PowerModelInstance )m_modelInstance,"",newFileName); - } - -} +package org.sa.rainbow.brass.p3_cp1.model.power; + +import java.io.InputStream; + +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class PowerModelCommandFactory extends ModelCommandFactory { + + public static final String UPDATE_POWER_MODEL_CMD = "updatePowerModel"; + + @LoadOperation + public static LoadPowerModelCmd loadCommand(ModelsManager mm, + String modelName, + InputStream stream, + String source) { + return new LoadPowerModelCmd(mm, modelName, stream, source); + } + + public PowerModelCommandFactory( + CP1PowerModelInstance model) throws RainbowException { + super(CP1PowerModelInstance.class, model); + } + + + @Override + public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { + return null; + } + + @Operation(name=UPDATE_POWER_MODEL_CMD) + public UpdatePowerModelCmd updatePowerModelCmd(String newFileName) { + return new UpdatePowerModelCmd(UPDATE_POWER_MODEL_CMD, (CP1PowerModelInstance )m_modelInstance,"",newFileName); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/UpdatePowerModelCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/UpdatePowerModelCmd.java index a2cbb40c7..cefad4e1d 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/UpdatePowerModelCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/power/UpdatePowerModelCmd.java @@ -1,67 +1,67 @@ -package org.sa.rainbow.brass.p3_cp1.model.power; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; - -import org.json.simple.parser.ParseException; -import org.sa.rainbow.brass.confsynthesis.SimpleConfiguration; -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public class UpdatePowerModelCmd extends AbstractRainbowModelOperation { - - private String m_newFileName; - private Boolean m_successful; - private HashMap m_oldModel; - - public UpdatePowerModelCmd(CP1PowerModelInstance modelInstance, String target, String newFileName) { - super("updatePowerModel", modelInstance, target, newFileName); - m_newFileName = newFileName; - - } - - @Override - public Boolean getResult() throws IllegalStateException { - return m_successful; - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "updatePowerModel"); - } - - @Override - protected void subExecute() throws RainbowException { - try { - m_oldModel = new HashMap (getModelContext().getModelInstance().m_configuration_objects); - getModelContext().getModelInstance().reloadFromFile(m_newFileName); - } catch (IOException | ParseException e) { - m_successful = false; - } - } - - @Override - protected void subRedo() throws RainbowException { - try { - getModelContext().getModelInstance().reloadFromFile(m_newFileName); - } catch (IOException | ParseException e) { - e.printStackTrace(); - } - - } - - @Override - protected void subUndo() throws RainbowException { - getModelContext().getModelInstance().m_configuration_objects = m_oldModel; - } - - @Override - protected boolean checkModelValidForCommand(SimpleConfigurationStore model) { - return model == getModelContext().getModelInstance(); - } - -} +package org.sa.rainbow.brass.p3_cp1.model.power; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; + +import org.json.simple.parser.ParseException; +import org.sa.rainbow.brass.confsynthesis.SimpleConfiguration; +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class UpdatePowerModelCmd extends AbstractRainbowModelOperation { + + private String m_newFileName; + private Boolean m_successful; + private HashMap m_oldModel; + + public UpdatePowerModelCmd(String commandName, CP1PowerModelInstance modelInstance, String target, String newFileName) { + super(commandName, modelInstance, target, newFileName); + m_newFileName = newFileName; + + } + + @Override + public Boolean getResult() throws IllegalStateException { + return m_successful; + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents(messageFactory, getName()); + } + + @Override + protected void subExecute() throws RainbowException { + try { + m_oldModel = new HashMap (getModelContext().getModelInstance().m_configuration_objects); + getModelContext().getModelInstance().reloadFromFile(m_newFileName); + } catch (IOException | ParseException e) { + m_successful = false; + } + } + + @Override + protected void subRedo() throws RainbowException { + try { + getModelContext().getModelInstance().reloadFromFile(m_newFileName); + } catch (IOException | ParseException e) { + e.printStackTrace(); + } + + } + + @Override + protected void subUndo() throws RainbowException { + getModelContext().getModelInstance().m_configuration_objects = m_oldModel; + } + + @Override + protected boolean checkModelValidForCommand(SimpleConfigurationStore model) { + return model == getModelContext().getModelInstance(); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotState.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotState.java index af8350d73..d00285882 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotState.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotState.java @@ -1,30 +1,30 @@ -package org.sa.rainbow.brass.p3_cp1.model.robot; - -import java.util.ArrayDeque; -import java.util.Deque; - -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.core.models.ModelReference; - -public class CP1RobotState extends RobotState { - - Deque> m_configHistory = new ArrayDeque<>(); - - public CP1RobotState(ModelReference model) { - super(model); - } - - public String getConfigId() { - synchronized(m_configHistory) { - TimeStamped peek = m_configHistory.peek(); - return peek!=null?peek.data:""; - } - } - - public void setConfigId(String configId) { - synchronized(m_configHistory) { - m_configHistory.push(new TimeStamped(configId)); - } - } - -} +package org.sa.rainbow.brass.p3_cp1.model.robot; + +import java.util.ArrayDeque; +import java.util.Deque; + +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.core.models.ModelReference; + +public class CP1RobotState extends RobotState { + + Deque> m_configHistory = new ArrayDeque<>(); + + public CP1RobotState(ModelReference model) { + super(model); + } + + public String getConfigId() { + synchronized(m_configHistory) { + TimeStamped peek = m_configHistory.peek(); + return peek!=null?peek.data:""; + } + } + + public void setConfigId(String configId) { + synchronized(m_configHistory) { + m_configHistory.push(new TimeStamped(configId)); + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateCommandFactory.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateCommandFactory.java index 0c919e79b..d5df1adfa 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateCommandFactory.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateCommandFactory.java @@ -1,41 +1,40 @@ -package org.sa.rainbow.brass.p3_cp1.model.robot; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.sa.rainbow.brass.model.p2_cp3.robot.SaveCP3RobotStateCmd; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.RobotStateCommandFactory; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; - -public class CP1RobotStateCommandFactory extends RobotStateCommandFactory { - public CP1RobotStateCommandFactory(CP1RobotStateModelInstance model) { - super(CP1RobotStateModelInstance.class, model); - } - - public static CP1RobotStateLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream stream, String source) { - return new CP1RobotStateLoadCmd(mm, modelName, stream, source); - } - - @Override - public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { - try (FileOutputStream os = new FileOutputStream(location)) { - return new SaveCP3RobotStateCmd(null, location, os, m_modelInstance.getOriginalSource()); - } catch (IOException e) { - return null; - } - } - - @Override - protected void fillInCommandMap() { - super.fillInCommandMap(); - m_commandMap.put("setConfig".toLowerCase(), SetConfigCmd.class); - } - - public SetConfigCmd setConfigCmd(String configId) { - return new SetConfigCmd((CP1RobotStateModelInstance )m_modelInstance, "", configId); - } -} +package org.sa.rainbow.brass.p3_cp1.model.robot; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.sa.rainbow.brass.model.p2_cp3.robot.SaveCP3RobotStateCmd; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.RobotStateCommandFactory; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; + +public class CP1RobotStateCommandFactory extends RobotStateCommandFactory { + private static final String SET_CONFIG_CMD = "setConfig"; + + public CP1RobotStateCommandFactory(CP1RobotStateModelInstance model) throws RainbowException { + super(CP1RobotStateModelInstance.class, model); + } + + @LoadOperation + public static CP1RobotStateLoadCmd loadCommand(ModelsManager mm, String modelName, InputStream stream, String source) { + return new CP1RobotStateLoadCmd(mm, modelName, stream, source); + } + + @Override + public AbstractSaveModelCmd saveCommand(String location) throws RainbowModelException { + try (FileOutputStream os = new FileOutputStream(location)) { + return new SaveCP3RobotStateCmd(null, location, os, m_modelInstance.getOriginalSource()); + } catch (IOException e) { + return null; + } + } + + @Operation(name=SET_CONFIG_CMD) + public SetConfigCmd setConfigCmd(String configId) { + return new SetConfigCmd(SET_CONFIG_CMD, (CP1RobotStateModelInstance )m_modelInstance, "", configId); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateLoadCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateLoadCmd.java index d7992a310..9286ae1ea 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateLoadCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateLoadCmd.java @@ -1,24 +1,24 @@ -package org.sa.rainbow.brass.p3_cp1.model.robot; - -import java.io.InputStream; - -import org.sa.rainbow.brass.model.robot.RobotStateLoadCmd; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelsManager; - -public class CP1RobotStateLoadCmd extends RobotStateLoadCmd { - - public CP1RobotStateLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { - super(mm, resource, is, source); - } - - @Override - protected void subExecute() throws RainbowException { - if (m_stream == null) { - CP1RobotState m = new CP1RobotState(getModelReference()); - m_result = new CP1RobotStateModelInstance(m, getOriginalSource()); - doPostExecute(); - } - } - -} +package org.sa.rainbow.brass.p3_cp1.model.robot; + +import java.io.InputStream; + +import org.sa.rainbow.brass.model.robot.RobotStateLoadCmd; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelsManager; + +public class CP1RobotStateLoadCmd extends RobotStateLoadCmd { + + public CP1RobotStateLoadCmd(IModelsManager mm, String resource, InputStream is, String source) { + super(mm, resource, is, source); + } + + @Override + protected void subExecute() throws RainbowException { + if (m_stream == null) { + CP1RobotState m = new CP1RobotState(getModelReference()); + m_result = new CP1RobotStateModelInstance(m, getOriginalSource()); + doPostExecute(); + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateModelInstance.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateModelInstance.java index 3ec9719fd..34203573f 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateModelInstance.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/CP1RobotStateModelInstance.java @@ -1,26 +1,27 @@ -package org.sa.rainbow.brass.p3_cp1.model.robot; - -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class CP1RobotStateModelInstance extends RobotStateModelInstance { - private CP1RobotStateCommandFactory m_commandFactory; - - public CP1RobotStateModelInstance(CP1RobotState r, String source) { - super(r, source); - } - - @Override - public CP1RobotState getModelInstance() { - return (CP1RobotState )super.getModelInstance(); - } - - @Override - public ModelCommandFactory getCommandFactory() { - if (m_commandFactory == null) { - m_commandFactory = new CP1RobotStateCommandFactory(this); - } - return m_commandFactory; - } -} +package org.sa.rainbow.brass.p3_cp1.model.robot; + +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.RobotStateModelInstance; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class CP1RobotStateModelInstance extends RobotStateModelInstance { + private CP1RobotStateCommandFactory m_commandFactory; + + public CP1RobotStateModelInstance(CP1RobotState r, String source) { + super(r, source); + } + + @Override + public CP1RobotState getModelInstance() { + return (CP1RobotState )super.getModelInstance(); + } + + @Override + public ModelCommandFactory getCommandFactory() throws RainbowException { + if (m_commandFactory == null) { + m_commandFactory = new CP1RobotStateCommandFactory(this); + } + return m_commandFactory; + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/SaveCP1RobotStateCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/SaveCP1RobotStateCmd.java index 04cecdb31..fc13354ca 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/SaveCP1RobotStateCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/SaveCP1RobotStateCmd.java @@ -1,39 +1,39 @@ -package org.sa.rainbow.brass.p3_cp1.model.robot; - -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.EnumSet; -import java.util.Iterator; - -import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel.TimeStamped; -import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.brass.model.robot.SaveRobotStateCmd; -import org.sa.rainbow.core.models.IModelsManager; - -public class SaveCP1RobotStateCmd extends SaveRobotStateCmd { - - public SaveCP1RobotStateCmd(IModelsManager mm, String resource, OutputStream os, String source) { - super(mm, resource, os, source); - } - - @Override - protected void insertRobotState(PrintStream ps, RobotState model) { - super.insertRobotState(ps, model); - if (model instanceof CP1RobotState) { - CP1RobotState cp3 = (CP1RobotState )model; - ps.print(" configHistory: [\n"); - for (Iterator> iterator = cp3.m_configHistory.iterator(); iterator.hasNext();) { - TimeStamped entry = iterator.next(); - ps.print("{timestamp: " + entry.timestamp + ", config: " + entry.data + "}"); - if (iterator.hasNext()) ps.print(","); - } - - ps.print("]"); - } - - } - -} +package org.sa.rainbow.brass.p3_cp1.model.robot; + +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.EnumSet; +import java.util.Iterator; + +import org.sa.rainbow.brass.model.p2_cp3.clock.ClockedModel.TimeStamped; +import org.sa.rainbow.brass.model.p2_cp3.robot.CP3RobotState.Sensors; +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.brass.model.robot.SaveRobotStateCmd; +import org.sa.rainbow.core.models.IModelsManager; + +public class SaveCP1RobotStateCmd extends SaveRobotStateCmd { + + public SaveCP1RobotStateCmd(IModelsManager mm, String resource, OutputStream os, String source) { + super(mm, resource, os, source); + } + + @Override + protected void insertRobotState(PrintStream ps, RobotState model) { + super.insertRobotState(ps, model); + if (model instanceof CP1RobotState) { + CP1RobotState cp3 = (CP1RobotState )model; + ps.print(" configHistory: [\n"); + for (Iterator> iterator = cp3.m_configHistory.iterator(); iterator.hasNext();) { + TimeStamped entry = iterator.next(); + ps.print("{timestamp: " + entry.timestamp + ", config: " + entry.data + "}"); + if (iterator.hasNext()) ps.print(","); + } + + ps.print("]"); + } + + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/SetConfigCmd.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/SetConfigCmd.java index 23721e6f1..1d4e8a9c4 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/SetConfigCmd.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/model/robot/SetConfigCmd.java @@ -1,50 +1,50 @@ -package org.sa.rainbow.brass.p3_cp1.model.robot; - -import java.util.List; - -import org.sa.rainbow.brass.model.robot.RobotState; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public class SetConfigCmd extends AbstractRainbowModelOperation { - - public SetConfigCmd(CP1RobotStateModelInstance model, String target, - String config) { - super("setConfig", model, target, config); - } - - @Override - public String getResult() throws IllegalStateException { - return ((CP1RobotState )getModelContext()).getConfigId(); - } - - @Override - protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { - return generateEvents(messageFactory, "setConfig"); - } - - @Override - protected void subExecute() throws RainbowException { - ((CP1RobotState )getModelContext().getModelInstance()).setConfigId(getParameters()[0]); - } - - @Override - protected void subRedo() throws RainbowException { - subExecute(); - } - - @Override - protected void subUndo() throws RainbowException { - // TODO Auto-generated method stub - - } - - @Override - protected boolean checkModelValidForCommand(RobotState model) { - return model == getModelContext().getModelInstance(); - } - -} +package org.sa.rainbow.brass.p3_cp1.model.robot; + +import java.util.List; + +import org.sa.rainbow.brass.model.robot.RobotState; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class SetConfigCmd extends AbstractRainbowModelOperation { + + public SetConfigCmd(String commandName, CP1RobotStateModelInstance model, String target, + String config) { + super(commandName, model, target, config); + } + + @Override + public String getResult() throws IllegalStateException { + return ((CP1RobotState )getModelContext()).getConfigId(); + } + + @Override + protected List getGeneratedEvents(IRainbowMessageFactory messageFactory) { + return generateEvents(messageFactory, "setConfig"); + } + + @Override + protected void subExecute() throws RainbowException { + ((CP1RobotState )getModelContext().getModelInstance()).setConfigId(getParameters()[0]); + } + + @Override + protected void subRedo() throws RainbowException { + subExecute(); + } + + @Override + protected void subUndo() throws RainbowException { + // TODO Auto-generated method stub + + } + + @Override + protected boolean checkModelValidForCommand(RobotState model) { + return model == getModelContext().getModelInstance(); + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/plan/DecisionEngineCP1.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/plan/DecisionEngineCP1.java index 284b9568e..352238457 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/plan/DecisionEngineCP1.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/plan/DecisionEngineCP1.java @@ -31,6 +31,7 @@ public static void init(Properties props) throws Exception { MapTranslator.ROBOT_BATTERY_CHARGING_RATIO = SimpleConfigurationBatteryModel.getChargingRate(); m_energyWeight = SimpleConfigurationBatteryModel.getEnergyWeight(); m_timelinessWeight = SimpleConfigurationBatteryModel.getTimelinessWeight(); + m_priority_index = 1; } /** * Returns the maximum estimated time for a candidate policy in the scoreboard diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/probes/PowerModelChangeProbe.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/probes/PowerModelChangeProbe.java index 6d5fea81d..fc736b7a1 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/probes/PowerModelChangeProbe.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/p3_cp1/probes/PowerModelChangeProbe.java @@ -1,86 +1,86 @@ -package org.sa.rainbow.brass.p3_cp1.probes; - -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Path; -import java.nio.file.StandardWatchEventKinds; -import java.nio.file.WatchEvent; -import java.nio.file.WatchKey; -import java.nio.file.WatchService; -import java.text.MessageFormat; -import java.util.concurrent.TimeUnit; - -import org.sa.rainbow.core.ConfigHelper; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.util.RainbowLogger; -import org.sa.rainbow.translator.probes.AbstractProbe; - -public class PowerModelChangeProbe extends AbstractProbe implements Runnable { - - private static final String PROBE_TYPE = "powermodelupdateprobe"; - private long m_sleepTime; - private String m_path; - private WatchService m_watcher; - private WatchKey m_watchKey; - private Thread m_watchTrhead; - private Path m_filePath; - private boolean m_deactivated; - - public PowerModelChangeProbe(String id, long sleepTime) { - super(id, PROBE_TYPE, Kind.JAVA); - m_sleepTime = sleepTime; - } - - public PowerModelChangeProbe(String id, long sleepTime, String args) { - this(id, sleepTime); - m_path = ConfigHelper.convertToAbsolute(args); - } - - @Override - public synchronized void activate() { - super.activate(); - m_filePath = FileSystems.getDefault().getPath(m_path); - if (!m_filePath.getParent().toFile().exists()) { - RainbowLogger.error(RainbowComponentT.PROBE, MessageFormat.format("The path containing the file '{0}' does not exist", m_path), getLoggingPort(), LOGGER); - } - else { - try { - m_watcher = FileSystems.getDefault().newWatchService(); - m_watchKey = m_filePath.getParent().register(m_watcher, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE); - m_deactivated = false; - m_watchTrhead = new Thread(this); - m_watchTrhead.start(); - } catch (IOException e) { - RainbowLogger.error(RainbowComponentT.PROBE, "Failed to activate probe " + id(), e, getLoggingPort(), - LOGGER); - } - } - - } - - @Override - public synchronized void deactivate() { - m_deactivated = true; - super.deactivate(); - } - - @Override - public void run() { - boolean ok = true; - while (!m_deactivated && ok) { - try { - final WatchKey wk = m_watcher.poll(m_sleepTime, TimeUnit.MILLISECONDS); - if (wk != null) { - for (WatchEvent event : wk.pollEvents()) { - if (m_filePath.getFileName().equals((Path )event.context())) { - reportData(m_filePath.toFile().getAbsolutePath()); - } - } - ok = wk.reset(); - } - } catch (InterruptedException e) { - } - } - } - -} +package org.sa.rainbow.brass.p3_cp1.probes; + +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import java.text.MessageFormat; +import java.util.concurrent.TimeUnit; + +import org.sa.rainbow.core.ConfigHelper; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.util.RainbowLogger; +import org.sa.rainbow.translator.probes.AbstractProbe; + +public class PowerModelChangeProbe extends AbstractProbe implements Runnable { + + private static final String PROBE_TYPE = "powermodelupdateprobe"; + private long m_sleepTime; + private String m_path; + private WatchService m_watcher; + private WatchKey m_watchKey; + private Thread m_watchTrhead; + private Path m_filePath; + private boolean m_deactivated; + + public PowerModelChangeProbe(String id, long sleepTime) { + super(id, PROBE_TYPE, Kind.JAVA); + m_sleepTime = sleepTime; + } + + public PowerModelChangeProbe(String id, long sleepTime, String args) { + this(id, sleepTime); + m_path = ConfigHelper.convertToAbsolute(args); + } + + @Override + public synchronized void activate() { + super.activate(); + m_filePath = FileSystems.getDefault().getPath(m_path); + if (!m_filePath.getParent().toFile().exists()) { + RainbowLogger.error(RainbowComponentT.PROBE, MessageFormat.format("The path containing the file '{0}' does not exist", m_path), getLoggingPort(), LOGGER); + } + else { + try { + m_watcher = FileSystems.getDefault().newWatchService(); + m_watchKey = m_filePath.getParent().register(m_watcher, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE); + m_deactivated = false; + m_watchTrhead = new Thread(this); + m_watchTrhead.start(); + } catch (IOException e) { + RainbowLogger.error(RainbowComponentT.PROBE, "Failed to activate probe " + id(), e, getLoggingPort(), + LOGGER); + } + } + + } + + @Override + public synchronized void deactivate() { + m_deactivated = true; + super.deactivate(); + } + + @Override + public void run() { + boolean ok = true; + while (!m_deactivated && ok) { + try { + final WatchKey wk = m_watcher.poll(m_sleepTime, TimeUnit.MILLISECONDS); + if (wk != null) { + for (WatchEvent event : wk.pollEvents()) { + if (m_filePath.getFileName().equals((Path )event.context())) { + reportData(m_filePath.toFile().getAbsolutePath()); + } + } + ok = wk.reset(); + } + } catch (InterruptedException e) { + } + } + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2/DecisionEngine.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2/DecisionEngine.java index 18cc990cf..60328da97 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2/DecisionEngine.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2/DecisionEngine.java @@ -156,6 +156,7 @@ public static void scoreCandidates (EnvMap map, long batteryLevel, int robotHead // We generate the policy for the priority QA BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.ADAPTING.name(), "Model checking path " + candidate_key.toString()); // Get the configuration tht is most likely to be successful on this path + log("Checking " + candidate_key.toString() + " for properties in " + m_properties_file); result = PrismConnectorAPI.instance().modelCheckFromFileS (m_candidates.get(candidate_key), m_properties_file, m_candidates.get (candidate_key), m_priority_index, m_consts); BRASSHttpConnector.instance(Phases.Phase2).reportStatus(DASPhase2StatusT.ADAPTING.name(), " Finished first model check"); diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2/MapTranslator.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2/MapTranslator.java index 72b8eca17..b906ee280 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2/MapTranslator.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2/MapTranslator.java @@ -1,727 +1,728 @@ -package org.sa.rainbow.brass.plan.p2; - - -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import org.apache.log4j.Logger; -import org.sa.rainbow.brass.confsynthesis.Configuration; -import org.sa.rainbow.brass.confsynthesis.ConfigurationProvider; -import org.sa.rainbow.brass.confsynthesis.ConfigurationSynthesizer; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.EnvMapArc; -import org.sa.rainbow.brass.model.map.EnvMapNode; -import org.sa.rainbow.brass.model.map.EnvMapPath; -import org.sa.rainbow.brass.model.map.dijkstra.Dijkstra; -import org.sa.rainbow.brass.model.map.dijkstra.Edge; -import org.sa.rainbow.brass.model.map.dijkstra.Graph; -import org.sa.rainbow.brass.model.map.dijkstra.Vertex; -import org.sa.rainbow.brass.model.mission.MissionState; - -import com.google.common.base.Objects; - -/** - * @author jcamara - * - * Eventually, the MapTranslator might be moved into a more general - * translator incorporating elements from the architecture model, etc. - */ - - -public class MapTranslator { - - public static final String VERSION_STR = "V0.5a - April 2018"; - - public static final String MODEL_TYPE = "mdp"; - public static final String MODULE_POSTFIX_STR = "_module"; - public static final String TURN_VARIABLE = "turn"; - public static final String MOVE_CMD_STR = "_to_"; - public static final String MIN_POSTFIX = "_min"; - public static final String MAX_POSTFIX = "_max"; - public static final String INIT_POSTFIX = "_init"; - public static final String UPDATE_POSTFIX = "_upd"; - public static final String HEADING_CONST_PREFIX="H_"; - public static final String ROTATION_TIME_FORMULA_PREFIX="rot_time_"; - public static final String ROTATION_ENERGY_FORMULA_PREFIX="rot_energy_"; - public static final String ENVIRONMENT_TURN_STR = "ET"; - public static final String ROBOT_TURN_STR = "RT"; - - - // Environment Configuration constants - - public static final String ENVIRONMENT_PLAYER_NAME = "env"; - public static final String ENVIRONMENT_UPDATE_HOUSEKEEPING_STR = " ("+TURN_VARIABLE+"'="+ROBOT_TURN_STR+")"; - public static final String ENVIRONMENT_GUARD_STR = "& (turn="+ENVIRONMENT_TURN_STR+")"; - - // Robot Configuration constants - - public static final String ROBOT_PLAYER_NAME = "bot"; - public static final String ROBOT_GUARD_STR = "& (turn="+ROBOT_TURN_STR+")"; - public static final String ROBOT_UPDATE_HOUSEKEEPING_STR = " & ("+TURN_VARIABLE+"'="+ENVIRONMENT_TURN_STR+")"; - public static final String ROBOT_LOCATION_VAR = "l"; - public static final String INITIAL_ROBOT_LOCATION_CONST = "INITIAL_LOCATION"; - public static final String TARGET_ROBOT_LOCATION_CONST = "TARGET_LOCATION"; - public static final String ROBOT_BATTERY_VAR = "b"; - public static final String ROBOT_BATTERY_RANGE_MIN = "0"; - public static long ROBOT_BATTERY_RANGE_MAX = 180000; - public static Double ROBOT_BATTERY_CHARGING_RATIO = BatteryPredictor.getChargingTimeRatio(); - public static final String ROBOT_BATTERY_RANGE_MAX_CONST = "MAX_BATTERY"; - public static final String INITIAL_ROBOT_BATTERY_CONST = "INITIAL_BATTERY"; - public static final String ROBOT_BATTERY_DELTA = "10"; // Constant for the time being, this should be transition+context dependent - public static final String BATTERY_GUARD_STR="& ("+ROBOT_BATTERY_VAR+">="+ROBOT_BATTERY_DELTA+")"; // Not used for the time being (battery depletion condition covered by STOP_GUARD_STR) - public static final String BATTERY_UPDATE_STR = ROBOT_BATTERY_VAR+UPDATE_POSTFIX; - public static final float ROBOT_CHARGING_TIME = 15.0f; - - public static final float ROBOT_FULL_SPEED_VALUE = 0.68f; // m/s - public static final float ROBOT_HALF_SPEED_VALUE = 0.35f; - public static final float ROBOT_SAFE_SPEED_VALUE = 0.25f; - public static final float ROBOT_DR_SPEED_VALUE = 0.25f; // Dead reckoning speed value .. this is implicit in ROBOT_LOC_MODE_LO - public static final String ROBOT_FULL_SPEED_CONST = "FULL_SPEED"; // These are just symbolic constants for PRISM - public static final String ROBOT_HALF_SPEED_CONST = "HALF_SPEED"; - public static final String ROBOT_DR_SPEED_CONST = "DR_SPEED"; - public static final String ROBOT_SPEED_VAR = "s"; - - public static final float ROBOT_ROTATIONAL_SPEED_VALUE = 1.5f; // rad/s - public static final String ROBOT_HEADING_VAR = "r"; - public static final String INITIAL_ROBOT_HEADING_CONST = "INITIAL_HEADING"; - - public static final String ROBOT_CONF_VAR = "c"; - public static final String INITIAL_ROBOT_CONF_CONST = "INITIAL_CONFIGURATION"; - public static final String ROBOT_MAX_RECONF_CONST = "RECONF_MAX"; - public static final String ROBOT_RECONF_VAR = "cr"; - public static String ROBOT_MAX_RECONF_VAL = "1"; // Only reconfiguring at start of plan, for the time being... -// public static final String ROBOT_CONF_PREFIX = "sol_"; - - - public static final String ROBOT_COLLISION_VAR = "collided"; - - - public static final float MAXIMUM_KINECT_OFF_DISTANCE_VAL = 6.0f; // Maximum driving distance with kinect off in m. - -// public static Double TRAVERSAL_SUCCESS_THRESHOLD=0.9; // Tolerance for map arc traversal success rate (if lower, segment not considered as a valid map trajectory in a given configuration) - public static Double TRAVERSAL_SUCCESS_THRESHOLD=0.1; // Tolerance for map arc traversal success rate (if lower, segment not considered as a valid map trajectory in a given configuration) - public static final Double TRAVERSAL_HIT_THRESHOLD=0.1; // Tolerance for map arc traversal hit rate(if higher, segment not considered as a vaid map trajectory) - - // Goal and stop condition configuration constants - - public static final String GOAL_PRED="goal"; // Goal achieved predicate (currently target location reached) - public static final String GOAL_PRED_DEF=GOAL_PRED+" = "+ROBOT_LOCATION_VAR+"="+TARGET_ROBOT_LOCATION_CONST+";"; - - public static final String STOP_PRED = "stop"; // Stop condition predicate (currently target location reached of insufficient battery to move to a nearby location) -// public static final String STOP_PRED_DEF = STOP_PRED + " = "+GOAL_PRED+" | "+ROBOT_BATTERY_VAR+"<"+ROBOT_BATTERY_DELTA+";"; - public static final String STOP_PRED_DEF = STOP_PRED + " = "+GOAL_PRED+";"; - public static final String STOP_GUARD_STR = "& (!"+STOP_PRED+")"; - public static final String FAILED_PRED = "l=lfailed"; - public static final String NOT_FAILED_PRED="l!=lfailed"; - - public static final double MAX_DISTANCE = 999.0; // Distance assigned to disabled edges (for distance reward computation) - public static final double DEFAULT_TIME_TACTIC_TIME=1; // Tactics are not instantaneous; - public static final String TACTIC_PREFIX="t"; - - public static boolean CONSIDER_RECONFIGURATION_COST=false; - - // Properties' indices - public static final int TIME_PROPERTY = 0; - public static final int ACCURACY_PROPERTY = 1; - - private static EnvMap m_map; - private static ConfigurationProvider m_cp; - private static LinkedList m_generated_movecommands = new LinkedList(); - - - private static Logger LOGGER; - - public static Logger getLogger() { - return LOGGER; - } - - public static void setLogger(Logger lOGGER) { - LOGGER = lOGGER; - } - - public static void logInfo(String msg) { - if (LOGGER==null) { - System.out.println(msg); - } - else LOGGER.info(msg); - } - - public static void logError(String msg) { - if (LOGGER==null) { - System.out.println(msg); - } - else LOGGER.error(msg); - } - - /** - * Sets the Configuration provider - */ - public static void setConfigurationProvider(ConfigurationProvider cp){ - m_cp = cp; - } - - /** - * Sets the map to translate into a PRISM specification - * @param map an EnvMap encoding the graph that captures the physical space - */ - public static void setMap(EnvMap map){ - m_map = map; - } - - /** - * Generates PRISM model game structure - Alternating Robot/Environment turns - * @return String a string with the general declarations for PRISM model turn structure - */ - public static String generateGameStructure(){ - String buf=new String(); - buf+=MODEL_TYPE+"\n\n"; - buf+="const "+ENVIRONMENT_TURN_STR+"=0;\n"; - buf+="const "+ROBOT_TURN_STR+"=1;\n"; - buf+="\nglobal "+TURN_VARIABLE+":["+ENVIRONMENT_TURN_STR+".."+ROBOT_TURN_STR+"] init "+ENVIRONMENT_TURN_STR+";\n\n"; - return buf+"\n"; - } - - - /** - * Generates a list of labels for movement commands between locations - * @return LinkedString list of movement between location command strings - * Unused for the time being - */ - public static LinkedList generateMoveCommandStrs(){ - synchronized (m_map) { - LinkedList res = new LinkedList (); - LinkedList arcs = m_map.getArcs(); - for (int i=0; i entry : m_map.getNodes().entrySet() ){ - buf+="const "+entry.getKey()+"="+String.valueOf(entry.getValue().getId())+";\n"; -// buf+="const "+entry.getKey()+"="+String.valueOf(c)+";\n"; - c++; - } - buf += "const lfailed=-1; // location indicating failed transitions\n"; - return buf+"\n"; - } - - /** - * Generates labels for robot configurations - * @return String PRISM encoding for configuration constants - */ - public static String generateConfigurationConstants(){ - String buf="// Configuration constants\n\n"; - buf+="const "+INITIAL_ROBOT_CONF_CONST+";\n"; - int cid=0; - for (Map.Entry entry : m_cp.getConfigurations().entrySet() ){ - buf+="const "+entry.getKey()+"="+String.valueOf(cid)+";\n"; - cid+=1; - } - return buf+"\n"; - } - - /** - * @return String PRISM encoding for the environment process - */ - public static String generateEnvironmentModule(){ - String buf="// Environment process\n\n"; - buf+="module "+ENVIRONMENT_PLAYER_NAME+MODULE_POSTFIX_STR+"\n"; - buf+="end:bool init false;\n\n"; - buf+="\t[] true "+ENVIRONMENT_GUARD_STR +" "+STOP_GUARD_STR+" & " + NOT_FAILED_PRED +"-> "+ENVIRONMENT_UPDATE_HOUSEKEEPING_STR+";\n"; - buf+="\t[] "+STOP_PRED +" & !end -> (end'=true);\n"; - buf+="\t[] !end " + ENVIRONMENT_GUARD_STR + " &" + FAILED_PRED + "-> (end'=true);\n"; - buf+="endmodule\n\n"; - return buf; - } - - /** - * @return String PRISM encoding for the robot process - * @param boolean inhibitTactics if true, it does not generate any tactic commands (just movement commands) - */ - public static String generateRobotModule(boolean inhibitTactics){ - String buf="// Robot process\n\n"; - buf+="const "+ROBOT_BATTERY_RANGE_MAX_CONST+"="+ROBOT_BATTERY_RANGE_MAX+";\n"; - buf+="const "+INITIAL_ROBOT_BATTERY_CONST+";\n"; - buf+="const "+INITIAL_ROBOT_HEADING_CONST+";\n"; - buf+="const "+ROBOT_MAX_RECONF_CONST+"="+ROBOT_MAX_RECONF_VAL+";\n"; - - buf+="\n"+generateBatteryUpdates(); - buf+="module "+ROBOT_PLAYER_NAME+MODULE_POSTFIX_STR+"\n"; - buf+=ROBOT_BATTERY_VAR+":["+ROBOT_BATTERY_RANGE_MIN+".."+ROBOT_BATTERY_RANGE_MAX_CONST+"] init "+INITIAL_ROBOT_BATTERY_CONST+";\n"; - buf+=ROBOT_LOCATION_VAR+":[-1..1000] init "+INITIAL_ROBOT_LOCATION_CONST+";\n"; -// buf+=ROBOT_LOCATION_VAR+":[0.."+m_map.getNodeCount()+"] init "+INITIAL_ROBOT_LOCATION_CONST+";\n"; - buf+=ROBOT_CONF_VAR+":[-1.."+m_cp.getConfigurations().size()+"] init "+INITIAL_ROBOT_CONF_CONST+";\n"; - buf+=ROBOT_HEADING_VAR+":[0.."+String.valueOf(MissionState.Heading.values().length)+"] init "+INITIAL_ROBOT_HEADING_CONST+";\n"; - String initRCVal="0"; - if (inhibitTactics) - initRCVal="1"; - buf+=ROBOT_RECONF_VAR+":[0.."+ROBOT_MAX_RECONF_VAL+"] init "+initRCVal+";\n"; - buf+=ROBOT_COLLISION_VAR+": bool init false;\n"; - - buf+="robot_done:bool init false;\n"; - buf+="\t[] true "+ROBOT_GUARD_STR+" "+STOP_GUARD_STR+" & (robot_done) -> (robot_done'=false)"+ROBOT_UPDATE_HOUSEKEEPING_STR+";\n"; - if (!inhibitTactics) { - buf+="\n"+generateTacticCommands(); - } - buf+="\n"+generateMoveCommands(); - buf+="endmodule\n\n"; - return buf; - - } - - /** - * Generates battery update formulas employed in updates of movement commands in robot module - * @return String PRISM encoding for possible battery updates (corresponding to movements between map locations) - */ - - private static String getDeltaEnergy(Configuration config, double distance){ - return String.valueOf (Math.round (config.getSpeed()*distance*config.getEnergyDischargeRate())); - } - - public static String generateBatteryUpdates(){ - synchronized (m_map) { - String buf=""; -// buf+="formula b_upd_charge = min("+ROBOT_BATTERY_VAR+"+"+String.valueOf(Math.round (bp.batteryCharge(ROBOT_CHARGING_TIME)))+", "+ROBOT_BATTERY_RANGE_MAX_CONST+");\n\n"; - buf+="formula b_upd_charge = "+ROBOT_BATTERY_RANGE_MAX_CONST+";\n\n"; - for (int i=0;i battery_deltas = new HashMap(); - for (Map.Entry c: m_cp.getConfigurations().entrySet()){ - battery_deltas.put(c.getKey(),getDeltaEnergy(c.getValue(), t_distance)); - } - - String rote = ROTATION_ENERGY_FORMULA_PREFIX+a.getSource()+MOVE_CMD_STR+a.getTarget(); - - String formulaBaseName = BATTERY_UPDATE_STR+"_"+a.getSource()+"_"+a.getTarget(); - buf+="formula " + formulaBaseName + "= "; - int counter=0; - for (Map.Entry d: battery_deltas.entrySet()){ - if (counter>0) buf += " : "; - buf += ROBOT_CONF_VAR + "=" + d.getKey() + "? max(0,"+ROBOT_BATTERY_VAR+"-("+d.getValue()+"+"+rote+"))"; - counter++; - } - buf += ": 0;\n"; - } - return buf+"\n"; - } - } - - - /** - * Generates PRISM encoding for movement commands between locations in the robot module - * @return String encoding between location command strings - */ - public static String generateMoveCommands(){ - synchronized (m_map) { - String buf=""; - String confStr=""; - for (int i=0;i0) & ("+ROBOT_LOCATION_VAR+"="+a.getSource()+") "+" & ("+ROBOT_BATTERY_VAR+">="+BATTERY_UPDATE_STR+"_"+a.getSource()+"_"+a.getTarget()+")"+STOP_GUARD_STR+" "+ROBOT_GUARD_STR+" & (!robot_done) -> ("+ROBOT_LOCATION_VAR+"'="+a.getTarget()+") "+" & ("+ROBOT_BATTERY_VAR+"'="+BATTERY_UPDATE_STR+"_"+a.getSource()+"_"+a.getTarget()+")"+ " & ("+ROBOT_HEADING_VAR+"'="+HEADING_CONST_PREFIX + findArcHeading(a).name() + ") & (robot_done'=true);\n"; - //System.out.println("\t ["+a.getSource()+MOVE_CMD_STR+a.getTarget()+"] does not include hitrates"); - m_generated_movecommands.add(a.getSource()+MOVE_CMD_STR+a.getTarget()); - } else { // If collision risk exist, generate alternative probabilistic branches - Set successfulConfs = new HashSet<>(); - for (Map.Entry c: m_cp.getConfigurations().entrySet()){ - confStr=m_cp.translateId(c.getKey()); - if ((a.getSuccessRate(confStr)>=TRAVERSAL_SUCCESS_THRESHOLD)|| - (!a.existsSuccessRateAboveThreshold(TRAVERSAL_SUCCESS_THRESHOLD) && - (a.getSuccessRate(confStr)==(a.getMaxSuccessRate())))){ - if (a.getHitRate(confStr)>=0){ - successfulConfs.add(c.getKey()); - m_generated_movecommands.add(a.getSource()+MOVE_CMD_STR+a.getTarget()); - String confGuard = "("+ROBOT_CONF_VAR+"="+c.getValue().getId()+")"; - buf+="\t ["+a.getSource()+MOVE_CMD_STR+a.getTarget()+"] ("+ ROBOT_RECONF_VAR +">0) & ("+ROBOT_LOCATION_VAR+"="+a.getSource()+") "+" & ("+ROBOT_BATTERY_VAR+">="+BATTERY_UPDATE_STR+"_"+a.getSource()+"_"+a.getTarget()+")"+STOP_GUARD_STR+" "+ROBOT_GUARD_STR+" & "+confGuard+" & (!robot_done) -> "; - - String mainUpdateStr = "("+ROBOT_LOCATION_VAR+"'="+a.getTarget()+") "+" & ("+ROBOT_BATTERY_VAR+"'="+BATTERY_UPDATE_STR+"_"+a.getSource()+"_"+a.getTarget()+")"+ " & ("+ROBOT_HEADING_VAR+"'="+HEADING_CONST_PREFIX + findArcHeading(a).name() + ") & (robot_done'=true)"; - - if (a.getHitRate(confStr)>0.0){ - hitRateComplementGuard = String.valueOf(1.0-a.getHitRate(confStr)) + ": "; - hitRateGuard = String.valueOf(a.getHitRate(confStr)) + ": "; - buf+= " "+ hitRateGuard + mainUpdateStr + " & ("+ROBOT_COLLISION_VAR+"'=true)"; - buf+= " + "+ hitRateComplementGuard + mainUpdateStr + " & ("+ROBOT_COLLISION_VAR+"'=false);\n"; - } else { - buf+= " "+ mainUpdateStr+";\n"; - } - } - } - else { - String s = a.m_source + " -> " + a.m_target + " Unsuccessful under " + confStr; - s = s + "\n"; - } - } - // if not all confs are successful - // confGuard = for c in successful_confs : confGuard + "c!=" + c + "&" - if (!successfulConfs.containsAll(m_cp.getConfigurations().keySet())) { - StringBuffer confGuard = new StringBuffer("("); - for (Iterator iterator = successfulConfs.iterator(); iterator.hasNext();) { - String c = iterator.next(); - confGuard.append(ROBOT_CONF_VAR).append("!=").append(c); - if (iterator.hasNext()) confGuard.append("&"); - } - confGuard.append(")"); - buf += "\t [" + a.getSource() + MOVE_CMD_STR + a.getTarget()+"] ("+ ROBOT_RECONF_VAR +">0) & ("+ROBOT_LOCATION_VAR+"="+a.getSource() + ")" + STOP_GUARD_STR + " " + ROBOT_GUARD_STR + "& " + confGuard.toString() + " & (!robot_done) -> (l'=lfailed) & (robot_done'=true);\n" ; - } - - } - } - } - return buf+"\n"; - } - } - - /** - * Returns PRISM encoding for robot module tactics - * @return - */ - public static String generateTacticCommands(){ - String buf=""; - buf += generateReconfTacticCommands(); - buf += generateChargingTacticCommands(); - return buf; - } - - /** - * Returns PRISM encoding for robot module tactics - * @return - */ - public static String generateReconfTacticCommands(){ - String reconfGuard = "& ("+ROBOT_RECONF_VAR+"<"+ROBOT_MAX_RECONF_CONST+") "; - String reconfUpdate = "& ("+ROBOT_RECONF_VAR+"'="+ROBOT_RECONF_VAR+"+1) "; - String buf=""; - for (Map.Entry c: m_cp.getLegalTargetConfigurations().entrySet()){ -// buf+= "\t [t_set_"+c.getValue().getId()+"] ("+ROBOT_CONF_VAR+"!="+ROBOT_CONF_PREFIX+c.getValue().getId()+") "+reconfGuard +STOP_GUARD_STR+" "+ROBOT_GUARD_STR+" & (!robot_done) -> ("+ROBOT_CONF_VAR+"'="+ROBOT_CONF_PREFIX+c.getValue().getId()+")"+ reconfUpdate +" & (robot_done'=true);\n"; - - String reconfCostGuard = ""; - String reconfCostUpdate = ""; - if (CONSIDER_RECONFIGURATION_COST){ - Double rc = c.getValue().getEnergyDischargeRate() * m_cp.getReconfigurationTime("",c.getValue().getId()); - String reconfCost = String.valueOf(rc.intValue()); -// System.out.println("COST OF Reconfiguring to "+c.getValue().getId()+": " +reconfCost); - reconfCostGuard = " & ("+ROBOT_BATTERY_VAR+">"+reconfCost+") "; - reconfCostUpdate = "& ("+ROBOT_BATTERY_VAR+"'="+ROBOT_BATTERY_VAR+"-"+reconfCost+") "; - } - buf+= "\t [t_set_"+c.getValue().getId()+"] ("+ROBOT_CONF_VAR+"!="+c.getValue().getId()+") "+ reconfCostGuard + reconfGuard +STOP_GUARD_STR+" "+ROBOT_GUARD_STR+" & (!robot_done) -> ("+ROBOT_CONF_VAR+"'="+c.getValue().getId()+")"+ reconfUpdate + reconfCostUpdate +" & (robot_done'=true);\n"; - - } - return buf+"\n"; - } - - /** - * Returns PRISM encoding for robot module tactics (Charging) - * @return - */ - public static String generateChargingTacticCommands(){ - String guard_can_charge=" & (false"; - synchronized(m_map){ - for (Map.Entry e: m_map.getNodes().entrySet()){ - if (e.getValue().isChargingStation()){ - guard_can_charge +="|"+ROBOT_LOCATION_VAR+"="+e.getValue().getId(); - - } - } -// guard_can_charge+=") & ("+ROBOT_BATTERY_VAR+"<1500*"+String.valueOf(BatteryPredictor.m_battery_scaling_factor)+")"; //TODO: refine this constraint - guard_can_charge+=") & ("+ROBOT_BATTERY_VAR+"<"+ROBOT_BATTERY_RANGE_MAX+")"; //TODO: refine this constraint - } - - String buf="\t // Recharge tactics\n"; - buf+="\t [t_recharge] true "+ guard_can_charge +STOP_GUARD_STR+" "+ROBOT_GUARD_STR+" & (!robot_done) -> ("+ROBOT_BATTERY_VAR+"'=b_upd_charge"+")"+" & (robot_done'=true);\n"; - return buf+"\n"; - } - - /** - * @return String PRISM encoding for time rewards associated with an EnvMap - * @param inhibitTactics boolean if true, it does not generate rewards associated with tactics - */ - - private static String getDeltaTime(Configuration config, double distance){ - return String.valueOf (Math.round (config.getSpeed()*distance)); - } - - public static String generateTimeReward(boolean inhibitTactics){ - synchronized (m_map) { - String buf="rewards \"time\"\n"; - NumberFormat f = new DecimalFormat("#0.0000"); - - - // Robot recharging tactics - if (!inhibitTactics){ - // buf+="\t[t_set_half_speed] true : "+String.valueOf(DEFAULT_TIME_TACTIC_TIME)+";\n"; - buf+="\t[t_recharge] true : ("+ROBOT_BATTERY_RANGE_MAX+" - "+ROBOT_BATTERY_VAR+")/"+String.valueOf(ROBOT_BATTERY_CHARGING_RATIO)+";\n"; - } - - // Robot movement tactics - for (int i=0;i time_deltas = new HashMap(); - for (Map.Entry c: m_cp.getConfigurations().entrySet()){ - String confStr=m_cp.translateId(c.getKey()); - if (a.getTime(confStr)>0.0) // If we have timing information for the configuration in that arc - time_deltas.put(c.getKey(), String.valueOf(a.getTime(confStr))); - else // Otherwise, we just use the speed estimation formula - time_deltas.put(c.getKey(),getDeltaTime(c.getValue(), t_distance)); - } - - buf+="\t["+action_name+"] true :"; - int counter=0; - for (Map.Entry d: time_deltas.entrySet()){ - if (counter>0) buf += " : "; - buf += ROBOT_CONF_VAR + "=" + d.getKey() + " ? "+d.getValue(); - counter++; - } - buf += ": 99999;\n"; - - } - } - - // Robot reconfiguration tactics - if (!inhibitTactics){ - for (Map.Entry c: m_cp.getLegalTargetConfigurations().entrySet()){ - buf+= "\t [t_set_"+c.getValue().getId()+"] true :"; - int counter=0; +package org.sa.rainbow.brass.plan.p2; + + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.text.DecimalFormat; +import java.text.MessageFormat; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Stack; + +import org.apache.log4j.Logger; +import org.sa.rainbow.brass.confsynthesis.Configuration; +import org.sa.rainbow.brass.confsynthesis.ConfigurationProvider; +import org.sa.rainbow.brass.confsynthesis.ConfigurationSynthesizer; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.EnvMapArc; +import org.sa.rainbow.brass.model.map.EnvMapNode; +import org.sa.rainbow.brass.model.map.EnvMapPath; +import org.sa.rainbow.brass.model.map.dijkstra.Dijkstra; +import org.sa.rainbow.brass.model.map.dijkstra.Edge; +import org.sa.rainbow.brass.model.map.dijkstra.Graph; +import org.sa.rainbow.brass.model.map.dijkstra.Vertex; +import org.sa.rainbow.brass.model.mission.MissionState; + +import com.google.common.base.Objects; + +/** + * @author jcamara + * + * Eventually, the MapTranslator might be moved into a more general + * translator incorporating elements from the architecture model, etc. + */ + + +public class MapTranslator { + + public static final String VERSION_STR = "V0.5a - April 2018"; + + public static final String MODEL_TYPE = "mdp"; + public static final String MODULE_POSTFIX_STR = "_module"; + public static final String TURN_VARIABLE = "turn"; + public static final String MOVE_CMD_STR = "_to_"; + public static final String MIN_POSTFIX = "_min"; + public static final String MAX_POSTFIX = "_max"; + public static final String INIT_POSTFIX = "_init"; + public static final String UPDATE_POSTFIX = "_upd"; + public static final String HEADING_CONST_PREFIX="H_"; + public static final String ROTATION_TIME_FORMULA_PREFIX="rot_time_"; + public static final String ROTATION_ENERGY_FORMULA_PREFIX="rot_energy_"; + public static final String ENVIRONMENT_TURN_STR = "ET"; + public static final String ROBOT_TURN_STR = "RT"; + + + // Environment Configuration constants + + public static final String ENVIRONMENT_PLAYER_NAME = "env"; + public static final String ENVIRONMENT_UPDATE_HOUSEKEEPING_STR = " ("+TURN_VARIABLE+"'="+ROBOT_TURN_STR+")"; + public static final String ENVIRONMENT_GUARD_STR = "& (turn="+ENVIRONMENT_TURN_STR+")"; + + // Robot Configuration constants + + public static final String ROBOT_PLAYER_NAME = "bot"; + public static final String ROBOT_GUARD_STR = "& (turn="+ROBOT_TURN_STR+")"; + public static final String ROBOT_UPDATE_HOUSEKEEPING_STR = " & ("+TURN_VARIABLE+"'="+ENVIRONMENT_TURN_STR+")"; + public static final String ROBOT_LOCATION_VAR = "l"; + public static final String INITIAL_ROBOT_LOCATION_CONST = "INITIAL_LOCATION"; + public static final String TARGET_ROBOT_LOCATION_CONST = "TARGET_LOCATION"; + public static final String ROBOT_BATTERY_VAR = "b"; + public static final String ROBOT_BATTERY_RANGE_MIN = "0"; + public static long ROBOT_BATTERY_RANGE_MAX = 180000; + public static Double ROBOT_BATTERY_CHARGING_RATIO = BatteryPredictor.getChargingTimeRatio(); + public static final String ROBOT_BATTERY_RANGE_MAX_CONST = "MAX_BATTERY"; + public static final String INITIAL_ROBOT_BATTERY_CONST = "INITIAL_BATTERY"; + public static final String ROBOT_BATTERY_DELTA = "10"; // Constant for the time being, this should be transition+context dependent + public static final String BATTERY_GUARD_STR="& ("+ROBOT_BATTERY_VAR+">="+ROBOT_BATTERY_DELTA+")"; // Not used for the time being (battery depletion condition covered by STOP_GUARD_STR) + public static final String BATTERY_UPDATE_STR = ROBOT_BATTERY_VAR+UPDATE_POSTFIX; + public static final float ROBOT_CHARGING_TIME = 15.0f; + + public static final float ROBOT_FULL_SPEED_VALUE = 0.68f; // m/s + public static final float ROBOT_HALF_SPEED_VALUE = 0.35f; + public static final float ROBOT_SAFE_SPEED_VALUE = 0.25f; + public static final float ROBOT_DR_SPEED_VALUE = 0.25f; // Dead reckoning speed value .. this is implicit in ROBOT_LOC_MODE_LO + public static final String ROBOT_FULL_SPEED_CONST = "FULL_SPEED"; // These are just symbolic constants for PRISM + public static final String ROBOT_HALF_SPEED_CONST = "HALF_SPEED"; + public static final String ROBOT_DR_SPEED_CONST = "DR_SPEED"; + public static final String ROBOT_SPEED_VAR = "s"; + + public static final float ROBOT_ROTATIONAL_SPEED_VALUE = 1.5f; // rad/s + public static final String ROBOT_HEADING_VAR = "r"; + public static final String INITIAL_ROBOT_HEADING_CONST = "INITIAL_HEADING"; + + public static final String ROBOT_CONF_VAR = "c"; + public static final String INITIAL_ROBOT_CONF_CONST = "INITIAL_CONFIGURATION"; + public static final String ROBOT_MAX_RECONF_CONST = "RECONF_MAX"; + public static final String ROBOT_RECONF_VAR = "cr"; + public static String ROBOT_MAX_RECONF_VAL = "1"; // Only reconfiguring at start of plan, for the time being... +// public static final String ROBOT_CONF_PREFIX = "sol_"; + + + public static final String ROBOT_COLLISION_VAR = "collided"; + + + public static final float MAXIMUM_KINECT_OFF_DISTANCE_VAL = 6.0f; // Maximum driving distance with kinect off in m. + +// public static Double TRAVERSAL_SUCCESS_THRESHOLD=0.9; // Tolerance for map arc traversal success rate (if lower, segment not considered as a valid map trajectory in a given configuration) + public static Double TRAVERSAL_SUCCESS_THRESHOLD=0.1; // Tolerance for map arc traversal success rate (if lower, segment not considered as a valid map trajectory in a given configuration) + public static final Double TRAVERSAL_HIT_THRESHOLD=0.1; // Tolerance for map arc traversal hit rate(if higher, segment not considered as a vaid map trajectory) + + // Goal and stop condition configuration constants + + public static final String GOAL_PRED="goal"; // Goal achieved predicate (currently target location reached) + public static final String GOAL_PRED_DEF=GOAL_PRED+" = "+ROBOT_LOCATION_VAR+"="+TARGET_ROBOT_LOCATION_CONST+";"; + + public static final String STOP_PRED = "stop"; // Stop condition predicate (currently target location reached of insufficient battery to move to a nearby location) +// public static final String STOP_PRED_DEF = STOP_PRED + " = "+GOAL_PRED+" | "+ROBOT_BATTERY_VAR+"<"+ROBOT_BATTERY_DELTA+";"; + public static final String STOP_PRED_DEF = STOP_PRED + " = "+GOAL_PRED+";"; + public static final String STOP_GUARD_STR = "& (!"+STOP_PRED+")"; + public static final String FAILED_PRED = "l=lfailed"; + public static final String NOT_FAILED_PRED="l!=lfailed"; + + public static final double MAX_DISTANCE = 999.0; // Distance assigned to disabled edges (for distance reward computation) + public static final double DEFAULT_TIME_TACTIC_TIME=1; // Tactics are not instantaneous; + public static final String TACTIC_PREFIX="t"; + + public static boolean CONSIDER_RECONFIGURATION_COST=false; + + // Properties' indices + public static final int TIME_PROPERTY = 0; + public static final int ACCURACY_PROPERTY = 1; + + private static EnvMap m_map; + private static ConfigurationProvider m_cp; + private static LinkedList m_generated_movecommands = new LinkedList(); + + + private static Logger LOGGER; + + public static Logger getLogger() { + return LOGGER; + } + + public static void setLogger(Logger lOGGER) { + LOGGER = lOGGER; + } + + public static void logInfo(String msg) { + if (LOGGER==null) { + System.out.println(msg); + } + else LOGGER.info(msg); + } + + public static void logError(String msg) { + if (LOGGER==null) { + System.out.println(msg); + } + else LOGGER.error(msg); + } + + /** + * Sets the Configuration provider + */ + public static void setConfigurationProvider(ConfigurationProvider cp){ + m_cp = cp; + } + + /** + * Sets the map to translate into a PRISM specification + * @param map an EnvMap encoding the graph that captures the physical space + */ + public static void setMap(EnvMap map){ + m_map = map; + } + + /** + * Generates PRISM model game structure - Alternating Robot/Environment turns + * @return String a string with the general declarations for PRISM model turn structure + */ + public static String generateGameStructure(){ + String buf=new String(); + buf+=MODEL_TYPE+"\n\n"; + buf+="const "+ENVIRONMENT_TURN_STR+"=0;\n"; + buf+="const "+ROBOT_TURN_STR+"=1;\n"; + buf+="\nglobal "+TURN_VARIABLE+":["+ENVIRONMENT_TURN_STR+".."+ROBOT_TURN_STR+"] init "+ENVIRONMENT_TURN_STR+";\n\n"; + return buf+"\n"; + } + + + /** + * Generates a list of labels for movement commands between locations + * @return LinkedString list of movement between location command strings + * Unused for the time being + */ + public static LinkedList generateMoveCommandStrs(){ + synchronized (m_map) { + LinkedList res = new LinkedList (); + LinkedList arcs = m_map.getArcs(); + for (int i=0; i entry : m_map.getNodes().entrySet() ){ + buf+="const "+entry.getKey()+"="+String.valueOf(entry.getValue().getId())+";\n"; +// buf+="const "+entry.getKey()+"="+String.valueOf(c)+";\n"; + c++; + } + buf += "const lfailed=-1; // location indicating failed transitions\n"; + return buf+"\n"; + } + + /** + * Generates labels for robot configurations + * @return String PRISM encoding for configuration constants + */ + public static String generateConfigurationConstants(){ + String buf="// Configuration constants\n\n"; + buf+="const "+INITIAL_ROBOT_CONF_CONST+";\n"; + int cid=0; + for (Map.Entry entry : m_cp.getConfigurations().entrySet() ){ + buf+="const "+entry.getKey()+"="+String.valueOf(cid)+";\n"; + cid+=1; + } + return buf+"\n"; + } + + /** + * @return String PRISM encoding for the environment process + */ + public static String generateEnvironmentModule(){ + String buf="// Environment process\n\n"; + buf+="module "+ENVIRONMENT_PLAYER_NAME+MODULE_POSTFIX_STR+"\n"; + buf+="end:bool init false;\n\n"; + buf+="\t[] true "+ENVIRONMENT_GUARD_STR +" "+STOP_GUARD_STR+" & " + NOT_FAILED_PRED +"-> "+ENVIRONMENT_UPDATE_HOUSEKEEPING_STR+";\n"; + buf+="\t[] "+STOP_PRED +" & !end -> (end'=true);\n"; + buf+="\t[] !end " + ENVIRONMENT_GUARD_STR + " &" + FAILED_PRED + "-> (end'=true);\n"; + buf+="endmodule\n\n"; + return buf; + } + + /** + * @return String PRISM encoding for the robot process + * @param boolean inhibitTactics if true, it does not generate any tactic commands (just movement commands) + */ + public static String generateRobotModule(boolean inhibitTactics){ + String buf="// Robot process\n\n"; + buf+="const "+ROBOT_BATTERY_RANGE_MAX_CONST+"="+ROBOT_BATTERY_RANGE_MAX+";\n"; + buf+="const "+INITIAL_ROBOT_BATTERY_CONST+";\n"; + buf+="const "+INITIAL_ROBOT_HEADING_CONST+";\n"; + buf+="const "+ROBOT_MAX_RECONF_CONST+"="+ROBOT_MAX_RECONF_VAL+";\n"; + + buf+="\n"+generateBatteryUpdates(); + buf+="module "+ROBOT_PLAYER_NAME+MODULE_POSTFIX_STR+"\n"; + buf+=ROBOT_BATTERY_VAR+":["+ROBOT_BATTERY_RANGE_MIN+".."+ROBOT_BATTERY_RANGE_MAX_CONST+"] init "+INITIAL_ROBOT_BATTERY_CONST+";\n"; + buf+=ROBOT_LOCATION_VAR+":[-1..1000] init "+INITIAL_ROBOT_LOCATION_CONST+";\n"; +// buf+=ROBOT_LOCATION_VAR+":[0.."+m_map.getNodeCount()+"] init "+INITIAL_ROBOT_LOCATION_CONST+";\n"; + buf+=ROBOT_CONF_VAR+":[-1.."+m_cp.getConfigurations().size()+"] init "+INITIAL_ROBOT_CONF_CONST+";\n"; + buf+=ROBOT_HEADING_VAR+":[0.."+String.valueOf(MissionState.Heading.values().length)+"] init "+INITIAL_ROBOT_HEADING_CONST+";\n"; + String initRCVal="0"; + if (inhibitTactics) + initRCVal="1"; + buf+=ROBOT_RECONF_VAR+":[0.."+ROBOT_MAX_RECONF_VAL+"] init "+initRCVal+";\n"; + buf+=ROBOT_COLLISION_VAR+": bool init false;\n"; + + buf+="robot_done:bool init false;\n"; + buf+="\t[] true "+ROBOT_GUARD_STR+" "+STOP_GUARD_STR+" & (robot_done) -> (robot_done'=false)"+ROBOT_UPDATE_HOUSEKEEPING_STR+";\n"; + if (!inhibitTactics) { + buf+="\n"+generateTacticCommands(); + } + buf+="\n"+generateMoveCommands(); + buf+="endmodule\n\n"; + return buf; + + } + + /** + * Generates battery update formulas employed in updates of movement commands in robot module + * @return String PRISM encoding for possible battery updates (corresponding to movements between map locations) + */ + + private static String getDeltaEnergy(Configuration config, double distance){ + return String.valueOf (Math.round (config.getSpeed()*distance*config.getEnergyDischargeRate())); + } + + public static String generateBatteryUpdates(){ + synchronized (m_map) { + String buf=""; +// buf+="formula b_upd_charge = min("+ROBOT_BATTERY_VAR+"+"+String.valueOf(Math.round (bp.batteryCharge(ROBOT_CHARGING_TIME)))+", "+ROBOT_BATTERY_RANGE_MAX_CONST+");\n\n"; + buf+="formula b_upd_charge = "+ROBOT_BATTERY_RANGE_MAX_CONST+";\n\n"; + for (int i=0;i battery_deltas = new HashMap(); + for (Map.Entry c: m_cp.getConfigurations().entrySet()){ + battery_deltas.put(c.getKey(),getDeltaEnergy(c.getValue(), t_distance)); + } + + String rote = ROTATION_ENERGY_FORMULA_PREFIX+a.getSource()+MOVE_CMD_STR+a.getTarget(); + + String formulaBaseName = BATTERY_UPDATE_STR+"_"+a.getSource()+"_"+a.getTarget(); + buf+="formula " + formulaBaseName + "= "; + int counter=0; + for (Map.Entry d: battery_deltas.entrySet()){ + if (counter>0) buf += " : "; + buf += ROBOT_CONF_VAR + "=" + d.getKey() + "? max(0,"+ROBOT_BATTERY_VAR+"-("+d.getValue()+"+"+rote+"))"; + counter++; + } + buf += ": 0;\n"; + } + return buf+"\n"; + } + } + + + /** + * Generates PRISM encoding for movement commands between locations in the robot module + * @return String encoding between location command strings + */ + public static String generateMoveCommands(){ + synchronized (m_map) { + String buf=""; + String confStr=""; + for (int i=0;i0) & ("+ROBOT_LOCATION_VAR+"="+a.getSource()+") "+" & ("+ROBOT_BATTERY_VAR+">="+BATTERY_UPDATE_STR+"_"+a.getSource()+"_"+a.getTarget()+")"+STOP_GUARD_STR+" "+ROBOT_GUARD_STR+" & (!robot_done) -> ("+ROBOT_LOCATION_VAR+"'="+a.getTarget()+") "+" & ("+ROBOT_BATTERY_VAR+"'="+BATTERY_UPDATE_STR+"_"+a.getSource()+"_"+a.getTarget()+")"+ " & ("+ROBOT_HEADING_VAR+"'="+HEADING_CONST_PREFIX + findArcHeading(a).name() + ") & (robot_done'=true);\n"; + //System.out.println("\t ["+a.getSource()+MOVE_CMD_STR+a.getTarget()+"] does not include hitrates"); + m_generated_movecommands.add(a.getSource()+MOVE_CMD_STR+a.getTarget()); + } else { // If collision risk exist, generate alternative probabilistic branches + Set successfulConfs = new HashSet<>(); + for (Map.Entry c: m_cp.getConfigurations().entrySet()){ + confStr=m_cp.translateId(c.getKey()); + if ((a.getSuccessRate(confStr)>=TRAVERSAL_SUCCESS_THRESHOLD)|| + (!a.existsSuccessRateAboveThreshold(TRAVERSAL_SUCCESS_THRESHOLD) && + (a.getSuccessRate(confStr)==(a.getMaxSuccessRate())))){ + if (a.getHitRate(confStr)>=0){ + successfulConfs.add(c.getKey()); + m_generated_movecommands.add(a.getSource()+MOVE_CMD_STR+a.getTarget()); + String confGuard = "("+ROBOT_CONF_VAR+"="+c.getValue().getId()+")"; + buf+="\t ["+a.getSource()+MOVE_CMD_STR+a.getTarget()+"] ("+ ROBOT_RECONF_VAR +">0) & ("+ROBOT_LOCATION_VAR+"="+a.getSource()+") "+" & ("+ROBOT_BATTERY_VAR+">="+BATTERY_UPDATE_STR+"_"+a.getSource()+"_"+a.getTarget()+")"+STOP_GUARD_STR+" "+ROBOT_GUARD_STR+" & "+confGuard+" & (!robot_done) -> "; + + String mainUpdateStr = "("+ROBOT_LOCATION_VAR+"'="+a.getTarget()+") "+" & ("+ROBOT_BATTERY_VAR+"'="+BATTERY_UPDATE_STR+"_"+a.getSource()+"_"+a.getTarget()+")"+ " & ("+ROBOT_HEADING_VAR+"'="+HEADING_CONST_PREFIX + findArcHeading(a).name() + ") & (robot_done'=true)"; + + if (a.getHitRate(confStr)>0.0){ + hitRateComplementGuard = String.valueOf(1.0-a.getHitRate(confStr)) + ": "; + hitRateGuard = String.valueOf(a.getHitRate(confStr)) + ": "; + buf+= " "+ hitRateGuard + mainUpdateStr + " & ("+ROBOT_COLLISION_VAR+"'=true)"; + buf+= " + "+ hitRateComplementGuard + mainUpdateStr + " & ("+ROBOT_COLLISION_VAR+"'=false);\n"; + } else { + buf+= " "+ mainUpdateStr+";\n"; + } + } + } + else { + String s = a.m_source + " -> " + a.m_target + " Unsuccessful under " + confStr; + s = s + "\n"; + } + } + // if not all confs are successful + // confGuard = for c in successful_confs : confGuard + "c!=" + c + "&" + if (!successfulConfs.containsAll(m_cp.getConfigurations().keySet())) { + StringBuffer confGuard = new StringBuffer("("); + for (Iterator iterator = successfulConfs.iterator(); iterator.hasNext();) { + String c = iterator.next(); + confGuard.append(ROBOT_CONF_VAR).append("!=").append(c); + if (iterator.hasNext()) confGuard.append("&"); + } + confGuard.append(")"); + buf += "\t [" + a.getSource() + MOVE_CMD_STR + a.getTarget()+"] ("+ ROBOT_RECONF_VAR +">0) & ("+ROBOT_LOCATION_VAR+"="+a.getSource() + ")" + STOP_GUARD_STR + " " + ROBOT_GUARD_STR + "& " + confGuard.toString() + " & (!robot_done) -> (l'=lfailed) & (robot_done'=true);\n" ; + } + + } + } + } + return buf+"\n"; + } + } + + /** + * Returns PRISM encoding for robot module tactics + * @return + */ + public static String generateTacticCommands(){ + String buf=""; + buf += generateReconfTacticCommands(); + buf += generateChargingTacticCommands(); + return buf; + } + + /** + * Returns PRISM encoding for robot module tactics + * @return + */ + public static String generateReconfTacticCommands(){ + String reconfGuard = "& ("+ROBOT_RECONF_VAR+"<"+ROBOT_MAX_RECONF_CONST+") "; + String reconfUpdate = "& ("+ROBOT_RECONF_VAR+"'="+ROBOT_RECONF_VAR+"+1) "; + String buf=""; + for (Map.Entry c: m_cp.getLegalTargetConfigurations().entrySet()){ +// buf+= "\t [t_set_"+c.getValue().getId()+"] ("+ROBOT_CONF_VAR+"!="+ROBOT_CONF_PREFIX+c.getValue().getId()+") "+reconfGuard +STOP_GUARD_STR+" "+ROBOT_GUARD_STR+" & (!robot_done) -> ("+ROBOT_CONF_VAR+"'="+ROBOT_CONF_PREFIX+c.getValue().getId()+")"+ reconfUpdate +" & (robot_done'=true);\n"; + + String reconfCostGuard = ""; + String reconfCostUpdate = ""; + if (CONSIDER_RECONFIGURATION_COST){ + Double rc = c.getValue().getEnergyDischargeRate() * m_cp.getReconfigurationTime("",c.getValue().getId()); + String reconfCost = String.valueOf(rc.intValue()); +// System.out.println("COST OF Reconfiguring to "+c.getValue().getId()+": " +reconfCost); + reconfCostGuard = " & ("+ROBOT_BATTERY_VAR+">"+reconfCost+") "; + reconfCostUpdate = "& ("+ROBOT_BATTERY_VAR+"'="+ROBOT_BATTERY_VAR+"-"+reconfCost+") "; + } + buf+= "\t [t_set_"+c.getValue().getId()+"] ("+ROBOT_CONF_VAR+"!="+c.getValue().getId()+") "+ reconfCostGuard + reconfGuard +STOP_GUARD_STR+" "+ROBOT_GUARD_STR+" & (!robot_done) -> ("+ROBOT_CONF_VAR+"'="+c.getValue().getId()+")"+ reconfUpdate + reconfCostUpdate +" & (robot_done'=true);\n"; + + } + return buf+"\n"; + } + + /** + * Returns PRISM encoding for robot module tactics (Charging) + * @return + */ + public static String generateChargingTacticCommands(){ + String guard_can_charge=" & (false"; + synchronized(m_map){ + for (Map.Entry e: m_map.getNodes().entrySet()){ + if (e.getValue().isChargingStation()){ + guard_can_charge +="|"+ROBOT_LOCATION_VAR+"="+e.getValue().getId(); + + } + } +// guard_can_charge+=") & ("+ROBOT_BATTERY_VAR+"<1500*"+String.valueOf(BatteryPredictor.m_battery_scaling_factor)+")"; //TODO: refine this constraint + guard_can_charge+=") & ("+ROBOT_BATTERY_VAR+"<"+ROBOT_BATTERY_RANGE_MAX+")"; //TODO: refine this constraint + } + + String buf="\t // Recharge tactics\n"; + buf+="\t [t_recharge] true "+ guard_can_charge +STOP_GUARD_STR+" "+ROBOT_GUARD_STR+" & (!robot_done) -> ("+ROBOT_BATTERY_VAR+"'=b_upd_charge"+")"+" & (robot_done'=true);\n"; + return buf+"\n"; + } + + /** + * @return String PRISM encoding for time rewards associated with an EnvMap + * @param inhibitTactics boolean if true, it does not generate rewards associated with tactics + */ + + private static String getDeltaTime(Configuration config, double distance){ + return String.valueOf (Math.round (config.getSpeed()*distance)); + } + + public static String generateTimeReward(boolean inhibitTactics){ + synchronized (m_map) { + String buf="rewards \"time\"\n"; + NumberFormat f = new DecimalFormat("#0.0000"); + + + // Robot recharging tactics + if (!inhibitTactics){ + // buf+="\t[t_set_half_speed] true : "+String.valueOf(DEFAULT_TIME_TACTIC_TIME)+";\n"; + buf+="\t[t_recharge] true : ("+ROBOT_BATTERY_RANGE_MAX+" - "+ROBOT_BATTERY_VAR+")/"+String.valueOf(ROBOT_BATTERY_CHARGING_RATIO)+";\n"; + } + + // Robot movement tactics + for (int i=0;i time_deltas = new HashMap(); + for (Map.Entry c: m_cp.getConfigurations().entrySet()){ + String confStr=m_cp.translateId(c.getKey()); + if (a.getTime(confStr)>0.0) // If we have timing information for the configuration in that arc + time_deltas.put(c.getKey(), String.valueOf(a.getTime(confStr))); + else // Otherwise, we just use the speed estimation formula + time_deltas.put(c.getKey(),getDeltaTime(c.getValue(), t_distance)); + } + + buf+="\t["+action_name+"] true :"; + int counter=0; + for (Map.Entry d: time_deltas.entrySet()){ + if (counter>0) buf += " : "; + buf += ROBOT_CONF_VAR + "=" + d.getKey() + " ? "+d.getValue(); + counter++; + } + buf += ": 99999;\n"; + + } + } + + // Robot reconfiguration tactics + if (!inhibitTactics){ + for (Map.Entry c: m_cp.getLegalTargetConfigurations().entrySet()){ + buf+= "\t [t_set_"+c.getValue().getId()+"] true :"; + int counter=0; String reconfCost = "0"; - for (Map.Entry cs: m_cp.getLegalTargetConfigurations().entrySet()){ - if (CONSIDER_RECONFIGURATION_COST){ - reconfCost = String.valueOf(m_cp.getReconfigurationTime(cs.getValue().getId(),c.getValue().getId())); - } - if (counter>0) buf += " : "; - buf+= ROBOT_CONF_VAR + "=" + cs.getKey() + " ? "+ reconfCost; - counter++; - } + for (Map.Entry cs: m_cp.getLegalTargetConfigurations().entrySet()){ + if (CONSIDER_RECONFIGURATION_COST){ + reconfCost = String.valueOf(m_cp.getReconfigurationTime(cs.getValue().getId(),c.getValue().getId())); + } + if (counter>0) buf += " : "; + buf+= ROBOT_CONF_VAR + "=" + cs.getKey() + " ? "+ reconfCost; + counter++; + } buf += ": "+reconfCost+";\n"; - } - } - buf+="endrewards\n\n"; - return buf; - } - } - - - /** - * @return PRISM encoding for all rotation formulas (for all arcs in map) - */ - public static String generateRotationTimeFormulas(){ - String buf="// Rotation time formulas for map arcs\n"; - synchronized (m_map) { - for (int i=0;i Math.PI) ? 2*Math.PI - theta : theta; - return (min_theta/ROBOT_ROTATIONAL_SPEED_VALUE); - } - - - /** - * Determines the angle (in Radians) between two endpoints of an arc, taking the source node of the arc - * as the reference of coordinates in the plane. Used to determine the part of the time reward structure - * associated with in-node robot rotations. - * @param a Map arc - * @return angle in radians between a.m_source and a.m_target - */ - public static double findArcOrientation(EnvMapArc a){ - synchronized (m_map) { - double nodeX = m_map.getNodeX(a.getSource()); - double nodeY = m_map.getNodeY(a.getSource()); - double nodeX2 = m_map.getNodeX(a.getTarget()); - double nodeY2 = m_map.getNodeY(a.getTarget()); - if (nodeX == Double.NEGATIVE_INFINITY || nodeX2 == Double.NEGATIVE_INFINITY) return 0; - return findArcOrientation( nodeX, nodeY, nodeX2, nodeY2); - } - } - - - public static double findArcOrientation(double src_x, double src_y, double tgt_x, double tgt_y){ - return Math.atan2( tgt_y - src_y, tgt_x - src_x); - } - - - /** - * Determines the heading between two endpoints of an arc (snaps result of findArcOrientation to one of the predetermined headings) - * @param a Map arc - * @return heading enum arc heading - */ - public static MissionState.Heading findArcHeading (EnvMapArc a) { - return MissionState.Heading.convertFromRadians(findArcOrientation(a)); - } - - - public static Stack connectionPath = null; // Aux data structures for finding all paths between arbitrary locations - public static List connectionPaths = null; - - - /** - * Generates all non-cyclic paths between two locations in map - * @param node1 - * @param node2 - */ - public static List goFindAllPaths(String node1, String node2){ - connectionPath = new Stack(); - connectionPath.push(node1); - connectionPaths = new ArrayList<>(); - - findAllPaths (node1, node2); - for (int i=0; i(); - for (String node1 : connectionPath) { - temp.add(node1); - } - connectionPaths.add(temp); - } else if (!connectionPath.contains(nextNode)) { - connectionPath.push(nextNode); - findAllPaths(nextNode, tgt); - connectionPath.pop(); - } - } - - } - - /** - * Translates a path into a PRISM module constraining the movements of the robot to that path - * @param path List of strings with the locations of the path from source to target (e.g., ["ls", ..., "l1"]) - * @return String PRISM encoding of the path constraint module - */ - public static String generatePathConstraintModule(List path){ - String buf="\n"+"module path_constraint\n"; - LinkedList allowed = new LinkedList(); - for (int i=0; i< path.size()-1; i++){ - allowed.add(path.get(i)+ MOVE_CMD_STR + path.get(i+1)); - } - buf+= "// Allowed arcs: "+ String.valueOf(allowed) + "\n"; - synchronized(m_map) { - for (EnvMapArc a : m_map.getArcs()){ - String str_arc= a.getSource() + MOVE_CMD_STR + a.getTarget(); - if (!allowed.contains(str_arc)) { - buf += "\t[" + str_arc + "] false -> true; \n"; - } - } - } - buf += "endmodule\n"; - return buf; - } - + } + } + buf+="endrewards\n\n"; + return buf; + } + } + + + /** + * @return PRISM encoding for all rotation formulas (for all arcs in map) + */ + public static String generateRotationTimeFormulas(){ + String buf="// Rotation time formulas for map arcs\n"; + synchronized (m_map) { + for (int i=0;i Math.PI) ? 2*Math.PI - theta : theta; + return (min_theta/ROBOT_ROTATIONAL_SPEED_VALUE); + } + + + /** + * Determines the angle (in Radians) between two endpoints of an arc, taking the source node of the arc + * as the reference of coordinates in the plane. Used to determine the part of the time reward structure + * associated with in-node robot rotations. + * @param a Map arc + * @return angle in radians between a.m_source and a.m_target + */ + public static double findArcOrientation(EnvMapArc a){ + synchronized (m_map) { + double nodeX = m_map.getNodeX(a.getSource()); + double nodeY = m_map.getNodeY(a.getSource()); + double nodeX2 = m_map.getNodeX(a.getTarget()); + double nodeY2 = m_map.getNodeY(a.getTarget()); + if (nodeX == Double.NEGATIVE_INFINITY || nodeX2 == Double.NEGATIVE_INFINITY) return 0; + return findArcOrientation( nodeX, nodeY, nodeX2, nodeY2); + } + } + + + public static double findArcOrientation(double src_x, double src_y, double tgt_x, double tgt_y){ + return Math.atan2( tgt_y - src_y, tgt_x - src_x); + } + + + /** + * Determines the heading between two endpoints of an arc (snaps result of findArcOrientation to one of the predetermined headings) + * @param a Map arc + * @return heading enum arc heading + */ + public static MissionState.Heading findArcHeading (EnvMapArc a) { + return MissionState.Heading.convertFromRadians(findArcOrientation(a)); + } + + + public static Stack connectionPath = null; // Aux data structures for finding all paths between arbitrary locations + public static List connectionPaths = null; + + + /** + * Generates all non-cyclic paths between two locations in map + * @param node1 + * @param node2 + */ + public static List goFindAllPaths(String node1, String node2){ + connectionPath = new Stack(); + connectionPath.push(node1); + connectionPaths = new ArrayList<>(); + + findAllPaths (node1, node2); + for (int i=0; i(); + for (String node1 : connectionPath) { + temp.add(node1); + } + connectionPaths.add(temp); + } else if (!connectionPath.contains(nextNode)) { + connectionPath.push(nextNode); + findAllPaths(nextNode, tgt); + connectionPath.pop(); + } + } + + } + + /** + * Translates a path into a PRISM module constraining the movements of the robot to that path + * @param path List of strings with the locations of the path from source to target (e.g., ["ls", ..., "l1"]) + * @return String PRISM encoding of the path constraint module + */ + public static String generatePathConstraintModule(List path){ + String buf="\n"+"module path_constraint\n"; + LinkedList allowed = new LinkedList(); + for (int i=0; i< path.size()-1; i++){ + allowed.add(path.get(i)+ MOVE_CMD_STR + path.get(i+1)); + } + buf+= "// Allowed arcs: "+ String.valueOf(allowed) + "\n"; + synchronized(m_map) { + for (EnvMapArc a : m_map.getArcs()){ + String str_arc= a.getSource() + MOVE_CMD_STR + a.getTarget(); + if (!allowed.contains(str_arc)) { + buf += "\t[" + str_arc + "] false -> true; \n"; + } + } + } + buf += "endmodule\n"; + return buf; + } + /** * Translates a set of reconfiguration actions into a PRISM module constraining the reconfigurations of the robot to those @@ -745,375 +746,375 @@ public static String generateReconfigurationConstraintModule(List allowed){ } - /** - * Translates a plan into a PRISM module constraining the action of the robots to that plan00 - * @param plan List of strings (e.g., ["l1_to_l2", ..., "t_recharge", ..., "l4_to_l5"]) - * @return String PRISM encoding of the plan constraint module - */ - public static String generatePlanConstraintModule(List plan){ - LinkedList allTactics = new LinkedList(Arrays.asList("t_set_loc_lo", "t_set_loc_med", "t_set_loc_hi", "t_set_half_speed", "t_set_full_speed", "t_recharge")); - - String buf="\n"+"module plan_constraint\n"; - buf+= "pc_s : [0.."+String.valueOf(plan.size())+"] init 0;\n"; - for (int i=0; i< plan.size(); i++){ - buf += "\t["+plan.get(i)+"] (pc_s="+String.valueOf(i)+") -> (pc_s'="+String.valueOf(i+1)+"); \n"; - } - - LinkedList allowed = new LinkedList(); - for (int i=0; i< plan.size(); i++){ - String action = plan.get(i); - String[] e = action.split("_"); - if (!Objects.equal(MapTranslator.TACTIC_PREFIX, e[0])) { - allowed.add(plan.get(i)); - } - } - buf+="\t // Disallowed tactics\n"; - for (int i=0; i< allTactics.size(); i++){ - String action = allTactics.get(i); - if (!plan.contains(action)) { - buf += "\t[" + action + "] false -> true; \n"; - } - } - - buf+= "\t // Allowed arcs: "+ String.valueOf(allowed) + "\n"; - buf+="\t // Disallowed arcs\n"; - synchronized(m_map) { - for (EnvMapArc a : m_map.getArcs()){ - String str_arc= a.getSource() + MOVE_CMD_STR + a.getTarget(); - if (!allowed.contains(str_arc)) { - buf += "\t[" + str_arc + "] false -> true; \n"; - } - } - } - - buf += "endmodule\n"; - return buf; - } - - - /** - * Returns shortest distance between two nodes computed using Dijkstra's Algorithm - * @param node1 String label of source node (associated with an EnvMapNode in the map to translate) - * @param node2 String label of target node (associated with an EnvMapNode in the map to translate) - * @return float shortest distance between node1 and node2 - */ - public static double shortestPathDistance (String node1, String node2) { - synchronized (m_map) { - Graph graph = new Graph(); - Vertex[] vertices = new Vertex[m_map.getNodeCount()]; - - Map node_indexes = new HashMap<> (); - - int i=0; - for (Map.Entry entry : m_map.getNodes().entrySet() ){ - vertices[i] = new Vertex(entry.getKey()); - graph.addVertex(vertices[i], true); - node_indexes.put (entry.getKey (), i); - i++; - } - - Edge[] edges = new Edge[m_map.getUniqueArcCount()]; - - for (i=0;i entry : m_map.getNodes().entrySet() ){ - String v = entry.getKey(); - - buf+="\t"+STOP_PRED+" & "+TARGET_ROBOT_LOCATION_CONST+"="+v+" : "; - - for (Map.Entry entry2 : m_map.getNodes().entrySet() ){ - String v2 = entry2.getKey(); - if (!v2.equals(v)){ - buf += ROBOT_LOCATION_VAR + "=" + v2 + " ? " + f.format (shortestPathDistance (v, v2)) + " : "; - } - } - buf+=" 0;\n"; - - } - buf+="endrewards\n\n"; - return buf; - } - } - - - /** - * @return String PRISM encoding for energy rewards at the end of the execution - */ - public static String generateEnergyReward(){ - synchronized (m_map) { - String buf="rewards \"energy\"\n"; - buf+="\t"+STOP_PRED+"& " + NOT_FAILED_PRED + " : "+ROBOT_BATTERY_VAR+";\n"; - buf+="\t"+FAILED_PRED + ": 0;\n"; - buf+="endrewards\n\n"; - return buf; - } - } - - - /** - * Generates the PRISM specification for an adaptation scenario, based on a given EnvMap - * @param inhibitTactics boolean if true, it generates a specification only with move actions, disabling the rest of actions and tactics - * @return String PRISM encoding for adaptation scenario - */ - - public static String getMapTranslation(){ - return getMapTranslation(false); - } - - public static EnvMap getMap(){ - - return m_map; - - } - - public static String getMapTranslation(boolean inhibitTactics){ - String buf="// Generated by BRASS MARS Robot Map PRISM Translator "+VERSION_STR+".\n\n"; - buf+=generateGameStructure()+"\n"; - buf+=generateHeadingConstants()+"\n"; - buf+=generateConfigurationConstants()+"\n"; - buf+=generateLocationConstants()+"\n"; - buf+=generateEnvironmentModule()+"\n"; - buf+=generateRobotModule(inhibitTactics)+"\n"; - buf+=generateTimeReward(inhibitTactics)+"\n"; - buf+=generateRotationTimeFormulas()+"\n"; - buf+=generateRotationEnergyFormulas()+"\n"; -// buf+=generateDistanceReward()+"\n"; // Used in Phase 1 only - buf+=generateEnergyReward()+"\n"; - buf+="// --- End of generated code ---\n"; - m_generated_movecommands.clear(); // Housekeeping - return buf; - } - - - - /** - * Generates the PRISM specification for an adaptation scenario, constrained to a specific path of robot movements - * @param path List of strings containing the sequence of locations in the path, e.g., ["l1", ..., "l8"] - * @return String PRISM encoding for constrained adaptation scenario - */ - + /** + * Translates a plan into a PRISM module constraining the action of the robots to that plan00 + * @param plan List of strings (e.g., ["l1_to_l2", ..., "t_recharge", ..., "l4_to_l5"]) + * @return String PRISM encoding of the plan constraint module + */ + public static String generatePlanConstraintModule(List plan){ + LinkedList allTactics = new LinkedList(Arrays.asList("t_set_loc_lo", "t_set_loc_med", "t_set_loc_hi", "t_set_half_speed", "t_set_full_speed", "t_recharge")); + + String buf="\n"+"module plan_constraint\n"; + buf+= "pc_s : [0.."+String.valueOf(plan.size())+"] init 0;\n"; + for (int i=0; i< plan.size(); i++){ + buf += "\t["+plan.get(i)+"] (pc_s="+String.valueOf(i)+") -> (pc_s'="+String.valueOf(i+1)+"); \n"; + } + + LinkedList allowed = new LinkedList(); + for (int i=0; i< plan.size(); i++){ + String action = plan.get(i); + String[] e = action.split("_"); + if (!Objects.equal(MapTranslator.TACTIC_PREFIX, e[0])) { + allowed.add(plan.get(i)); + } + } + buf+="\t // Disallowed tactics\n"; + for (int i=0; i< allTactics.size(); i++){ + String action = allTactics.get(i); + if (!plan.contains(action)) { + buf += "\t[" + action + "] false -> true; \n"; + } + } + + buf+= "\t // Allowed arcs: "+ String.valueOf(allowed) + "\n"; + buf+="\t // Disallowed arcs\n"; + synchronized(m_map) { + for (EnvMapArc a : m_map.getArcs()){ + String str_arc= a.getSource() + MOVE_CMD_STR + a.getTarget(); + if (!allowed.contains(str_arc)) { + buf += "\t[" + str_arc + "] false -> true; \n"; + } + } + } + + buf += "endmodule\n"; + return buf; + } + + + /** + * Returns shortest distance between two nodes computed using Dijkstra's Algorithm + * @param node1 String label of source node (associated with an EnvMapNode in the map to translate) + * @param node2 String label of target node (associated with an EnvMapNode in the map to translate) + * @return float shortest distance between node1 and node2 + */ + public static double shortestPathDistance (String node1, String node2) { + synchronized (m_map) { + Graph graph = new Graph(); + Vertex[] vertices = new Vertex[m_map.getNodeCount()]; + + Map node_indexes = new HashMap<> (); + + int i=0; + for (Map.Entry entry : m_map.getNodes().entrySet() ){ + vertices[i] = new Vertex(entry.getKey()); + graph.addVertex(vertices[i], true); + node_indexes.put (entry.getKey (), i); + i++; + } + + Edge[] edges = new Edge[m_map.getUniqueArcCount()]; + + for (i=0;i entry : m_map.getNodes().entrySet() ){ + String v = entry.getKey(); + + buf+="\t"+STOP_PRED+" & "+TARGET_ROBOT_LOCATION_CONST+"="+v+" : "; + + for (Map.Entry entry2 : m_map.getNodes().entrySet() ){ + String v2 = entry2.getKey(); + if (!v2.equals(v)){ + buf += ROBOT_LOCATION_VAR + "=" + v2 + " ? " + f.format (shortestPathDistance (v, v2)) + " : "; + } + } + buf+=" 0;\n"; + + } + buf+="endrewards\n\n"; + return buf; + } + } + + + /** + * @return String PRISM encoding for energy rewards at the end of the execution + */ + public static String generateEnergyReward(){ + synchronized (m_map) { + String buf="rewards \"energy\"\n"; + buf+="\t"+STOP_PRED+"& " + NOT_FAILED_PRED + " : "+ROBOT_BATTERY_VAR+";\n"; + buf+="\t"+FAILED_PRED + ": 0;\n"; + buf+="endrewards\n\n"; + return buf; + } + } + + + /** + * Generates the PRISM specification for an adaptation scenario, based on a given EnvMap + * @param inhibitTactics boolean if true, it generates a specification only with move actions, disabling the rest of actions and tactics + * @return String PRISM encoding for adaptation scenario + */ + + public static String getMapTranslation(){ + return getMapTranslation(false); + } + + public static EnvMap getMap(){ + + return m_map; + + } + + public static String getMapTranslation(boolean inhibitTactics){ + String buf="// Generated by BRASS MARS Robot Map PRISM Translator "+VERSION_STR+".\n\n"; + buf+=generateGameStructure()+"\n"; + buf+=generateHeadingConstants()+"\n"; + buf+=generateConfigurationConstants()+"\n"; + buf+=generateLocationConstants()+"\n"; + buf+=generateEnvironmentModule()+"\n"; + buf+=generateRobotModule(inhibitTactics)+"\n"; + buf+=generateTimeReward(inhibitTactics)+"\n"; + buf+=generateRotationTimeFormulas()+"\n"; + buf+=generateRotationEnergyFormulas()+"\n"; +// buf+=generateDistanceReward()+"\n"; // Used in Phase 1 only + buf+=generateEnergyReward()+"\n"; + buf+="// --- End of generated code ---\n"; + m_generated_movecommands.clear(); // Housekeeping + return buf; + } + + + + /** + * Generates the PRISM specification for an adaptation scenario, constrained to a specific path of robot movements + * @param path List of strings containing the sequence of locations in the path, e.g., ["l1", ..., "l8"] + * @return String PRISM encoding for constrained adaptation scenario + */ + public static String getConstrainedToPathMapTranslation(List path, List reconfs){ return getConstrainedToPathMapTranslation(path, reconfs, false); - } - + } + public static String getConstrainedToPathMapTranslation(List path, List reconfs, boolean inhibitTactics){ return getMapTranslation(inhibitTactics) +"\n\n"+ generatePathConstraintModule(path) +"\n\n"+ generateReconfigurationConstraintModule(reconfs); - } - - /** - * Generates the PRISM specification for an adaptation scenario, constrained to a specific plan - * @param path List of strings containing the sequence of actions for the plan (e.g., ["l1_to_l2", ..., "t_recharge", ..., "l4_to_l5"]) - * @return String PRISM encoding for constrained adaptation scenario - */ - public static String getConstrainedToPlanMapTranslation(List plan){ - return getMapTranslation() +"\n\n"+ generatePlanConstraintModule(plan); - } - - /** - * Generates and exports the PRISM specification for an adaptation scenario to a text file - * @param f String filename to export PRISM specification (constrained to a path) - * @param path List of strings containing the sequence of locations in the path, e.g., ["l1", ..., "l8"] - */ - - + } + + /** + * Generates the PRISM specification for an adaptation scenario, constrained to a specific plan + * @param path List of strings containing the sequence of actions for the plan (e.g., ["l1_to_l2", ..., "t_recharge", ..., "l4_to_l5"]) + * @return String PRISM encoding for constrained adaptation scenario + */ + public static String getConstrainedToPlanMapTranslation(List plan){ + return getMapTranslation() +"\n\n"+ generatePlanConstraintModule(plan); + } + + /** + * Generates and exports the PRISM specification for an adaptation scenario to a text file + * @param f String filename to export PRISM specification (constrained to a path) + * @param path List of strings containing the sequence of locations in the path, e.g., ["l1", ..., "l8"] + */ + + public static void exportMapTranslation(String f, List path, List reconfs) { exportMapTranslation (f, path, reconfs, false); - } - + } + public static void exportMapTranslation(String f, List path, List reconfs, boolean inhibitTactics) { exportTranslation(f, getConstrainedToPathMapTranslation(path, reconfs, inhibitTactics)); - } - - /** - * Generates and exports the PRISM specification for an adaptation scenario to a text file - * @param f String filename to export PRISM specification (constrained to a plan) - * @param plan String list with action sequence (e.g., ["l1_to_l2", ..., "t_recharge", ..., "l4_to_l5"]) - */ - public static void exportConstrainedToPlanMapTranslation(String f, List plan) { - exportTranslation(f, getConstrainedToPlanMapTranslation(plan)); - } - - /** - * Generates and exports the PRISM specification for an adaptation scenario to a text file - * @param f String filename to export PRISM specification - */ - public static void exportMapTranslation(String f){ - exportTranslation(f, getMapTranslation()); - } - - public static void exportMapTranslation(String f, boolean inhibitTactics){ - exportTranslation(f, getMapTranslation(inhibitTactics)); - } - - - /** - * Exports a piece of code to a text file - * @param f String filename - * @param code String code to be exported - */ - public static void exportTranslation(String f, String code){ - try { - BufferedWriter out = new BufferedWriter (new FileWriter(f)); - out.write(code); - out.close(); - } - catch (IOException e){ - logError("Error exporting PRISM map translation"); - } - } - - - /** - * Generates PRISM encoding variants constrained by all non-cyclic paths between two locations - * @param f_base String base for PRISM models filenames (e.g., target folder) - * @param source String label of source location - * @param target String label of target location - * @return - */ + } + + /** + * Generates and exports the PRISM specification for an adaptation scenario to a text file + * @param f String filename to export PRISM specification (constrained to a plan) + * @param plan String list with action sequence (e.g., ["l1_to_l2", ..., "t_recharge", ..., "l4_to_l5"]) + */ + public static void exportConstrainedToPlanMapTranslation(String f, List plan) { + exportTranslation(f, getConstrainedToPlanMapTranslation(plan)); + } + + /** + * Generates and exports the PRISM specification for an adaptation scenario to a text file + * @param f String filename to export PRISM specification + */ + public static void exportMapTranslation(String f){ + exportTranslation(f, getMapTranslation()); + } + + public static void exportMapTranslation(String f, boolean inhibitTactics){ + exportTranslation(f, getMapTranslation(inhibitTactics)); + } + + + /** + * Exports a piece of code to a text file + * @param f String filename + * @param code String code to be exported + */ + public static void exportTranslation(String f, String code){ + try { + BufferedWriter out = new BufferedWriter (new FileWriter(f)); + out.write(code); + out.close(); + } + catch (IOException e){ + logError(MessageFormat.format("Error exporting PRISM map translation to ''{0}''. Error: {1}", f, e.getMessage())); + } + } + + + /** + * Generates PRISM encoding variants constrained by all non-cyclic paths between two locations + * @param f_base String base for PRISM models filenames (e.g., target folder) + * @param source String label of source location + * @param target String label of target location + * @return + */ public static Map exportConstrainedTranslationsBetween(String f_base, String source, List reconfs, String target) { return exportConstrainedTranslationsBetween(f_base, source, target, reconfs, false); - } - - public static Map exportSingleTranslationBetween(String f_base, String source, String target, boolean inhibitTactics) { - List paths = goFindAllPaths(source, target); - Map specifications = new HashMap(); - int c=0; - String filename = f_base + "/" + String.valueOf (c); - exportMapTranslation (filename, inhibitTactics); - logInfo("Exported map translation "+String.valueOf(c)); - specifications.put(paths.get(0), filename); - return specifications; - } - - - + } + + public static Map exportSingleTranslationBetween(String f_base, String source, String target, boolean inhibitTactics) { + List paths = goFindAllPaths(source, target); + Map specifications = new HashMap(); + int c=0; + String filename = f_base + "/" + String.valueOf (c); + exportMapTranslation (filename, inhibitTactics); + logInfo("Exported map translation "+String.valueOf(c)); + specifications.put(paths.get(0), filename); + return specifications; + } + + + public static Map exportConstrainedTranslationsBetween(String f_base, String source, String target, List reconfs, boolean inhibitTactics) { - List paths = goFindAllPaths(source, target); - Map specifications = new HashMap(); - int c=0; - for ( List path : paths ) { - String filename = f_base + "/" + String.valueOf (c); + List paths = goFindAllPaths(source, target); + Map specifications = new HashMap(); + int c=0; + for ( List path : paths ) { + String filename = f_base + "/" + String.valueOf (c); exportMapTranslation (filename, path, reconfs, inhibitTactics); - logInfo("Exported map translation "+String.valueOf(c)); - specifications.put(path, filename); - c++; - } - return specifications; - } - - + logInfo("Exported map translation "+String.valueOf(c)); + specifications.put(path, filename); + c++; + } + return specifications; + } + + public static Map exportConstrainedTranslationsBetweenCutOff(String f_base, String source, String target, List reconfs, boolean inhibitTactics) { - List paths = goFindAllPaths(source, target); - int cutoff=5; - ArrayList map_paths = new ArrayList(); - for (int i=0; i specifications = new HashMap(); - int c=0; - for ( EnvMapPath path : map_paths ) { - String filename = f_base + "/" + String.valueOf (c); + List paths = goFindAllPaths(source, target); + int cutoff=5; + ArrayList map_paths = new ArrayList(); + for (int i=0; i specifications = new HashMap(); + int c=0; + for ( EnvMapPath path : map_paths ) { + String filename = f_base + "/" + String.valueOf (c); exportMapTranslation (filename, path.getPath(), reconfs, inhibitTactics); - logInfo("Exported map translation "+String.valueOf(c)); - specifications.put(path.getPath(), filename); - logInfo("Candidate Path distance : "+String.valueOf(path.getDistance())+ " "+String.valueOf(path.getPath())); - c++; - if (c==cutoff){ - break; - } - } - return specifications; - } - - public static String getMapTranslationWithReconfs(List reconfs, boolean inhibitTactics){ - return getMapTranslation(inhibitTactics) +"\n\n" + generateReconfigurationConstraintModule(reconfs); - } - - public static void exportMapTranslationWithReconfs(String f, List reconfs, boolean inhibitTactics){ - exportTranslation(f, getMapTranslationWithReconfs(reconfs, inhibitTactics)); - } - - public static Map exportConstrainedTranslationFull(String f_base, String source, String target, List reconfs, boolean inhibitTactics) { - List paths = goFindAllPaths(source, target); - int cutoff=1; - ArrayList map_paths = new ArrayList(); - for (int i=0; i specifications = new HashMap(); - int c=0; - for ( EnvMapPath path : map_paths ) { - String filename = f_base + "/" + String.valueOf (c); - exportMapTranslationWithReconfs (filename, reconfs, inhibitTactics); - logInfo("Exported map translation "+String.valueOf(c)); - specifications.put(path.getPath(), filename); - logInfo("Candidate Path distance : "+String.valueOf(path.getDistance())+ " "+String.valueOf(path.getPath())); - c++; - if (c==cutoff){ - break; - } - } - return specifications; - } - - - /** - * Class test - * @param args - * @throws Exception - */ - public static void main(String[] args) throws Exception { - - - ConfigurationSynthesizer cs = new ConfigurationSynthesizer(); - cs.populate(); - EnvMap dummyMap = new EnvMap (null, null); - //dummyMap.insertNode("newnode", "l1", "l2", 17.0, 69.0); - setMap(dummyMap); - setConfigurationProvider(cs); - System.out.println(getMapTranslation()); // Class test - //System.out.println(); - exportMapTranslation("/Users/jcamara/Dropbox/Documents/Work/Projects/BRASS/rainbow-prototype/trunk/rainbow-brass/prismtmp/prismtmp-simple.prism", false); - // String export_path="/Users/jcamara/Dropbox/Documents/Work/Projects/BRASS/rainbow-prototype/trunk/rainbow-brass/prismtmp/"; - - // Map specifications = exportConstrainedTranslationsBetween (export_path, "ls", "l1"); - // System.out.println(String.valueOf(specifications)); - - } -} + logInfo("Exported map translation "+String.valueOf(c)); + specifications.put(path.getPath(), filename); + logInfo("Candidate Path distance : "+String.valueOf(path.getDistance())+ " "+String.valueOf(path.getPath())); + c++; + if (c==cutoff){ + break; + } + } + return specifications; + } + + public static String getMapTranslationWithReconfs(List reconfs, boolean inhibitTactics){ + return getMapTranslation(inhibitTactics) +"\n\n" + generateReconfigurationConstraintModule(reconfs); + } + + public static void exportMapTranslationWithReconfs(String f, List reconfs, boolean inhibitTactics){ + exportTranslation(f, getMapTranslationWithReconfs(reconfs, inhibitTactics)); + } + + public static Map exportConstrainedTranslationFull(String f_base, String source, String target, List reconfs, boolean inhibitTactics) { + List paths = goFindAllPaths(source, target); + int cutoff=1; + ArrayList map_paths = new ArrayList(); + for (int i=0; i specifications = new HashMap(); + int c=0; + for ( EnvMapPath path : map_paths ) { + String filename = f_base + "/" + String.valueOf (c); + exportMapTranslationWithReconfs (filename, reconfs, inhibitTactics); + logInfo("Exported map translation "+String.valueOf(c)); + specifications.put(path.getPath(), filename); + logInfo("Candidate Path distance : "+String.valueOf(path.getDistance())+ " "+String.valueOf(path.getPath())); + c++; + if (c==cutoff){ + break; + } + } + return specifications; + } + + + /** + * Class test + * @param args + * @throws Exception + */ + public static void main(String[] args) throws Exception { + + + ConfigurationSynthesizer cs = new ConfigurationSynthesizer(); + cs.populate(); + EnvMap dummyMap = new EnvMap (null, null); + //dummyMap.insertNode("newnode", "l1", "l2", 17.0, 69.0); + setMap(dummyMap); + setConfigurationProvider(cs); + System.out.println(getMapTranslation()); // Class test + //System.out.println(); + exportMapTranslation("/Users/jcamara/Dropbox/Documents/Work/Projects/BRASS/rainbow-prototype/trunk/rainbow-brass/prismtmp/prismtmp-simple.prism", false); + // String export_path="/Users/jcamara/Dropbox/Documents/Work/Projects/BRASS/rainbow-prototype/trunk/rainbow-brass/prismtmp/"; + + // Map specifications = exportConstrainedTranslationsBetween (export_path, "ls", "l1"); + // System.out.println(String.valueOf(specifications)); + + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2_cp1/DecisionEngineCP1.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2_cp1/DecisionEngineCP1.java index 1ccf1bfc1..8dbdb595a 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2_cp1/DecisionEngineCP1.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2_cp1/DecisionEngineCP1.java @@ -31,6 +31,7 @@ public static void init(Properties props) throws Exception { MapTranslator.ROBOT_BATTERY_CHARGING_RATIO = SimpleConfigurationBatteryModel.getChargingRate(); m_energyWeight = SimpleConfigurationBatteryModel.getEnergyWeight(); m_timelinessWeight = SimpleConfigurationBatteryModel.getTimelinessWeight(); + m_priority_index = 1; } /** * Returns the maximum estimated time for a candidate policy in the scoreboard diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2_cp3/DecisionEngineCP3.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2_cp3/DecisionEngineCP3.java index 9aae93c4b..d114cd02d 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2_cp3/DecisionEngineCP3.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/plan/p2_cp3/DecisionEngineCP3.java @@ -1,394 +1,394 @@ -package org.sa.rainbow.brass.plan.p2_cp3; - -import java.awt.geom.Point2D; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Properties; - -import org.sa.rainbow.brass.PropertiesConnector; -import org.sa.rainbow.brass.adaptation.PrismPolicy; -import org.sa.rainbow.brass.confsynthesis.ConfigurationSynthesizer; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.EnvMapPath; -import org.sa.rainbow.brass.plan.p2.DecisionEngine; -import org.sa.rainbow.brass.plan.p2.MapTranslator; -import org.sa.rainbow.core.Rainbow; - -public class DecisionEngineCP3 extends DecisionEngine { - - public static double m_selected_candidate_time = 0.0; - public static double m_selected_candidate_safety = 0.0; - public static double m_selected_candidate_energy = 0.0; - public static double m_safetyWeight; - public static double m_energyWeight; - public static double m_timelinessWeight; - public static boolean choose_balanced_utilty; - public static boolean do_not_change_paths; - public static String m_selected_candidate; - private static Properties s_properties; - - public static void init(Properties props) throws Exception { - s_properties = props; - DecisionEngine.init(props); - MapTranslator.ROBOT_BATTERY_RANGE_MAX = 180000; - MapTranslator.CONSIDER_RECONFIGURATION_COST = Boolean - .parseBoolean(props.getProperty("rainbow.consider_cost", "false")); - MapTranslator.ROBOT_MAX_RECONF_VAL = props.getProperty("rainbow.max_reconfs", "1"); - MapTranslator.TRAVERSAL_SUCCESS_THRESHOLD = Double.parseDouble(props.getProperty("rainbow.success_threshold", "0.9").trim()); - DecisionEngineCP3.choose_balanced_utilty = Boolean - .parseBoolean(props.getProperty("rainbow.balanced_utility", "true")); - DecisionEngineCP3.do_not_change_paths = Boolean.parseBoolean(props.getProperty("rainbow.fix_path", "false")); - setSafetyPreference(); - } - - public static final int ENERGY_INDEX = 0; - public static final int TIME_INDEX = 1; - public static final int SAFETY_INDEX = 2; - public static final int SUCCESS_INDEX = 3; - - public static void setSafetyPreference() { - m_safetyWeight = 0.6; - m_energyWeight = 0.2; - m_timelinessWeight = 0.2; - m_priority_index = SAFETY_INDEX; - } - - public static void setEnergyPreference() { - m_safetyWeight = 0.2; - m_energyWeight = 0.6; - m_timelinessWeight = 0.2; - m_priority_index = ENERGY_INDEX; - } - - public static void setTimelinessPreference() { - m_safetyWeight = 0.2; - m_energyWeight = 0.2; - m_timelinessWeight = 0.6; - m_priority_index = TIME_INDEX; - } - - /** - * Returns the maximum estimated remaining energy for a candidate policy in the - * scoreboard - * - * @return - */ - public static Double getMaxEnergy() { - Double res = 0.0; - for (Map.Entry> entry : m_scoreboard.entrySet()){ - Double e = entry.getValue().get(ENERGY_INDEX); - if (e>res && e != INFINITY){ - res = e; - } - } - return res; - } - - /** - * Returns the maximum estimated time for a candidate policy in the scoreboard - * - * @return - */ - public static Double getMaxTime() { - return getMaxItem(TIME_INDEX); - } - - /** - * Returns the maximum estimated safety index for a candidate policy in the - * scoreboard - * - * @return - */ - public static Double getMaxSafety() { - return getMaxItem(SAFETY_INDEX); - } - - /** - * Selects the policy with the best score (CP3) - * - * @return String filename of the selected policy - */ - public static String selectPolicy() { - Double maxTime = getMaxTime(); - Double maxSafety = getMaxSafety(); - Double maxEnergy = getMaxEnergy(); - Double maxScore = 0.0; - log("Considering cost: " + MapTranslator.CONSIDER_RECONFIGURATION_COST); - log("Max reconfgs: " + MapTranslator.ROBOT_MAX_RECONF_VAL); - log(String.format("|%3s|%5s|%5s|%5s|%5s|", "", "Time", "Safty", "NRG", "Score", "AllOrNothingScore")); - log("---+-----+-----+-----+----+"); - log(String.format("|%3s|%5.2f|%5.2f|%5.2f|%5s|", "Max", maxTime, maxSafety, maxEnergy, "1")); - - Map.Entry> maxEntry = m_scoreboard.entrySet().iterator().next(); - double maxSingeScore = 0.0; - Map.Entry> maxSingleEntry = m_scoreboard.entrySet().iterator().next(); - for (Map.Entry> entry : m_scoreboard.entrySet()) { - Double entryTime = entry.getValue().get(TIME_INDEX); - Double entryTimeliness = 0.0; - if (maxTime > 0.0) { - entryTimeliness = 1.0 - (entryTime / maxTime); - } - Double entryProbSafety = entry.getValue().get(SAFETY_INDEX); - Double entrySafety = 0.0; - if (maxSafety > 0.0) { - entrySafety = (entryProbSafety / maxSafety); - } - - Double entryEnergy = entry.getValue().get(ENERGY_INDEX) / maxEnergy; - - Double entryScore = m_safetyWeight * entrySafety + m_timelinessWeight * entryTimeliness - + m_energyWeight * entryEnergy; - log(String.format("|%3s|%5.2f|%5.2f|%5.2f|%5.2f|", "", entryTimeliness, entrySafety, entryEnergy, - entryScore)); - log(String.format("|%40s|", String.valueOf(entry.getKey()))); - double singleScore = 0.0; - if (m_safetyWeight == 0.6) - singleScore = entrySafety; - if (m_timelinessWeight == 0.6) - singleScore = entryTimeliness; - if (m_energyWeight == 0.6) - singleScore = entryEnergy; - if (entryScore > maxScore) { - maxEntry = entry; - maxScore = entryScore; - } - if (singleScore > maxSingeScore) { - maxSingeScore = singleScore; - maxSingleEntry = entry; - } - } - m_selected_candidate_time = maxEntry.getValue().get(TIME_INDEX); - m_selected_candidate_safety = maxEntry.getValue().get(SAFETY_INDEX); - m_selected_candidate_energy = maxEntry.getValue().get(ENERGY_INDEX); - m_selected_candidate_score = maxScore; - - String balancedCandidate = m_candidates.get(maxEntry.getKey()); - log("Balanced candidate policy: " + balancedCandidate); - log("Score: " + String.valueOf(m_selected_candidate_score) + " Safety: " - + String.valueOf(m_selected_candidate_safety) + " Time: " + String.valueOf(m_selected_candidate_time) - + " Energy: " + String.valueOf(m_selected_candidate_energy)); - String singleCriterionCandidate = m_candidates.get(maxSingleEntry.getKey()); - log("Single Criterion selected, based on really preferring one quality: " + singleCriterionCandidate); - if (!Objects.equals(maxSingleEntry.getKey(), maxEntry.getKey())) { - log("THESE PLANS ARE DIFFERENT"); - } - log("Choosing the plan: " + (choose_balanced_utilty ? "Balanced" : "Prioritized") + ", score=" + (choose_balanced_utilty?m_selected_candidate_score:maxSingeScore)); - m_selected_candidate = DecisionEngineCP3.choose_balanced_utilty ? (balancedCandidate) - : (singleCriterionCandidate); - return m_selected_candidate + ".adv"; - } - - public static double getSelectedPolicyTime() { - return m_selected_candidate_time; - } - - public static String generateLaTeXCandidateTable(){ - - String code=""; - code +="\n {\\scriptsize \n \\setlength\\tabcolsep{1pt} \n \\centering \n \\begin{tabular}{| p{2.5cm} | l || l | l | l | l | || l | l | l || l | } \n \\hline \n" - + "{\\bf Candidate} & {\\bf Config} & {\\bf PSuccess} & {\\bf Time} & {\\bf Safety} & {\\bf Energy} & {\\bf \\sf $U_{Time}$} & {\\bf \\sf $U_{Safety}$} & {\\bf \\sf $U_{Energy}$} & {\\bf Score} \\\\ \n" - + "\\hline \n"; - - Double maxTime = getMaxTime(); - Double maxSafety = getMaxSafety(); - Double maxEnergy = getMaxEnergy(); - Double maxScore=0.0; - - Map.Entry> maxEntry = m_scoreboard.entrySet().iterator().next(); - double maxSingeScore = 0.0; - Map.Entry> maxSingleEntry = m_scoreboard.entrySet().iterator().next(); - for (Map.Entry> entry : m_scoreboard.entrySet()) - { - Double entryTime = entry.getValue().get(TIME_INDEX); - Double entryTimeliness = 0.0; - if (maxTime>0.0){ - entryTimeliness = 1.0-(entryTime / maxTime); - } - Double entryProbSafety = entry.getValue().get(SAFETY_INDEX); - Double entrySafety=0.0; - if (maxSafety>0.0){ - entrySafety = (entryProbSafety/maxSafety); - } - - Double entryEnergy = entry.getValue().get(ENERGY_INDEX)/maxEnergy; - Double entryPsuccess = entry.getValue().get(SUCCESS_INDEX); - - PrismPolicy pp = new PrismPolicy(m_candidates.get(entry.getKey())+".adv"); - pp.readPolicy(); - String entryConfig = pp.getAllowedReconfigurations().toString(); - ConfigurationSynthesizer cs = new ConfigurationSynthesizer(DecisionEngineCP3.s_properties); - String entryConfigName = cs.translateId(entryConfig.replace("[", "").replace("]", "").replace("t_set_","")); - - Double entryScore = m_safetyWeight * entrySafety + m_timelinessWeight * entryTimeliness + m_energyWeight * entryEnergy; - - code += String.format("\n %40s & ", String.valueOf(entry.getKey()).replace("[", "").replace("]", "")); - code += String.format(" %30s & ", entryConfigName); - code += String.format("%5.2f & ", entryPsuccess); - code += String.format("%5.2f & %5.2f & %5.2f ", entryTime, entrySafety, entry.getValue().get(0)); - code += String.format("%3s & %5.2f & %5.2f & %5.2f & %5.2f \\\\", "", entryTimeliness, entrySafety, entryEnergy, entryScore); - - double singleScore = 0.0; - if (m_safetyWeight == 0.6) singleScore = entrySafety; - if (m_timelinessWeight == 0.6) singleScore = entryTimeliness; - if (m_energyWeight == 0.6) singleScore = entryEnergy; - if ( entryScore > maxScore) - { - maxEntry = entry; - maxScore = entryScore; - } - - if (singleScore > maxSingeScore) { - maxSingeScore =singleScore; - maxSingleEntry = entry; - } - } - - m_selected_candidate_time = maxEntry.getValue().get(TIME_INDEX); - m_selected_candidate_safety = maxEntry.getValue().get(SAFETY_INDEX); - m_selected_candidate_energy = maxEntry.getValue().get(ENERGY_INDEX); - m_selected_candidate_score = maxScore; - - code +="\n \\hline \n" - + "\\end{tabular} } \n"; - - return code; - } - - public static String exportPathToTikz(ArrayList path, String mode, String color) { - String code = "\\begin{scope}[> = stealth, ," + color + "," + mode - + ",thick, every node/.style = {black,right,align=center}]\n"; - for (int i = 0; i < path.size() - 1; i++) { - code += "\\draw (" + path.get(i) + ") edge [left] node {} (" + path.get(i + 1) + ");\n"; - - } - code += "\\end{scope}\n\n"; - return code; - } - - public static String openLaTeXDocument() { - String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()); - String code = "%------------\n% Experiment export generated on " + sdf - + "\n%-----------\n\n \\documentclass{article} \n" + "\\usepackage{graphicx} \n" - + "\\usepackage{tikz} \n" + "\\usepackage{pgfplots} \n" + "\\usepackage{pgfplotstable} \n" - + "\\usepgfplotslibrary{colorbrewer} \n" + "\\usetikzlibrary{shadows} \n" - + "\\usetikzlibrary{arrows} \n" + "\\usetikzlibrary{arrows.meta} \n" - + "\\usetikzlibrary{shadows.blur} \n" + "\\pgfplotsset{compat=1.14}\n\n" + "\\begin{document}\n\n"; - return code; - } - - public static String closeLaTeXDocument() { - return "\n\\end{document}\n%---- End of exported data -----\n"; - } - - public static String openTikzPicture() { - return "\n \\begin{tikzpicture}[mynode/.style = {draw,inner sep=0.6mm, circle,fill=white, blur shadow={shadow blur steps=3}}, scale=0.15]\n\n"; - } - - public static String closeTikzPicture() { - return "\\end{tikzpicture}\n\n"; - } - - public static String export(EnvMap m) { - String[] colors = { "red", "gray", "darkgray", "cyan", "violet" }; - String code = ""; - code += openLaTeXDocument(); - code += generateLaTeXCandidateTable(); - - code += "\n \\vspace{0.5cm} \n Selected: " + m_selected_candidate + "\n \\vspace{0.5cm}\n\n"; - - code += openTikzPicture(); - code += m.exportToTikz(); - int i = 0; - for (Map.Entry> entry : m_scoreboard.entrySet()) { - ArrayList p = new ArrayList( - Arrays.asList(String.valueOf(entry.getKey()).replace("[", "").replace("]", "").split(","))); - String color = colors[i]; - String mode = "dashed"; - if (Objects.equals(String.valueOf(entry.getKey()), m_selected_candidate)) { - mode = "solid"; - color = "green"; - } - code += exportPathToTikz(p, mode, color); - i++; - } - - code += closeTikzPicture(); - code += closeLaTeXDocument(); - return code; - } - - public static void generateCandidates(List path, boolean generateSeparatePaths) { - generateCandidates(path, false, generateSeparatePaths); - } - - public static void generateCandidates(List path, boolean inhibitTactics, boolean generateSeparatePaths) { - m_origin = path.get(0); - m_destination = path.get(path.size() - 1); - Map specifications = new HashMap(); - int c = 0; - String filename = m_export_path + "/" + String.valueOf(c); - EnvMapPath epath = new EnvMapPath(path, m_mt.getMap()); - if (generateSeparatePaths) - m_mt.exportMapTranslation(filename, epath.getPath(), new ArrayList(), inhibitTactics); - else - m_mt.exportMapTranslationWithReconfs(filename, new ArrayList<>(), inhibitTactics); - System.out.println("Exported map translation " + String.valueOf(c)); - specifications.put(epath.getPath(), filename); - System.out.println( - "Candidate Path distance : " + String.valueOf(epath.getDistance()) + " " + String.valueOf(path)); - m_candidates = specifications; - } - - /** - * Class test - * - * @param args - */ - public static void main(String[] args) throws Exception { - init(null); - - List coordinates = new ArrayList(); - PrismPolicy pp = null; - - EnvMap dummyMap = new EnvMap(null, null); - System.out.println("Loading Map: " + PropertiesConnector.DEFAULT.getProperty(PropertiesConnector.MAP_PROPKEY)); - dummyMap.loadFromFile(PropertiesConnector.DEFAULT.getProperty(PropertiesConnector.MAP_PROPKEY)); - System.out.println("Setting map..."); - setMap(dummyMap); - - ConfigurationSynthesizer cs = new ConfigurationSynthesizer(); - System.out.println("Populating configuration list.."); - cs.populate(); - System.out.println("Setting configuration provider..."); - setConfigurationProvider(cs); - - // String - // currentConfStr="mapServerStd0_INIT=0,mapServerObs0_INIT=0,safeSpeedSetting0_INIT=0,markerLocalization0_INIT=0,markerRecognizer0_INIT=0,amcl0_INIT=1,laserscanNodelet0_INIT=1,mrpt0_INIT=2,camera0_INIT=1,lidar0_INIT=1,headlamp0_INIT=0,kinect0_INIT=2,fullSpeedSetting0_INIT=0,halfSpeedSetting0_INIT=1"; - String currentConfStr = "laserscanNodelet0_INIT=0,amcl0_INIT=0,markerLocalization0_INIT=0,mapServerObs0_INIT=0,markerRecognizer0_INIT=0,mapServerStd0_INIT=1,mrpt0_INIT=2,kinect0_INIT=0,camera0_INIT=0,headlamp0_INIT=0,lidar0_INIT=2,fullSpeedSetting0_INIT=0,halfSpeedSetting0_INIT=1,safeSpeedSetting0_INIT=0"; - cs.generateReconfigurationsFrom(currentConfStr); - - setTimelinessPreference(); - for (int i = 180000; i < 180500; i += 500) { - System.out.println("Generating candidates for l1-l4..."); - generateCandidates("l32", "l36", true); - System.out.println("Scoring candidates..."); - scoreCandidates(dummyMap, i, 1, "-1"); - System.out.println(String.valueOf(m_scoreboard)); - pp = new PrismPolicy(selectPolicy()); - pp.readPolicy(); - String plan = pp.getPlan(cs, currentConfStr).toString(); - System.out.println("Selected Plan: " + plan); - PolicyToIGCP3 translator = new PolicyToIGCP3(pp, dummyMap); - System.out.println(translator.translate(cs, currentConfStr)); - } - System.out.println(export(dummyMap)); - - } - -} +package org.sa.rainbow.brass.plan.p2_cp3; + +import java.awt.geom.Point2D; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; + +import org.sa.rainbow.brass.PropertiesConnector; +import org.sa.rainbow.brass.adaptation.PrismPolicy; +import org.sa.rainbow.brass.confsynthesis.ConfigurationSynthesizer; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.EnvMapPath; +import org.sa.rainbow.brass.plan.p2.DecisionEngine; +import org.sa.rainbow.brass.plan.p2.MapTranslator; +import org.sa.rainbow.core.Rainbow; + +public class DecisionEngineCP3 extends DecisionEngine { + + public static double m_selected_candidate_time = 0.0; + public static double m_selected_candidate_safety = 0.0; + public static double m_selected_candidate_energy = 0.0; + public static double m_safetyWeight; + public static double m_energyWeight; + public static double m_timelinessWeight; + public static boolean choose_balanced_utilty; + public static boolean do_not_change_paths; + public static String m_selected_candidate; + private static Properties s_properties; + + public static void init(Properties props) throws Exception { + s_properties = props; + DecisionEngine.init(props); + MapTranslator.ROBOT_BATTERY_RANGE_MAX = 180000; + MapTranslator.CONSIDER_RECONFIGURATION_COST = Boolean + .parseBoolean(props.getProperty("rainbow.consider_cost", "false")); + MapTranslator.ROBOT_MAX_RECONF_VAL = props.getProperty("rainbow.max_reconfs", "1"); + MapTranslator.TRAVERSAL_SUCCESS_THRESHOLD = Double.parseDouble(props.getProperty("rainbow.success_threshold", "0.9").trim()); + DecisionEngineCP3.choose_balanced_utilty = Boolean + .parseBoolean(props.getProperty("rainbow.balanced_utility", "true")); + DecisionEngineCP3.do_not_change_paths = Boolean.parseBoolean(props.getProperty("rainbow.fix_path", "false")); + setSafetyPreference(); + } + + public static final int ENERGY_INDEX = 0; + public static final int TIME_INDEX = 1; + public static final int SAFETY_INDEX = 2; + public static final int SUCCESS_INDEX = 3; + + public static void setSafetyPreference() { + m_safetyWeight = 0.6; + m_energyWeight = 0.2; + m_timelinessWeight = 0.2; + m_priority_index = SAFETY_INDEX; + } + + public static void setEnergyPreference() { + m_safetyWeight = 0.2; + m_energyWeight = 0.6; + m_timelinessWeight = 0.2; + m_priority_index = ENERGY_INDEX; + } + + public static void setTimelinessPreference() { + m_safetyWeight = 0.2; + m_energyWeight = 0.2; + m_timelinessWeight = 0.6; + m_priority_index = TIME_INDEX; + } + + /** + * Returns the maximum estimated remaining energy for a candidate policy in the + * scoreboard + * + * @return + */ + public static Double getMaxEnergy() { + Double res = 0.0; + for (Map.Entry> entry : m_scoreboard.entrySet()){ + Double e = entry.getValue().get(ENERGY_INDEX); + if (e>res && e != INFINITY){ + res = e; + } + } + return res; + } + + /** + * Returns the maximum estimated time for a candidate policy in the scoreboard + * + * @return + */ + public static Double getMaxTime() { + return getMaxItem(TIME_INDEX); + } + + /** + * Returns the maximum estimated safety index for a candidate policy in the + * scoreboard + * + * @return + */ + public static Double getMaxSafety() { + return getMaxItem(SAFETY_INDEX); + } + + /** + * Selects the policy with the best score (CP3) + * + * @return String filename of the selected policy + */ + public static String selectPolicy() { + Double maxTime = getMaxTime(); + Double maxSafety = getMaxSafety(); + Double maxEnergy = getMaxEnergy(); + Double maxScore = 0.0; + log("Considering cost: " + MapTranslator.CONSIDER_RECONFIGURATION_COST); + log("Max reconfgs: " + MapTranslator.ROBOT_MAX_RECONF_VAL); + log(String.format("|%3s|%5s|%5s|%5s|%5s|", "", "Time", "Safty", "NRG", "Score", "AllOrNothingScore")); + log("---+-----+-----+-----+----+"); + log(String.format("|%3s|%5.2f|%5.2f|%5.2f|%5s|", "Max", maxTime, maxSafety, maxEnergy, "1")); + + Map.Entry> maxEntry = m_scoreboard.entrySet().iterator().next(); + double maxSingeScore = 0.0; + Map.Entry> maxSingleEntry = m_scoreboard.entrySet().iterator().next(); + for (Map.Entry> entry : m_scoreboard.entrySet()) { + Double entryTime = entry.getValue().get(TIME_INDEX); + Double entryTimeliness = 0.0; + if (maxTime > 0.0) { + entryTimeliness = 1.0 - (entryTime / maxTime); + } + Double entryProbSafety = entry.getValue().get(SAFETY_INDEX); + Double entrySafety = 0.0; + if (maxSafety > 0.0) { + entrySafety = (entryProbSafety / maxSafety); + } + + Double entryEnergy = entry.getValue().get(ENERGY_INDEX) / maxEnergy; + + Double entryScore = m_safetyWeight * entrySafety + m_timelinessWeight * entryTimeliness + + m_energyWeight * entryEnergy; + log(String.format("|%3s|%5.2f|%5.2f|%5.2f|%5.2f|", "", entryTimeliness, entrySafety, entryEnergy, + entryScore)); + log(String.format("|%40s|", String.valueOf(entry.getKey()))); + double singleScore = 0.0; + if (m_safetyWeight == 0.6) + singleScore = entrySafety; + if (m_timelinessWeight == 0.6) + singleScore = entryTimeliness; + if (m_energyWeight == 0.6) + singleScore = entryEnergy; + if (entryScore > maxScore) { + maxEntry = entry; + maxScore = entryScore; + } + if (singleScore > maxSingeScore) { + maxSingeScore = singleScore; + maxSingleEntry = entry; + } + } + m_selected_candidate_time = maxEntry.getValue().get(TIME_INDEX); + m_selected_candidate_safety = maxEntry.getValue().get(SAFETY_INDEX); + m_selected_candidate_energy = maxEntry.getValue().get(ENERGY_INDEX); + m_selected_candidate_score = maxScore; + + String balancedCandidate = m_candidates.get(maxEntry.getKey()); + log("Balanced candidate policy: " + balancedCandidate); + log("Score: " + String.valueOf(m_selected_candidate_score) + " Safety: " + + String.valueOf(m_selected_candidate_safety) + " Time: " + String.valueOf(m_selected_candidate_time) + + " Energy: " + String.valueOf(m_selected_candidate_energy)); + String singleCriterionCandidate = m_candidates.get(maxSingleEntry.getKey()); + log("Single Criterion selected, based on really preferring one quality: " + singleCriterionCandidate); + if (!Objects.equals(maxSingleEntry.getKey(), maxEntry.getKey())) { + log("THESE PLANS ARE DIFFERENT"); + } + log("Choosing the plan: " + (choose_balanced_utilty ? "Balanced" : "Prioritized") + ", score=" + (choose_balanced_utilty?m_selected_candidate_score:maxSingeScore)); + m_selected_candidate = DecisionEngineCP3.choose_balanced_utilty ? (balancedCandidate) + : (singleCriterionCandidate); + return m_selected_candidate + ".adv"; + } + + public static double getSelectedPolicyTime() { + return m_selected_candidate_time; + } + + public static String generateLaTeXCandidateTable(){ + + String code=""; + code +="\n {\\scriptsize \n \\setlength\\tabcolsep{1pt} \n \\centering \n \\begin{tabular}{| p{2.5cm} | l || l | l | l | l | || l | l | l || l | } \n \\hline \n" + + "{\\bf Candidate} & {\\bf Config} & {\\bf PSuccess} & {\\bf Time} & {\\bf Safety} & {\\bf Energy} & {\\bf \\sf $U_{Time}$} & {\\bf \\sf $U_{Safety}$} & {\\bf \\sf $U_{Energy}$} & {\\bf Score} \\\\ \n" + + "\\hline \n"; + + Double maxTime = getMaxTime(); + Double maxSafety = getMaxSafety(); + Double maxEnergy = getMaxEnergy(); + Double maxScore=0.0; + + Map.Entry> maxEntry = m_scoreboard.entrySet().iterator().next(); + double maxSingeScore = 0.0; + Map.Entry> maxSingleEntry = m_scoreboard.entrySet().iterator().next(); + for (Map.Entry> entry : m_scoreboard.entrySet()) + { + Double entryTime = entry.getValue().get(TIME_INDEX); + Double entryTimeliness = 0.0; + if (maxTime>0.0){ + entryTimeliness = 1.0-(entryTime / maxTime); + } + Double entryProbSafety = entry.getValue().get(SAFETY_INDEX); + Double entrySafety=0.0; + if (maxSafety>0.0){ + entrySafety = (entryProbSafety/maxSafety); + } + + Double entryEnergy = entry.getValue().get(ENERGY_INDEX)/maxEnergy; + Double entryPsuccess = entry.getValue().get(SUCCESS_INDEX); + + PrismPolicy pp = new PrismPolicy(m_candidates.get(entry.getKey())+".adv"); + pp.readPolicy(); + String entryConfig = pp.getAllowedReconfigurations().toString(); + ConfigurationSynthesizer cs = new ConfigurationSynthesizer(DecisionEngineCP3.s_properties); + String entryConfigName = cs.translateId(entryConfig.replace("[", "").replace("]", "").replace("t_set_","")); + + Double entryScore = m_safetyWeight * entrySafety + m_timelinessWeight * entryTimeliness + m_energyWeight * entryEnergy; + + code += String.format("\n %40s & ", String.valueOf(entry.getKey()).replace("[", "").replace("]", "")); + code += String.format(" %30s & ", entryConfigName); + code += String.format("%5.2f & ", entryPsuccess); + code += String.format("%5.2f & %5.2f & %5.2f ", entryTime, entrySafety, entry.getValue().get(0)); + code += String.format("%3s & %5.2f & %5.2f & %5.2f & %5.2f \\\\", "", entryTimeliness, entrySafety, entryEnergy, entryScore); + + double singleScore = 0.0; + if (m_safetyWeight == 0.6) singleScore = entrySafety; + if (m_timelinessWeight == 0.6) singleScore = entryTimeliness; + if (m_energyWeight == 0.6) singleScore = entryEnergy; + if ( entryScore > maxScore) + { + maxEntry = entry; + maxScore = entryScore; + } + + if (singleScore > maxSingeScore) { + maxSingeScore =singleScore; + maxSingleEntry = entry; + } + } + + m_selected_candidate_time = maxEntry.getValue().get(TIME_INDEX); + m_selected_candidate_safety = maxEntry.getValue().get(SAFETY_INDEX); + m_selected_candidate_energy = maxEntry.getValue().get(ENERGY_INDEX); + m_selected_candidate_score = maxScore; + + code +="\n \\hline \n" + + "\\end{tabular} } \n"; + + return code; + } + + public static String exportPathToTikz(ArrayList path, String mode, String color) { + String code = "\\begin{scope}[> = stealth, ," + color + "," + mode + + ",thick, every node/.style = {black,right,align=center}]\n"; + for (int i = 0; i < path.size() - 1; i++) { + code += "\\draw (" + path.get(i) + ") edge [left] node {} (" + path.get(i + 1) + ");\n"; + + } + code += "\\end{scope}\n\n"; + return code; + } + + public static String openLaTeXDocument() { + String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()); + String code = "%------------\n% Experiment export generated on " + sdf + + "\n%-----------\n\n \\documentclass{article} \n" + "\\usepackage{graphicx} \n" + + "\\usepackage{tikz} \n" + "\\usepackage{pgfplots} \n" + "\\usepackage{pgfplotstable} \n" + + "\\usepgfplotslibrary{colorbrewer} \n" + "\\usetikzlibrary{shadows} \n" + + "\\usetikzlibrary{arrows} \n" + "\\usetikzlibrary{arrows.meta} \n" + + "\\usetikzlibrary{shadows.blur} \n" + "\\pgfplotsset{compat=1.14}\n\n" + "\\begin{document}\n\n"; + return code; + } + + public static String closeLaTeXDocument() { + return "\n\\end{document}\n%---- End of exported data -----\n"; + } + + public static String openTikzPicture() { + return "\n \\begin{tikzpicture}[mynode/.style = {draw,inner sep=0.6mm, circle,fill=white, blur shadow={shadow blur steps=3}}, scale=0.15]\n\n"; + } + + public static String closeTikzPicture() { + return "\\end{tikzpicture}\n\n"; + } + + public static String export(EnvMap m) { + String[] colors = { "red", "gray", "darkgray", "cyan", "violet" }; + String code = ""; + code += openLaTeXDocument(); + code += generateLaTeXCandidateTable(); + + code += "\n \\vspace{0.5cm} \n Selected: " + m_selected_candidate + "\n \\vspace{0.5cm}\n\n"; + + code += openTikzPicture(); + code += m.exportToTikz(); + int i = 0; + for (Map.Entry> entry : m_scoreboard.entrySet()) { + ArrayList p = new ArrayList( + Arrays.asList(String.valueOf(entry.getKey()).replace("[", "").replace("]", "").split(","))); + String color = colors[i]; + String mode = "dashed"; + if (Objects.equals(String.valueOf(entry.getKey()), m_selected_candidate)) { + mode = "solid"; + color = "green"; + } + code += exportPathToTikz(p, mode, color); + i++; + } + + code += closeTikzPicture(); + code += closeLaTeXDocument(); + return code; + } + + public static void generateCandidates(List path, boolean generateSeparatePaths) { + generateCandidates(path, false, generateSeparatePaths); + } + + public static void generateCandidates(List path, boolean inhibitTactics, boolean generateSeparatePaths) { + m_origin = path.get(0); + m_destination = path.get(path.size() - 1); + Map specifications = new HashMap(); + int c = 0; + String filename = m_export_path + "/" + String.valueOf(c); + EnvMapPath epath = new EnvMapPath(path, m_mt.getMap()); + if (generateSeparatePaths) + m_mt.exportMapTranslation(filename, epath.getPath(), new ArrayList(), inhibitTactics); + else + m_mt.exportMapTranslationWithReconfs(filename, new ArrayList<>(), inhibitTactics); + System.out.println("Exported map translation " + String.valueOf(c)); + specifications.put(epath.getPath(), filename); + System.out.println( + "Candidate Path distance : " + String.valueOf(epath.getDistance()) + " " + String.valueOf(path)); + m_candidates = specifications; + } + + /** + * Class test + * + * @param args + */ + public static void main(String[] args) throws Exception { + init(null); + + List coordinates = new ArrayList(); + PrismPolicy pp = null; + + EnvMap dummyMap = new EnvMap(null, null); + System.out.println("Loading Map: " + PropertiesConnector.DEFAULT.getProperty(PropertiesConnector.MAP_PROPKEY)); + dummyMap.loadFromFile(PropertiesConnector.DEFAULT.getProperty(PropertiesConnector.MAP_PROPKEY)); + System.out.println("Setting map..."); + setMap(dummyMap); + + ConfigurationSynthesizer cs = new ConfigurationSynthesizer(); + System.out.println("Populating configuration list.."); + cs.populate(); + System.out.println("Setting configuration provider..."); + setConfigurationProvider(cs); + + // String + // currentConfStr="mapServerStd0_INIT=0,mapServerObs0_INIT=0,safeSpeedSetting0_INIT=0,markerLocalization0_INIT=0,markerRecognizer0_INIT=0,amcl0_INIT=1,laserscanNodelet0_INIT=1,mrpt0_INIT=2,camera0_INIT=1,lidar0_INIT=1,headlamp0_INIT=0,kinect0_INIT=2,fullSpeedSetting0_INIT=0,halfSpeedSetting0_INIT=1"; + String currentConfStr = "laserscanNodelet0_INIT=0,amcl0_INIT=0,markerLocalization0_INIT=0,mapServerObs0_INIT=0,markerRecognizer0_INIT=0,mapServerStd0_INIT=1,mrpt0_INIT=2,kinect0_INIT=0,camera0_INIT=0,headlamp0_INIT=0,lidar0_INIT=2,fullSpeedSetting0_INIT=0,halfSpeedSetting0_INIT=1,safeSpeedSetting0_INIT=0"; + cs.generateReconfigurationsFrom(currentConfStr); + + setTimelinessPreference(); + for (int i = 180000; i < 180500; i += 500) { + System.out.println("Generating candidates for l1-l4..."); + generateCandidates("l32", "l36", true); + System.out.println("Scoring candidates..."); + scoreCandidates(dummyMap, i, 1, "-1"); + System.out.println(String.valueOf(m_scoreboard)); + pp = new PrismPolicy(selectPolicy()); + pp.readPolicy(); + String plan = pp.getPlan(cs, currentConfStr).toString(); + System.out.println("Selected Plan: " + plan); + PolicyToIGCP3 translator = new PolicyToIGCP3(pp, dummyMap); + System.out.println(translator.translate(cs, currentConfStr)); + } + System.out.println(export(dummyMap)); + + } + +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/probes/BRASSRosTopicProbe.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/probes/BRASSRosTopicProbe.java index 079aeca63..a0491c8d0 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/probes/BRASSRosTopicProbe.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/probes/BRASSRosTopicProbe.java @@ -1,175 +1,175 @@ -package org.sa.rainbow.brass.probes; - -import org.ho.yaml.Yaml; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.util.RainbowLogger; -import org.sa.rainbow.translator.probes.AbstractProbe; -import org.sa.rainbow.translator.probes.IBashBasedScript; -import org.sa.rainbow.util.Util; - -import java.io.*; -import java.util.Date; -import java.util.Map; - -/** - * Created by schmerl on 12/26/2016. - */ -public class BRASSRosTopicProbe extends AbstractProbe implements IBashBasedScript { - - private static final String PROBE_TYPE = "rostopicprobe"; - - private String m_path; - private String m_params; - private Process m_process; - - - public class ErrorStreamGobbler extends Thread { - private InputStream m_inputStream; - - public ErrorStreamGobbler(InputStream is) { - m_inputStream = is; - } - - @Override - public void run() { - try { - InputStreamReader isr = new InputStreamReader (m_inputStream); - BufferedReader br = new BufferedReader (isr); - String line = br.readLine (); - while (line != null) { - System.err.println(line); - log(line); - line = br.readLine(); - } - } - catch (IOException e) { - log(e.getMessage()); - } - } - } - - public class StreamGobbler extends Thread { - private final InputStream m_inputStream; - - public StreamGobbler (InputStream is) { - m_inputStream = is; - } - - @Override - public void run () { - try { - InputStreamReader isr = new InputStreamReader (m_inputStream); - BufferedReader br = new BufferedReader (isr); - String line = br.readLine (); - while (line != null) { - StringBuffer yaml = new StringBuffer (line + "\n"); - while ((line = br.readLine ()) != null && !"---".equals (line) && !line.startsWith("Frame") && !line.contains("RPY (degree)")) { - yaml.append (line); - yaml.append ("\n"); - } - //Map o = (Map) Yaml.load (yaml.toString ()); -// yaml.append("\nobserving_time: "); -// yaml.append(new Date ().getTime ()); - reportData (yaml.toString ());//Yaml.dump (o, true)); - line = br.readLine (); - } - } catch (IOException ioe) { - log (ioe.getMessage ()); - } - } - } - - public BRASSRosTopicProbe (String id, long sleepTime) { - super (id, PROBE_TYPE, Kind.JAVA); - } - - public BRASSRosTopicProbe (String id, long sleepTime, String[] args) { - this (id, sleepTime); - if (args.length == 2) { - m_path = args[0]; - m_params = args[1]; - } - } - - -// /** -// * Main Constuctor that initializes the ID of this Probe. -// * -// * @param refID the unique identifier of the Probe -// * @param alias the type name of the Probe -// */ -// public BRASSRosTopicProbe (String refID, String alias, String path, String paramStr) { -// super (refID, alias, Kind.SCRIPT); -// m_path = path; -// m_params = paramStr; -// } - - @Override - public synchronized void activate () { - super.activate (); - String[] cmds = new String[3]; - switch (Rainbow.instance ().environment ()) { - case CYGWIN: - cmds[0] = CYGWIN_BASH; - break; - case LINUX: - cmds[0] = LINUX_BASH; - Util.setExecutablePermission (m_path); - break; - } - if (cmds[0] == null) - deactivate (); - else { - cmds[1] = BASH_OPT; - cmds[2] = m_path + " " + m_params; - - ProcessBuilder pb = new ProcessBuilder (cmds); - File workDir = new File (m_path).getParentFile (); - pb.directory (workDir); -// pb.redirectErrorStream (true); - try { - m_process = pb.start (); - StreamGobbler outputProcessor = new StreamGobbler (m_process.getInputStream ()); - ErrorStreamGobbler esg = new ErrorStreamGobbler(m_process.getErrorStream()); - outputProcessor.start (); - esg.start(); - } catch (IOException e) { - RainbowLogger.error (RainbowComponentT.PROBE, "Process I/O failed!", e, getLoggingPort (), LOGGER); - - } - } - } - - @Override - public synchronized void deactivate () { - if (m_process != null) { - dumpOutput (); - - m_process.destroy (); - log ("- Process destroyed."); - m_process = null; - } - super.deactivate (); - } - - @Override - public boolean isAlive () { - return true; -// boolean alive = true; -// if (m_process != null) { -// if (m_process.exitValue () == 0) { -// m_process = null; -// } else { -// alive = false; -// dumpOutput (); -// -// } -// } -// return alive; - } - - private void dumpOutput () { - log ("- STDOUT+STDERR: ----\n" + Util.getProcessOutput (m_process)); - } -} +package org.sa.rainbow.brass.probes; + +import org.ho.yaml.Yaml; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.util.RainbowLogger; +import org.sa.rainbow.translator.probes.AbstractProbe; +import org.sa.rainbow.translator.probes.IBashBasedScript; +import org.sa.rainbow.util.Util; + +import java.io.*; +import java.util.Date; +import java.util.Map; + +/** + * Created by schmerl on 12/26/2016. + */ +public class BRASSRosTopicProbe extends AbstractProbe implements IBashBasedScript { + + private static final String PROBE_TYPE = "rostopicprobe"; + + private String m_path; + private String m_params; + private Process m_process; + + + public class ErrorStreamGobbler extends Thread { + private InputStream m_inputStream; + + public ErrorStreamGobbler(InputStream is) { + m_inputStream = is; + } + + @Override + public void run() { + try { + InputStreamReader isr = new InputStreamReader (m_inputStream); + BufferedReader br = new BufferedReader (isr); + String line = br.readLine (); + while (line != null) { + System.err.println(line); + log(line); + line = br.readLine(); + } + } + catch (IOException e) { + log(e.getMessage()); + } + } + } + + public class StreamGobbler extends Thread { + private final InputStream m_inputStream; + + public StreamGobbler (InputStream is) { + m_inputStream = is; + } + + @Override + public void run () { + try { + InputStreamReader isr = new InputStreamReader (m_inputStream); + BufferedReader br = new BufferedReader (isr); + String line = br.readLine (); + while (line != null) { + StringBuffer yaml = new StringBuffer (line + "\n"); + while ((line = br.readLine ()) != null && !"---".equals (line) && !line.startsWith("Frame") && !line.contains("RPY (degree)")) { + yaml.append (line); + yaml.append ("\n"); + } + //Map o = (Map) Yaml.load (yaml.toString ()); +// yaml.append("\nobserving_time: "); +// yaml.append(new Date ().getTime ()); + reportData (yaml.toString ());//Yaml.dump (o, true)); + line = br.readLine (); + } + } catch (IOException ioe) { + log (ioe.getMessage ()); + } + } + } + + public BRASSRosTopicProbe (String id, long sleepTime) { + super (id, PROBE_TYPE, Kind.JAVA); + } + + public BRASSRosTopicProbe (String id, long sleepTime, String[] args) { + this (id, sleepTime); + if (args.length == 2) { + m_path = args[0]; + m_params = args[1]; + } + } + + +// /** +// * Main Constuctor that initializes the ID of this Probe. +// * +// * @param refID the unique identifier of the Probe +// * @param alias the type name of the Probe +// */ +// public BRASSRosTopicProbe (String refID, String alias, String path, String paramStr) { +// super (refID, alias, Kind.SCRIPT); +// m_path = path; +// m_params = paramStr; +// } + + @Override + public synchronized void activate () { + super.activate (); + String[] cmds = new String[3]; + switch (Rainbow.instance ().environment ()) { + case CYGWIN: + cmds[0] = CYGWIN_BASH; + break; + case LINUX: + cmds[0] = LINUX_BASH; + Util.setExecutablePermission (m_path); + break; + } + if (cmds[0] == null) + deactivate (); + else { + cmds[1] = BASH_OPT; + cmds[2] = m_path + " " + m_params; + + ProcessBuilder pb = new ProcessBuilder (cmds); + File workDir = new File (m_path).getParentFile (); + pb.directory (workDir); +// pb.redirectErrorStream (true); + try { + m_process = pb.start (); + StreamGobbler outputProcessor = new StreamGobbler (m_process.getInputStream ()); + ErrorStreamGobbler esg = new ErrorStreamGobbler(m_process.getErrorStream()); + outputProcessor.start (); + esg.start(); + } catch (IOException e) { + RainbowLogger.error (RainbowComponentT.PROBE, "Process I/O failed!", e, getLoggingPort (), LOGGER); + + } + } + } + + @Override + public synchronized void deactivate () { + if (m_process != null) { + dumpOutput (); + + m_process.destroy (); + log ("- Process destroyed."); + m_process = null; + } + super.deactivate (); + } + + @Override + public boolean isAlive () { + return true; +// boolean alive = true; +// if (m_process != null) { +// if (m_process.exitValue () == 0) { +// m_process = null; +// } else { +// alive = false; +// dumpOutput (); +// +// } +// } +// return alive; + } + + private void dumpOutput () { + log ("- STDOUT+STDERR: ----\n" + Util.getProcessOutput (m_process)); + } +} diff --git a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/probes/TargetWaypointProbe.java b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/probes/TargetWaypointProbe.java index 81019678b..b970ddf66 100644 --- a/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/probes/TargetWaypointProbe.java +++ b/deployments/rainbow-brass/src/main/java/org/sa/rainbow/brass/probes/TargetWaypointProbe.java @@ -1,104 +1,104 @@ -package org.sa.rainbow.brass.probes; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Path; -import java.nio.file.StandardWatchEventKinds; -import java.nio.file.WatchEvent; -import java.nio.file.WatchKey; -import java.nio.file.WatchService; -import java.util.concurrent.TimeUnit; - -import org.sa.rainbow.core.ConfigHelper; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.util.RainbowLogger; -import org.sa.rainbow.translator.probes.AbstractProbe; - -public class TargetWaypointProbe extends AbstractProbe implements Runnable { - private static final String PROBE_TYPE = "targetwaypointprobe"; - private String m_path; - - private WatchService m_watcher; - private WatchKey m_watchKey; - private Thread m_watchThread; - private boolean m_deactivated; - private Path m_filePath; - private long m_sleepTime; - - public TargetWaypointProbe(String id, long sleepTime) { - super(id, PROBE_TYPE, Kind.JAVA); - m_sleepTime = sleepTime; - } - - public TargetWaypointProbe(String id, long sleepTime, String args) { - this(id, sleepTime); - m_path = ConfigHelper.convertToAbsolute(args); - - } - - @Override - public synchronized void activate() { - super.activate(); - m_filePath = FileSystems.getDefault().getPath(m_path); - if (!m_filePath.getParent().toFile().exists()) { - RainbowLogger.error(RainbowComponentT.PROBE, - "The path that should contain the file '" + m_path + "' does not exist", getLoggingPort(), LOGGER); - } else { - try { - m_watcher = FileSystems.getDefault().newWatchService(); - m_watchKey = m_filePath.getParent().register(m_watcher, StandardWatchEventKinds.ENTRY_MODIFY, - StandardWatchEventKinds.ENTRY_CREATE); - m_deactivated = false; - m_watchThread = new Thread(this); - m_watchThread.start(); - } catch (IOException e) { - RainbowLogger.error(RainbowComponentT.PROBE, "Failed to activate probe " + id(), e, getLoggingPort(), - LOGGER); - } - } - } - - @Override - public synchronized void deactivate() { - m_deactivated = true; - super.deactivate(); - } - - @Override - public void run() { - boolean ok = true; - while (!m_deactivated && ok) { - try { - final WatchKey wk = m_watcher.poll(m_sleepTime, TimeUnit.MILLISECONDS); - if (wk != null) { - for (WatchEvent event : wk.pollEvents()) { - if (m_filePath.getFileName().equals((Path) event.context())) { - try (BufferedReader reader = new BufferedReader(new FileReader(m_filePath.toFile()))) { - StringBuilder builder = new StringBuilder(); - String line = null; - String ls = System.getProperty("line.separator"); - while ((line = reader.readLine()) != null) { - builder.append(line); - builder.append(ls); - } - reportData(builder.toString()); - } catch (IOException e) { - RainbowLogger.error(RainbowComponentT.PROBE, - "Probe '" + id() + "' failed to read file '" + m_path + "'", e, - getLoggingPort(), LOGGER); - } - } - } - - ok = wk.reset(); - } - } catch (InterruptedException e) { - } - } - } - -} +package org.sa.rainbow.brass.probes; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import java.util.concurrent.TimeUnit; + +import org.sa.rainbow.core.ConfigHelper; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.util.RainbowLogger; +import org.sa.rainbow.translator.probes.AbstractProbe; + +public class TargetWaypointProbe extends AbstractProbe implements Runnable { + private static final String PROBE_TYPE = "targetwaypointprobe"; + private String m_path; + + private WatchService m_watcher; + private WatchKey m_watchKey; + private Thread m_watchThread; + private boolean m_deactivated; + private Path m_filePath; + private long m_sleepTime; + + public TargetWaypointProbe(String id, long sleepTime) { + super(id, PROBE_TYPE, Kind.JAVA); + m_sleepTime = sleepTime; + } + + public TargetWaypointProbe(String id, long sleepTime, String args) { + this(id, sleepTime); + m_path = ConfigHelper.convertToAbsolute(args); + + } + + @Override + public synchronized void activate() { + super.activate(); + m_filePath = FileSystems.getDefault().getPath(m_path); + if (!m_filePath.getParent().toFile().exists()) { + RainbowLogger.error(RainbowComponentT.PROBE, + "The path that should contain the file '" + m_path + "' does not exist", getLoggingPort(), LOGGER); + } else { + try { + m_watcher = FileSystems.getDefault().newWatchService(); + m_watchKey = m_filePath.getParent().register(m_watcher, StandardWatchEventKinds.ENTRY_MODIFY, + StandardWatchEventKinds.ENTRY_CREATE); + m_deactivated = false; + m_watchThread = new Thread(this); + m_watchThread.start(); + } catch (IOException e) { + RainbowLogger.error(RainbowComponentT.PROBE, "Failed to activate probe " + id(), e, getLoggingPort(), + LOGGER); + } + } + } + + @Override + public synchronized void deactivate() { + m_deactivated = true; + super.deactivate(); + } + + @Override + public void run() { + boolean ok = true; + while (!m_deactivated && ok) { + try { + final WatchKey wk = m_watcher.poll(m_sleepTime, TimeUnit.MILLISECONDS); + if (wk != null) { + for (WatchEvent event : wk.pollEvents()) { + if (m_filePath.getFileName().equals((Path) event.context())) { + try (BufferedReader reader = new BufferedReader(new FileReader(m_filePath.toFile()))) { + StringBuilder builder = new StringBuilder(); + String line = null; + String ls = System.getProperty("line.separator"); + while ((line = reader.readLine()) != null) { + builder.append(line); + builder.append(ls); + } + reportData(builder.toString()); + } catch (IOException e) { + RainbowLogger.error(RainbowComponentT.PROBE, + "Probe '" + id() + "' failed to read file '" + m_path + "'", e, + getLoggingPort(), LOGGER); + } + } + } + + ok = wk.reset(); + } + } catch (InterruptedException e) { + } + } + } + +} diff --git a/deployments/rainbow-brass/src/test/java/TestEnergyPredictor.java b/deployments/rainbow-brass/src/test/java/TestEnergyPredictor.java index 3802b4570..8383076fd 100644 --- a/deployments/rainbow-brass/src/test/java/TestEnergyPredictor.java +++ b/deployments/rainbow-brass/src/test/java/TestEnergyPredictor.java @@ -1,78 +1,78 @@ -import static org.junit.Assert.*; - -import java.util.Collection; -import java.util.List; -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; -import org.sa.rainbow.brass.analyses.p2_cp1.EnergyConsumptionPredictor; -import org.sa.rainbow.brass.confsynthesis.PropertiesSimpleConfigurationStore; -import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; -import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; -import org.sa.rainbow.brass.model.map.EnvMap; -import org.sa.rainbow.brass.model.map.EnvMapNode; -import org.sa.rainbow.brass.model.map.MapTranslator; -import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; -import org.sa.rainbow.core.models.ModelReference; - -public class TestEnergyPredictor { - - private EnvMap m_e; - private MissionState m_m; - private SimpleConfigurationStore m_p; - - @Before - public void setUp() { - m_e = new EnvMap(new ModelReference("test", "Map")); - m_e.loadFromFile("src/test/resources/cp1_map.json"); - m_m = new MissionState(new ModelReference("test", "MissionState")); - Properties props = new Properties(); - props.setProperty(PropertiesSimpleConfigurationStore.CONFIGURATIONS_SOURCE_PROPKEY, "src/test/resources/config_list.json"); - m_p = new SimpleConfigurationStore(props); - m_p.populate(); - EnvMapNode envMapNode = m_e.getNodes().get("l1"); - m_m.setCurrentPose(envMapNode.getX(), envMapNode.getY(), 0.0); - } - - @Test - public void testHasEnoughEnergy() { - InstructionGraphProgress ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test"),"P(V(1, do MoveAbsH(-21.08, 11.08, 0.68, -0.0125) then 2),\r\n" + - "V(2, do MoveAbsH(0.54, 10.81, 0.68, 0.0000) then 3)::\r\n" + - "V(3, do MoveAbsH(22.97, 10.81, 0.68, -1.5470) then 4)::\r\n" + - "V(4, do MoveAbsH(23.24, -0.54, 0.68, -1.5470) then 5)::\r\n" + - "V(5, end)::\r\n" + - "nil)"); - configureIGWaypointInfo(ip); - m_m.setTargetWaypoint("l9"); - - - - EnergyConsumptionPredictor predictor = new EnergyConsumptionPredictor(m_e, m_m, m_p); - predictor.setConfig("sol_7"); - IInstruction firstInstruction = ip.getInstruction("1"); - ip.setExecutingInstruction("1", ""); - double energyRequired = predictor.getPlanEnergyConsumption(firstInstruction, ip.getRemainingInstructions(), "l9"); - assertTrue(energyRequired > 0); - assertTrue(energyRequired < MapTranslator.ROBOT_BATTERY_RANGE_MAX); - } - - private void configureIGWaypointInfo(InstructionGraphProgress ip) { - String currentSrc = m_e.getNode(m_m.getCurrentPose().getX(), m_m.getCurrentPose().getY()).getLabel(); - - Collection instructions = ip - .getInstructions(); - for (IInstruction i : instructions) { - if (i instanceof MoveAbsHInstruction) { - MoveAbsHInstruction mai = (MoveAbsHInstruction) i; - mai.setSourceWaypoint(currentSrc); - String tgtWp = m_e.getNode(mai.getTargetX(), mai.getTargetY()).getLabel(); - mai.setTargetWaypoint(tgtWp); - currentSrc = tgtWp; - } - } - } - -} +import static org.junit.Assert.*; + +import java.util.Collection; +import java.util.List; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.sa.rainbow.brass.analyses.p2_cp1.EnergyConsumptionPredictor; +import org.sa.rainbow.brass.confsynthesis.PropertiesSimpleConfigurationStore; +import org.sa.rainbow.brass.confsynthesis.SimpleConfigurationStore; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; +import org.sa.rainbow.brass.model.instructions.MoveAbsHInstruction; +import org.sa.rainbow.brass.model.map.EnvMap; +import org.sa.rainbow.brass.model.map.EnvMapNode; +import org.sa.rainbow.brass.model.map.MapTranslator; +import org.sa.rainbow.brass.model.p2_cp3.mission.MissionState; +import org.sa.rainbow.core.models.ModelReference; + +public class TestEnergyPredictor { + + private EnvMap m_e; + private MissionState m_m; + private SimpleConfigurationStore m_p; + + @Before + public void setUp() { + m_e = new EnvMap(new ModelReference("test", "Map")); + m_e.loadFromFile("src/test/resources/cp1_map.json"); + m_m = new MissionState(new ModelReference("test", "MissionState")); + Properties props = new Properties(); + props.setProperty(PropertiesSimpleConfigurationStore.CONFIGURATIONS_SOURCE_PROPKEY, "src/test/resources/config_list.json"); + m_p = new SimpleConfigurationStore(props); + m_p.populate(); + EnvMapNode envMapNode = m_e.getNodes().get("l1"); + m_m.setCurrentPose(envMapNode.getX(), envMapNode.getY(), 0.0); + } + + @Test + public void testHasEnoughEnergy() { + InstructionGraphProgress ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test"),"P(V(1, do MoveAbsH(-21.08, 11.08, 0.68, -0.0125) then 2),\r\n" + + "V(2, do MoveAbsH(0.54, 10.81, 0.68, 0.0000) then 3)::\r\n" + + "V(3, do MoveAbsH(22.97, 10.81, 0.68, -1.5470) then 4)::\r\n" + + "V(4, do MoveAbsH(23.24, -0.54, 0.68, -1.5470) then 5)::\r\n" + + "V(5, end)::\r\n" + + "nil)"); + configureIGWaypointInfo(ip); + m_m.setTargetWaypoint("l9"); + + + + EnergyConsumptionPredictor predictor = new EnergyConsumptionPredictor(m_e, m_m, m_p); + predictor.setConfig("sol_7"); + IInstruction firstInstruction = ip.getInstruction("1"); + ip.setExecutingInstruction("1", ""); + double energyRequired = predictor.getPlanEnergyConsumption(firstInstruction, ip.getRemainingInstructions(), "l9"); + assertTrue(energyRequired > 0); + assertTrue(energyRequired < MapTranslator.ROBOT_BATTERY_RANGE_MAX); + } + + private void configureIGWaypointInfo(InstructionGraphProgress ip) { + String currentSrc = m_e.getNode(m_m.getCurrentPose().getX(), m_m.getCurrentPose().getY()).getLabel(); + + Collection instructions = ip + .getInstructions(); + for (IInstruction i : instructions) { + if (i instanceof MoveAbsHInstruction) { + MoveAbsHInstruction mai = (MoveAbsHInstruction) i; + mai.setSourceWaypoint(currentSrc); + String tgtWp = m_e.getNode(mai.getTargetX(), mai.getTargetY()).getLabel(); + mai.setTargetWaypoint(tgtWp); + currentSrc = tgtWp; + } + } + } + +} diff --git a/deployments/rainbow-brass/src/test/java/TestIGProgress.java b/deployments/rainbow-brass/src/test/java/TestIGProgress.java index 55a3caf45..0e3fb1433 100644 --- a/deployments/rainbow-brass/src/test/java/TestIGProgress.java +++ b/deployments/rainbow-brass/src/test/java/TestIGProgress.java @@ -1,49 +1,49 @@ -import static org.junit.Assert.*; - -import java.util.List; - -import org.junit.Test; -import org.sa.rainbow.brass.model.instructions.ChargeInstruction; -import org.sa.rainbow.brass.model.instructions.IInstruction; -import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; -import org.sa.rainbow.core.models.ModelReference; - -public class TestIGProgress { - - @Test - public void testParseFromStringString() { - InstructionGraphProgress ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test"), - " P(V(1, do KillNodes(%laserscanNodelet%) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do SetSensor (%CAMERA%, %on%) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do StartNodes(%aruco%) then 6):: V(6, do MoveAbsH(-6.22, 0.00, 0.68, 1.5708) then 7):: V(7, do MoveAbsH(-6.22, 10.27, 0.68, 1.5708) then 8):: V(8, end):: nil)"); - assertTrue(ip.getInstructions().size() == 7); - - - } - - @Test - public void testSegmentByInstructionType() { - InstructionGraphProgress ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test")," P(V(1, do KillNodes(%laserscanNodelet%) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do SetSensor (%CAMERA%, %on%) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do Charge(200) then 6):: V(6, do MoveAbsH(-6.22, 0.00, 0.68, 1.5708) then 7):: V(7, do MoveAbsH(-6.22, 10.27, 0.68, 1.5708) then 8):: V(8, end):: nil)"); - List> s = InstructionGraphProgress.segmentByInstructionType(ip.getInstructions(), ChargeInstruction.class); - assertTrue(s.size() == 2); - // Two consecutive charges - ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test")," P(V(1, do KillNodes(%laserscanNodelet%) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do SetSensor (%CAMERA%, %on%) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do Charge(200) then 6):: V(6, do Charge(20) then 7):: V(7, do MoveAbsH(-6.22, 10.27, 0.68, 1.5708) then 8):: V(8, end):: nil)"); - s = InstructionGraphProgress.segmentByInstructionType(ip.getInstructions(), ChargeInstruction.class); - assertTrue(s.size() == 2); - - // Two charges not consecutive - ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test")," P(V(1, do KillNodes(%laserscanNodelet%) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do Charge(34) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do Charge(200) then 6):: V(6, do MoveAbseH(-6, -7, -9) then 7):: V(7, do MoveAbsH(-6.22, 10.27, 0.68, 1.5708) then 8):: V(8, end):: nil)"); - s = InstructionGraphProgress.segmentByInstructionType(ip.getInstructions(), ChargeInstruction.class); - assertTrue(s.size() == 3); - - // Charge at end only - ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test")," P(V(1, do KillNodes(%laserscanNodelet%) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do SetSensor (%CAMERA%, %on%) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do StartNodes(%aruco%) then 6):: V(6, do MoveAbsH(-6.22, 0.00, 0.68, 1.5708) then 7):: V(7, do Charge(2) then 8):: V(8, end):: nil)"); - s = InstructionGraphProgress.segmentByInstructionType(ip.getInstructions(), ChargeInstruction.class); - assertTrue(s.size() == 1); - - // Charge at begin and end - ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test")," P(V(1, do Charge(2) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do SetSensor (%CAMERA%, %on%) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do StartNodes(%aruco%) then 6):: V(6, do MoveAbsH(-6.22, 0.00, 0.68, 1.5708) then 7):: V(7, do Charge(2) then 8):: V(8, end):: nil)"); - s = InstructionGraphProgress.segmentByInstructionType(ip.getInstructions(), ChargeInstruction.class); - assertTrue(s.size() == 1); - - } - -} +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.Test; +import org.sa.rainbow.brass.model.instructions.ChargeInstruction; +import org.sa.rainbow.brass.model.instructions.IInstruction; +import org.sa.rainbow.brass.model.instructions.InstructionGraphProgress; +import org.sa.rainbow.core.models.ModelReference; + +public class TestIGProgress { + + @Test + public void testParseFromStringString() { + InstructionGraphProgress ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test"), + " P(V(1, do KillNodes(%laserscanNodelet%) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do SetSensor (%CAMERA%, %on%) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do StartNodes(%aruco%) then 6):: V(6, do MoveAbsH(-6.22, 0.00, 0.68, 1.5708) then 7):: V(7, do MoveAbsH(-6.22, 10.27, 0.68, 1.5708) then 8):: V(8, end):: nil)"); + assertTrue(ip.getInstructions().size() == 7); + + + } + + @Test + public void testSegmentByInstructionType() { + InstructionGraphProgress ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test")," P(V(1, do KillNodes(%laserscanNodelet%) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do SetSensor (%CAMERA%, %on%) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do Charge(200) then 6):: V(6, do MoveAbsH(-6.22, 0.00, 0.68, 1.5708) then 7):: V(7, do MoveAbsH(-6.22, 10.27, 0.68, 1.5708) then 8):: V(8, end):: nil)"); + List> s = InstructionGraphProgress.segmentByInstructionType(ip.getInstructions(), ChargeInstruction.class); + assertTrue(s.size() == 2); + // Two consecutive charges + ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test")," P(V(1, do KillNodes(%laserscanNodelet%) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do SetSensor (%CAMERA%, %on%) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do Charge(200) then 6):: V(6, do Charge(20) then 7):: V(7, do MoveAbsH(-6.22, 10.27, 0.68, 1.5708) then 8):: V(8, end):: nil)"); + s = InstructionGraphProgress.segmentByInstructionType(ip.getInstructions(), ChargeInstruction.class); + assertTrue(s.size() == 2); + + // Two charges not consecutive + ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test")," P(V(1, do KillNodes(%laserscanNodelet%) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do Charge(34) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do Charge(200) then 6):: V(6, do MoveAbseH(-6, -7, -9) then 7):: V(7, do MoveAbsH(-6.22, 10.27, 0.68, 1.5708) then 8):: V(8, end):: nil)"); + s = InstructionGraphProgress.segmentByInstructionType(ip.getInstructions(), ChargeInstruction.class); + assertTrue(s.size() == 3); + + // Charge at end only + ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test")," P(V(1, do KillNodes(%laserscanNodelet%) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do SetSensor (%CAMERA%, %on%) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do StartNodes(%aruco%) then 6):: V(6, do MoveAbsH(-6.22, 0.00, 0.68, 1.5708) then 7):: V(7, do Charge(2) then 8):: V(8, end):: nil)"); + s = InstructionGraphProgress.segmentByInstructionType(ip.getInstructions(), ChargeInstruction.class); + assertTrue(s.size() == 1); + + // Charge at begin and end + ip = InstructionGraphProgress.parseFromString (new ModelReference ("test", "test")," P(V(1, do Charge(2) then 2), V(2, do SetSensor (%KINECT%, %off%) then 3):: V(3, do SetSensor (%CAMERA%, %on%) then 4):: V(4, do SetSensor (%HEADLAMP%, %on%) then 5):: V(5, do StartNodes(%aruco%) then 6):: V(6, do MoveAbsH(-6.22, 0.00, 0.68, 1.5708) then 7):: V(7, do Charge(2) then 8):: V(8, end):: nil)"); + s = InstructionGraphProgress.segmentByInstructionType(ip.getInstructions(), ChargeInstruction.class); + assertTrue(s.size() == 1); + + } + +} diff --git a/deployments/rainbow-example/.classpath b/deployments/rainbow-example/.classpath index 48ef3eb0b..99a7bdb02 100644 --- a/deployments/rainbow-example/.classpath +++ b/deployments/rainbow-example/.classpath @@ -6,16 +6,18 @@ + + + - @@ -23,5 +25,10 @@ + + + + + diff --git a/deployments/rainbow-example/.project b/deployments/rainbow-example/.project index f4358baf4..565f5d2e2 100644 --- a/deployments/rainbow-example/.project +++ b/deployments/rainbow-example/.project @@ -5,6 +5,11 @@ + + org.eclipse.xtext.ui.shared.xtextBuilder + + + org.eclipse.jdt.core.javabuilder @@ -17,6 +22,7 @@ + org.eclipse.xtext.ui.shared.xtextNature org.eclipse.m2e.core.maven2Nature org.eclipse.jdt.core.javanature diff --git a/deployments/rainbow-example/Dockerfile b/deployments/rainbow-example/Dockerfile index 6961b487b..763f9a0be 100644 --- a/deployments/rainbow-example/Dockerfile +++ b/deployments/rainbow-example/Dockerfile @@ -1,6 +1,15 @@ FROM ubuntu:16.04 AS builder #maven:3-jdk-8 AS builder ARG rainbow_version=SWIM1.0 +# This overcomes the Hash Sum error with the standard ubuntu locations +RUN rm -f /etc/apt/sources.list +RUN echo "deb mirror://mirrors.ubuntu.com/mirrors.txt xenial main restricted universe multiverse" >> /etc/apt/sources.list +RUN echo "deb mirror://mirrors.ubuntu.com/mirrors.txt xenial-updates main restricted universe multiverse" >> /etc/apt/sources.list +RUN echo "deb-src mirror://mirrors.ubuntu.com/mirrors.txt xenial-updates main restricted universe multiverse" >> /etc/apt/sources.list +RUN echo "deb mirror://mirrors.ubuntu.com/mirrors.txt xenial-backports main restricted universe multiverse" >> /etc/apt/sources.list +RUN echo "deb mirror://mirrors.ubuntu.com/mirrors.txt xenial-security main restricted universe multiverse" >> /etc/apt/sources.list + +# Start real installation from here RUN apt update && apt-get install --no-install-recommends -y software-properties-common zip unzip tar gzip libboost-all-dev libyaml-cpp-dev make automake autoconf g++ ant wget libpcre3-dev socat swig curl bash git-core # To ensure the right versions of the libraries in the build @@ -47,14 +56,32 @@ RUN mvn -DskipTests install WORKDIR ../rainbow-mem-comms RUN mvn -DskipTests install +ADD ide /root/rainbow/ide +WORKDIR /root/rainbow/ide/org.acme.xtext.parent +RUN mvn -DskiptTests install +WORKDIR /root/rainbow/ide/org.sa.rainbow.stitch.parent +RUN mvn -DskipTests install +WORKDIR /root/rainbow/ide/org.sa.rainbow.configuration.parent +# This first is needed because of a bug in Tycho build classptahs +# https://stackoverflow.com/questions/5017687/use-maven-tycho-to-build-with-a-manifest-entry-bundle-classpath-that-gets-downlo +#RUN mkdir org.sa.rainbow.configuration/lib && cp /root/rainbow/rainbow/rainbow-core/target/rainbow-core*.jar org.sa.rainbow.configuration/lib/rainbow-core.jar +RUN mvn -DskipTests install + + ADD deployments /root/rainbow/deployments WORKDIR /root/rainbow/deployments/rainbow-example -RUN mvn -DskipTests install +RUN mvn -e -DskipTests install +RUN ls /root/rainbow/deployments/rainbow-example/src/main/resources/generated/rainbow-example/* CMD [/bin/bash] FROM gabrielmoreno/swim:1.0 ARG BUILD_ENV +# This overcomes the Hash Sum error with the standard ubuntu locations +#RUN cat /etc/apt/sources.list +#RUN sed --in-place=.bak -e "s/debian/ubuntu/" -e "s/http:\/\/security.debian.org xenial\/updates/http:\/\/mirrors.digitalocean.com\/ubuntu xenial-security/" /etc/apt/sources.list +#RUN cat /etc/apt/sources.list +# Start real installation from here RUN apt update && DEBIAN_FRONTEND=noninteractive apt-get -y install software-properties-common dbus dbus-x11 xorg xserver-xorg-legacy xinit xterm libboost-all-dev libyaml-cpp-dev libpcre3-dev socat RUN sed -i "s/allowed_users=console/allowed_users=anybody/;$ a needs_root_rights=yes" /etc/X11/Xwrapper.config @@ -71,7 +98,8 @@ COPY targets/rainbow-example targets/rainbow-example COPY license.html . COPY --from=builder /root/rainbow/deployments/rainbow-example/target/lib/* lib/ COPY --from=builder /root/rainbow/deployments/rainbow-example/target/*.jar lib/ - +COPY --from=builder /root/rainbow/deployments/rainbow-example/src/main/resources/generated/rainbow-example/ targets/rainbow-example/ +RUN ls targets/rainbow-example RUN echo "export SOCAT_PORT=4242" >> /headless/.bashrc RUN echo "export JAVA_FONTS=/usr/local/share/fonts/ms_fonts" >> /headless/.bashrc diff --git a/deployments/rainbow-example/docker/Rainbow-debug.desktop b/deployments/rainbow-example/docker/Rainbow-debug.desktop index 790ea0bb9..097dd31df 100644 --- a/deployments/rainbow-example/docker/Rainbow-debug.desktop +++ b/deployments/rainbow-example/docker/Rainbow-debug.desktop @@ -3,7 +3,7 @@ Version=1.0 Type=Application Name=Rainbow Debug Comment=Rainbow system for managing SWIM simulation -Exec=xterm -e "./run-oracle.sh -d -a -p rainbow-gui.properties rainbow-example | tee /rainbow/logs/rainbow-console.out" +Exec=xterm -e "./run-oracle.sh -d -a -p rainbow-gui.properties rainbow-example |& tee /rainbow/logs/rainbow-console.out" Icon=/headless/rainbow.png Path=/rainbow Terminal=false diff --git a/deployments/rainbow-example/docker/Rainbow.desktop b/deployments/rainbow-example/docker/Rainbow.desktop index 6953dcfe2..8f43876dc 100644 --- a/deployments/rainbow-example/docker/Rainbow.desktop +++ b/deployments/rainbow-example/docker/Rainbow.desktop @@ -3,7 +3,7 @@ Version=1.0 Type=Application Name=Rainbow Comment=Rainbow system for managing SWIM simulation -Exec=xterm -e "./run-oracle.sh -a -p rainbow-gui.properties rainbow-example | tee /rainbow/logs/rainbow-console.out" +Exec=xterm -e "./run-oracle.sh -a -p rainbow-gui.properties rainbow-example |& tee /rainbow/logs/rainbow-console.out" Icon=/headless/rainbow.png Path=/rainbow Terminal=false diff --git a/deployments/rainbow-example/pom.xml b/deployments/rainbow-example/pom.xml index 84f461ea9..88761aa48 100644 --- a/deployments/rainbow-example/pom.xml +++ b/deployments/rainbow-example/pom.xml @@ -1,357 +1,511 @@ - 4.0.0 - rainbow-example - rainbow-example - 3.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + rainbow-example + rainbow-example + 3.1.0-SNAPSHOT - - utf-8 - + + utf-8 + 3.1.0-SNAPSHOT + 1.0.1-SNAPSHOT + - - - - - - - Not yet defined. - - - manual - - Unknown - - + + + + + + + Not yet defined. + + + manual + + Unknown + + - - - - We - - http://www.we.com - + + + + We + + http://www.we.com + - - - - - - schmerl - - Bradley Schmerl - - schmerl@cs.cmu.edu - - CMU - - -5 - - - - - - - - pasc - Paulo Casanova - paulo.casanova@cs.cmu.edu - CMU - 0 - - - - - + + + + + + schmerl + + Bradley Schmerl + + schmerl@cs.cmu.edu + + CMU + + -5 + + + + + + + + pasc + Paulo Casanova + paulo.casanova@cs.cmu.edu + CMU + 0 + + + + + - - - - + + + + - + - - - - - scm:svn:svn://acme.able.cs.cmu.edu/rainbow/v2/trunk - - - - scm:svn:svn://acme.able.cs.cmu.edu/rainbow/v2/trunk - - - svn://acme.able.cs.cmu.edu/rainbow/v2/trunk - - - - - - org.apache.maven.wagon - wagon-webdav - 1.0-beta-2 - - + + + + + scm:svn:svn://acme.able.cs.cmu.edu/rainbow/v2/trunk + + + + scm:svn:svn://acme.able.cs.cmu.edu/rainbow/v2/trunk + + + svn://acme.able.cs.cmu.edu/rainbow/v2/trunk + + + + + + org.apache.maven.wagon + wagon-webdav + 1.0-beta-2 + + - - - - - org.apache.maven.plugins - maven-site-plugin - 3.2 - - - - - - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - - - - - - org.apache.maven.plugins - maven-release-plugin - 2.4 - - - http://svn.homenet/svn/projects/incubator/tags - - - + + + + + org.apache.maven.plugins + maven-site-plugin + 3.2 + + + + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.4 + + + http://svn.homenet/svn/projects/incubator/tags + + + - - - org.codehaus.mojo - buildnumber-maven-plugin - 1.1 - - - validate - - create - - - - + + + org.codehaus.mojo + buildnumber-maven-plugin + 1.1 + + + validate + + create + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + src/main/java-gen + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + test-jar + + + + + + + + true + + + + + ${buildNumber} + + + + + - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - - test-jar - - - - - - - - true - - - - - ${buildNumber} - - - - - + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12.4 + + -XX:-UseSplitVerifier + true + + + ${basedir} + + + + - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12.4 - - -XX:-UseSplitVerifier - true - - - ${basedir} - - - - + + maven-dependency-plugin + + + install + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + org.eclipse.xtext + xtext-maven-plugin + 2.19.0 + + + + generate + + + + + 1.8 + 1.8 + + + org.sa.rainbow.configuration.RclStandaloneSetup + + + src/main/java-gen + + + src/main/resources/generated + true + true + true + + + + + org.sa.rainbow.stitch.StitchStandaloneSetup + + + src/main/resources/generated + true + true + true + + + + + org.acme.AcmeStandaloneSetup + + + src/main/resources/generated + true + true + true + + + + + + src/main/resources/rbw + + + + + org.eclipse.emf + org.eclipse.emf.mwe2.launch + 2.11.0 + + + org.eclipse.xtext + org.eclipse.xtext.common.types + 2.19.0 + + + org.eclipse.xtext + org.eclipse.xtext.xtext.generator + 2.19.0 + + + org.eclipse.xtext + org.eclipse.xtext.xbase + 2.19.0 + + + org.eclipse.xtext + xtext-antlr-generator + 2.1.1 + + + + io.typefox.xtext + jflex-fragment + 0.2.1 + + + org.eclipse.xtext + org.eclipse.xtext.xbase.lib + 2.18.0 + - - maven-dependency-plugin - - - install - - copy-dependencies - - - ${project.build.directory}/lib - - - - - - + + org.sa.rainbow.stitch + org.sa.rainbow.stitch + 1.0.0-SNAPSHOT + + + + org.acme.xtext + org.acme.xtext + 1.0.0-SNAPSHOT + + + + org.sa.rainbow.configuration + org.sa.rainbow.configuration + ${rclVersion} + + + + + + + - + - - - - able.maven.repository - - dav:http://acme.able.cs.cmu.edu/maven-repository - - - + + + + able.maven.repository + + dav:http://acme.able.cs.cmu.edu/maven-repository + + + - + - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + - - - maven-javadoc-plugin - 2.9 - - true - - + + + maven-javadoc-plugin + 2.9 + + true + + - - - org.apache.maven.plugins - maven-jxr-plugin - 2.3 - + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + - - - org.apache.maven.plugins - maven-surefire-report-plugin - 2.12.4 - + + + org.apache.maven.plugins + maven-surefire-report-plugin + 2.12.4 + - - - org.codehaus.mojo - cobertura-maven-plugin - 2.5.2 - + + + org.codehaus.mojo + cobertura-maven-plugin + 2.5.2 + - - - org.apache.maven.plugins - maven-changes-plugin - 2.8 - + + + org.apache.maven.plugins + maven-changes-plugin + 2.8 + - - - org.codehaus.mojo - taglist-maven-plugin - 2.4 - - - TODO - FIXME - IDEA - @todo - @deprecated - - - + + + org.codehaus.mojo + taglist-maven-plugin + 2.4 + + + TODO + FIXME + IDEA + @todo + @deprecated + + + - - - org.apache.maven.plugins - maven-pmd-plugin - 2.7.1 - - true - iso8859-1 - 100 - 1.6 - - **/*Bean.java - **/generated/*.java - - - + + + org.apache.maven.plugins + maven-pmd-plugin + 2.7.1 + + true + iso8859-1 + 100 + 1.6 + + **/*Bean.java + **/generated/*.java + + + - - - org.codehaus.mojo - findbugs-maven-plugin - 2.5.2 - + + + org.codehaus.mojo + findbugs-maven-plugin + 2.5.2 + - - - - + + + + - + - - - + + + - - - able.maven.repository - ABLE maven repository - - dav:http://acme.able.cs.cmu.edu/maven-repository - - - + + + able.maven.repository + ABLE maven repository + + dav:http://acme.able.cs.cmu.edu/maven-repository + + + - + + rainbow rainbow-acme-model - 3.0 + ${rainbowVersion} rainbow rainbow-stitch - 3.0 + ${rainbowVersion} rainbow rainbow-utility-model - 3.0 + ${rainbowVersion} rainbow rainbow-gui - 3.0 + ${rainbowVersion} rainbow rainbow-mem-comms - 3.0 + ${rainbowVersion} xerces xercesImpl - 2.12.0 + 2.9.1 org.jfree @@ -454,3 +607,4 @@ + diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/gui/RainbowControl.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/gui/RainbowControl.java index 9d777e507..0c6baa7ad 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/gui/RainbowControl.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/gui/RainbowControl.java @@ -1,56 +1,56 @@ -package org.sa.rainbow.gui; - -import java.text.MessageFormat; -import java.util.EnumSet; - -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.globals.ExitState; -import org.sa.rainbow.core.ports.IMasterCommandPort; -import org.sa.rainbow.core.ports.IMasterConnectionPort.ReportType; -import org.sa.rainbow.core.ports.IRainbowReportingSubscriberPort; -import org.sa.rainbow.core.ports.IRainbowReportingSubscriberPort.IRainbowReportingSubscriberCallback; -import org.sa.rainbow.core.ports.RainbowPortFactory; - -public class RainbowControl { - - private static void usage() { - String usage = MessageFormat.format( - "Usage: {0} command\n\tcommand='{startprobes|killprobes|terminate}'", RainbowControl.class.getSimpleName()); - System.out.println(usage); - } - - public static void main (String[] args) throws RainbowConnectionException { - if (args.length != 1) { - usage(); - return; - } - - IMasterCommandPort master = RainbowPortFactory.createMasterCommandPort (); - IRainbowReportingSubscriberPort reportingSubscriberPort = RainbowPortFactory - .createReportingSubscriberPort (new IRainbowReportingSubscriberCallback () { - - @Override - public void report (RainbowComponentT component, ReportType type, String message) { - if (type == ReportType.ERROR || type == ReportType.FATAL || type == ReportType.WARNING) { - System.out.println (type.name () + ": " + message); - } - if (component == RainbowComponentT.GAUGE) { - System.out.println ("Gauge: " + message); - } - } - }); - reportingSubscriberPort.subscribe (EnumSet.allOf (RainbowComponentT.class), EnumSet.allOf (ReportType.class)); - - if (args[0].equals("startprobes")) { - master.startProbes (); - } else if (args[0].equals("killprobes")) { - master.killProbes(); - } else if (args[0].equals("terminate")) { - master.terminate (ExitState.DESTRUCT); - } else { - usage(); - } - System.exit (1); - } -} +package org.sa.rainbow.gui; + +import java.text.MessageFormat; +import java.util.EnumSet; + +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.globals.ExitState; +import org.sa.rainbow.core.ports.IMasterCommandPort; +import org.sa.rainbow.core.ports.IMasterConnectionPort.ReportType; +import org.sa.rainbow.core.ports.IRainbowReportingSubscriberPort; +import org.sa.rainbow.core.ports.IRainbowReportingSubscriberPort.IRainbowReportingSubscriberCallback; +import org.sa.rainbow.core.ports.RainbowPortFactory; + +public class RainbowControl { + + private static void usage() { + String usage = MessageFormat.format( + "Usage: {0} command\n\tcommand='{startprobes|killprobes|terminate}'", RainbowControl.class.getSimpleName()); + System.out.println(usage); + } + + public static void main (String[] args) throws RainbowConnectionException { + if (args.length != 1) { + usage(); + return; + } + + IMasterCommandPort master = RainbowPortFactory.createMasterCommandPort (); + IRainbowReportingSubscriberPort reportingSubscriberPort = RainbowPortFactory + .createReportingSubscriberPort (new IRainbowReportingSubscriberCallback () { + + @Override + public void report (RainbowComponentT component, ReportType type, String message) { + if (type == ReportType.ERROR || type == ReportType.FATAL || type == ReportType.WARNING) { + System.out.println (type.name () + ": " + message); + } + if (component == RainbowComponentT.GAUGE) { + System.out.println ("Gauge: " + message); + } + } + }); + reportingSubscriberPort.subscribe (EnumSet.allOf (RainbowComponentT.class), EnumSet.allOf (ReportType.class)); + + if (args[0].equals("startprobes")) { + master.startProbes (); + } else if (args[0].equals("killprobes")) { + master.killProbes(); + } else if (args[0].equals("terminate")) { + master.terminate (ExitState.DESTRUCT); + } else { + usage(); + } + System.exit (1); + } +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java index 6fc7aabcb..c6d4870e2 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java @@ -1,114 +1,114 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim; - -import java.util.HashSet; -import java.util.Set; -import java.util.Stack; - -import org.acmestudio.acme.core.resource.RegionManager; -import org.acmestudio.acme.element.IAcmeElementInstance; -import org.acmestudio.acme.element.IAcmeElementType; -import org.acmestudio.acme.environment.error.AcmeError; -import org.acmestudio.acme.rule.AcmeSet; -import org.acmestudio.acme.rule.node.IExpressionNode; -import org.acmestudio.acme.type.verification.NodeScopeLookup; -import org.acmestudio.acme.type.verification.RuleTypeChecker; -import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; - -/** - * This class provides SWIM-specific operators that can be referred to in strategies and tactics. This class can be - * imported into Stitch and the static members called from there. - * - * @author Bradley Schmerl: schmerl - * @author gmoreno - */ -public class Swim { - // Acme expressions for evaluating the methods - private static final String FIND_SERVICES_EXPR = "/self/components:T[!isArchEnabled]"; - private static final String AVAILABLE_SERVICES_EXPR = "size (" + FIND_SERVICES_EXPR + ")"; - // Holder objects for caching parsed Acme expressions - private static IExpressionNode s_availableServicesExpr = null; - private static IExpressionNode s_findServicesExpression; - - /** - * Returns the number services of a particular type that are available. Availability here means that they are not - * yet marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type - * - * @param model - * The model to find availabile services in - * @param elemType - * The type of service to find - * @return the number of services that are available. - * @throws Exception - */ - public static int availableServices (SwimModelUpdateOperatorsImpl model, IAcmeElementType elemType) - throws Exception { - if (s_availableServicesExpr == null) { - s_availableServicesExpr = StandaloneLanguagePackHelper.defaultLanguageHelper () - .designRuleExpressionFromString ( - AVAILABLE_SERVICES_EXPR, new RegionManager ()); - } - - // Add "T" as a name in scope, referring to the type that we are looking for - NodeScopeLookup nameLookup = new NodeScopeLookup (); - nameLookup.put ("T", elemType); - return RuleTypeChecker.evaluateAsInt (model.getModelInstance (), null, s_availableServicesExpr, - new Stack (), - nameLookup); - } - - /** - * Returns the services of a particular type that are available. Availability here means that they are not yet - * marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type - * - * @param model - * The model to find availabile services in - * @param type - * The type of service to find - * @return the number of services that are available. - * @throws Exception - */ - public static Set> findServices (SwimModelUpdateOperatorsImpl model, - IAcmeElementType type) - throws Exception { - if (s_findServicesExpression == null) { - s_findServicesExpression = StandaloneLanguagePackHelper.defaultLanguageHelper () - .designRuleExpressionFromString (FIND_SERVICES_EXPR, new RegionManager ()); - } - NodeScopeLookup nameLookup = new NodeScopeLookup (); - nameLookup.put ("T", type); - AcmeSet set = RuleTypeChecker.evaluateAsSet (model.getModelInstance (), null, s_findServicesExpression, - new Stack (), - nameLookup); - - Set> retSet = new HashSet<> (); - for (Object o : set.getValues ()) { - if (o instanceof IAcmeElementInstance) { - retSet.add ((IAcmeElementInstance )o); - } - } - return retSet; - } -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim; + +import java.util.HashSet; +import java.util.Set; +import java.util.Stack; + +import org.acmestudio.acme.core.resource.RegionManager; +import org.acmestudio.acme.element.IAcmeElementInstance; +import org.acmestudio.acme.element.IAcmeElementType; +import org.acmestudio.acme.environment.error.AcmeError; +import org.acmestudio.acme.rule.AcmeSet; +import org.acmestudio.acme.rule.node.IExpressionNode; +import org.acmestudio.acme.type.verification.NodeScopeLookup; +import org.acmestudio.acme.type.verification.RuleTypeChecker; +import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; + +/** + * This class provides SWIM-specific operators that can be referred to in strategies and tactics. This class can be + * imported into Stitch and the static members called from there. + * + * @author Bradley Schmerl: schmerl + * @author gmoreno + */ +public class Swim { + // Acme expressions for evaluating the methods + private static final String FIND_SERVICES_EXPR = "/self/components:T[!isArchEnabled]"; + private static final String AVAILABLE_SERVICES_EXPR = "size (" + FIND_SERVICES_EXPR + ")"; + // Holder objects for caching parsed Acme expressions + private static IExpressionNode s_availableServicesExpr = null; + private static IExpressionNode s_findServicesExpression; + + /** + * Returns the number services of a particular type that are available. Availability here means that they are not + * yet marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type + * + * @param model + * The model to find availabile services in + * @param elemType + * The type of service to find + * @return the number of services that are available. + * @throws Exception + */ + public static int availableServices (SwimModelUpdateOperatorsImpl model, IAcmeElementType elemType) + throws Exception { + if (s_availableServicesExpr == null) { + s_availableServicesExpr = StandaloneLanguagePackHelper.defaultLanguageHelper () + .designRuleExpressionFromString ( + AVAILABLE_SERVICES_EXPR, new RegionManager ()); + } + + // Add "T" as a name in scope, referring to the type that we are looking for + NodeScopeLookup nameLookup = new NodeScopeLookup (); + nameLookup.put ("T", elemType); + return RuleTypeChecker.evaluateAsInt (model.getModelInstance (), null, s_availableServicesExpr, + new Stack (), + nameLookup); + } + + /** + * Returns the services of a particular type that are available. Availability here means that they are not yet + * marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type + * + * @param model + * The model to find availabile services in + * @param type + * The type of service to find + * @return the number of services that are available. + * @throws Exception + */ + public static Set> findServices (SwimModelUpdateOperatorsImpl model, + IAcmeElementType type) + throws Exception { + if (s_findServicesExpression == null) { + s_findServicesExpression = StandaloneLanguagePackHelper.defaultLanguageHelper () + .designRuleExpressionFromString (FIND_SERVICES_EXPR, new RegionManager ()); + } + NodeScopeLookup nameLookup = new NodeScopeLookup (); + nameLookup.put ("T", type); + AcmeSet set = RuleTypeChecker.evaluateAsSet (model.getModelInstance (), null, s_findServicesExpression, + new Stack (), + nameLookup); + + Set> retSet = new HashSet<> (); + for (Object o : set.getValues ()) { + if (o instanceof IAcmeElementInstance) { + retSet.add ((IAcmeElementInstance )o); + } + } + return retSet; + } +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/SwimModelUpdateOperatorsImpl.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/SwimModelUpdateOperatorsImpl.java index 652bfd2e8..25b43e8c6 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/SwimModelUpdateOperatorsImpl.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/SwimModelUpdateOperatorsImpl.java @@ -1,268 +1,87 @@ -/* - * The MIT License - * - * Copyright 2import org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.model.acme.AcmeModelInstance; -import org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory; -oftware"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.Vector; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.IntStream; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; -import org.acmestudio.acme.core.type.IAcmeIntValue; -import org.acmestudio.acme.element.IAcmeElementInstance; -import org.acmestudio.acme.element.IAcmeElementType; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.DefaultAcmeModel; -import org.acmestudio.acme.type.AcmeTypeHelper; -import org.apache.commons.lang.NotImplementedException; -import org.apache.log4j.Logger; -import org.sa.rainbow.model.acme.AcmeModelInstance; -import org.sa.rainbow.model.acme.swim.commands.SwimCommandFactory; - -import javassist.Modifier; - -/** - * An Acme model that embodies the SWIM architecture and the associated - * style-specific operations - * - * @author Bradley Schmerl: schmerl - * @author gmoreno - */ -public class SwimModelUpdateOperatorsImpl extends AcmeModelInstance { - private static final String MAX_KEY = "[Max]"; - private static final String AVG_KEY = "[Avg]"; - private static final String CALL_KEY = "[CALL]"; - - private final Logger LOGGER = Logger.getLogger(this.getClass()); - - private SwimCommandFactory m_commandFactory; - - public SwimModelUpdateOperatorsImpl(IAcmeSystem system, String source) { - super(system, source); - // Make sure it is the right family - } - - @Override - public SwimCommandFactory getCommandFactory() { - if (m_commandFactory == null) { - m_commandFactory = new SwimCommandFactory(this); - } - return m_commandFactory; - } - - @Override - protected AcmeModelInstance generateInstance(IAcmeSystem sys) { - return new SwimModelUpdateOperatorsImpl(sys, getOriginalSource()); - } - - @Override - public Object getProperty(String id) { - if (getModelInstance() == null) - return null; - Object prop = null; - if (id.startsWith(MAX_KEY) || id.startsWith(AVG_KEY) || id.startsWith(CALL_KEY)) { - prop = internalGetProperty(id, 0); - } else { - prop = super.getProperty(id); - } - return prop; - } - - /** - * Gets current or predicted property, depending on whether prediction is - * enabled and future duration is greater than 0. - * - * @param id the identifier for the property to get value for - * @param dur duration into the future to predict value, if applicable - * @return the Object that represents the value of the sought property. - */ - private Object internalGetProperty(String id, long dur) { - if (dur > 0) - throw new NotImplementedException("Prediction is not implemented"); - if (getModelInstance() == null) - return null; - Object prop = null; - if (id.startsWith(MAX_KEY)) { - // the property id is expected to be of the form . - int idxStart = MAX_KEY.length(); - int idxDot = id.indexOf("."); - if (idxDot == -1) { // property ID is not of expected form - LOGGER.error("Unrecognized form of Max Property Name!" + id); - return null; - } - String typeName = id.substring(idxStart, idxDot); - String propName = id.substring(idxDot + 1); - - List propValues = collectInstancePropValues(typeName, propName); - if (propValues.size() > 0) { - - // find the maximum value of the property - double max = -Double.MAX_VALUE; - for (Double v : propValues) { - max = Math.max(max, v); - } - prop = max; - } - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Max Prop " + id + (dur > 0 ? "(+" + dur + ") " : "") + " requested == " + prop); - } - } else if (id.startsWith(AVG_KEY)) { - // the property id is expected to be of the form . - int idxStart = AVG_KEY.length(); - int idxDot = id.indexOf("."); - if (idxDot == -1) { // property ID is not of expected form - LOGGER.error("Unrecognized form of Average Property Name!" + id); - return null; - } - String typeName = id.substring(idxStart, idxDot); - String propName = id.substring(idxDot + 1); - - List propValues = collectInstancePropValues(typeName, propName); - if (propValues.size() > 0) { - - // find the average value of the property - double sum = 0.0; - for (Double v : propValues) { - sum += v; - } - prop = sum / propValues.size(); - } - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Avg Prop " + id + (dur > 0 ? "(+" + dur + ") " : "") + " requested == " + prop); - } - } else if (id.startsWith(CALL_KEY)) { - int idxStart = CALL_KEY.length(); - String call = id.substring(idxStart); - Pattern methodRegex = Pattern.compile("([^\\(]*)\\(([^\\)]*)\\)"); - Matcher m = methodRegex.matcher(call); - if (m.matches()) { - String method = m.group(1); - String[] args = Arrays.stream(m.group(2).split(",")).map(String::trim).toArray(String[]::new); - - int dotIdx = method.lastIndexOf("."); - String methodClass = null; - if (dotIdx > -1) { - methodClass = method.substring(0, dotIdx); - method = method.substring(dotIdx + 1); - } - if (methodClass == null) { - LOGGER.error("Could not identify a class for the method `" + method + "'"); - return null; - } - - Class clazz; - try { - clazz = Class.forName(methodClass); - } catch (ClassNotFoundException e) { - LOGGER.error(MessageFormat.format("Could not find class ''{0}''", methodClass)); - return null; - } - Object result = null; - Object[] argumentsJ = new Object[args.length]; - for (int i = 0; i < argumentsJ.length; i++) { - argumentsJ[i] = getProperty(args[i]); - } - - for (Method mthd : clazz.getDeclaredMethods()) { - if (mthd.getName().equals(method) && Modifier.isStatic(mthd.getModifiers()) - && mthd.getParameterTypes().length == args.length) { -// Object[] argumentsJ = IntStream.range(0, args.length). -// mapToObj(i -> PropertyHelper.toJavaVal(getProperty(args[i]), mthd.getParameterTypes()[i])).toArray(); - try { - result = mthd.invoke(null, argumentsJ); - break; - } catch (IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - } - } - } - return result; - - } - - } - - return prop; - } - - /** - * Iterates through model's systems to collect all instances that either - * declares or instantiates the specified type name, then for all instances - * found that also have the specified property names, collect the property - * values - * - * @param typeName the specified element type name - * @param propName the specified property name within relevant instance - * @return the list of property values - */ - - private List collectInstancePropValues(String typeName, String propName) { - Vector values = new Vector<>(); - boolean useSatisfies = false; - if (typeName.startsWith("!")) { - typeName = typeName.substring(1); - useSatisfies = true; - } - // Object elemObj = m_acme.findNamedObject(m_acme, typeName); - // if (! (elemObj instanceof IAcmeElementType)) { - // Debug.errorln("Element type of Average Property requested NOT found! " - // + typeName); - // return propKeys; - // } - IAcmeSystem sys = getModelInstance(); - Set> children = new HashSet<>(); - children.addAll(sys.getComponents()); - children.addAll(sys.getConnectors()); - children.addAll(sys.getPorts()); - children.addAll(sys.getRoles()); - for (IAcmeElementInstance child : children) { - - // seek element with specified type AND specified property - if ((useSatisfies && AcmeTypeHelper.satisfiesElementType(child, - ((IAcmeElementType) child.lookupName(typeName, true)), null)) || child.declaresType(typeName) - || child.instantiatesType(typeName)) { - IAcmeProperty childProp = child.getProperty(propName); - childProp.getValue(); - if (childProp != null) { - if (childProp.getType() == DefaultAcmeModel.defaultIntType()) { - values.add((double) ((IAcmeIntValue) childProp.getValue()).getValue()); - } else if (childProp.getType() == DefaultAcmeModel.defaultFloatType()) { - values.add(((IAcmeFloatingPointValue) childProp.getValue()).getDoubleValue()); - } - } - } - } - return values; - } -} +/* + * The MIT License + * + * Copyright 2import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory; +oftware"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.IntStream; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; +import org.acmestudio.acme.core.type.IAcmeIntValue; +import org.acmestudio.acme.element.IAcmeElementInstance; +import org.acmestudio.acme.element.IAcmeElementType; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.DefaultAcmeModel; +import org.acmestudio.acme.type.AcmeTypeHelper; +import org.apache.commons.lang.NotImplementedException; +import org.apache.log4j.Logger; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.swim.commands.SwimCommandFactory; + +import javassist.Modifier; + +/** + * An Acme model that embodies the SWIM architecture and the associated + * style-specific operations + * + * @author Bradley Schmerl: schmerl + * @author gmoreno + */ +public class SwimModelUpdateOperatorsImpl extends AcmeModelInstance { + + private final Logger LOGGER = Logger.getLogger(this.getClass()); + + private SwimCommandFactory m_commandFactory; + + public SwimModelUpdateOperatorsImpl(IAcmeSystem system, String source) { + super(system, source); + // Make sure it is the right family + } + + @Override + public SwimCommandFactory getCommandFactory() throws RainbowException { + if (m_commandFactory == null) { + m_commandFactory = new SwimCommandFactory(this); + } + return m_commandFactory; + } + + @Override + protected AcmeModelInstance generateInstance(IAcmeSystem sys) { + return new SwimModelUpdateOperatorsImpl(sys, getOriginalSource()); + } + + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java index 767fc4091..ade702880 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java @@ -1,103 +1,103 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -/** - * A class representing the Acme command to activate a server in SWIM. - * This is represented using the property isActive - * - * @author Bradley Schmerl: schmerl - * @author gmoreno - * - */ -public class ActivateServerCmd extends SwimAcmeModelCommand { - - private static final String PROPERTY = "isActive"; - - - // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" - public ActivateServerCmd (AcmeModelInstance model, String target, String enable) { - super ("activateServer", model, target, enable); - } - - /** - * Constructs the list of commands for activating the server by setting the isActive property - * - * @return the list of commands - * @throws RainbowModelException - * when the server cannot be found, is of the incorrect type, or the argument is malformed. - */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - List> cmds = new LinkedList<> (); - IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", getTarget ())); - IAcmeProperty property = server.getProperty (PROPERTY); - if (property == null) { - throw new RainbowModelException(MessageFormat.format( - "The server ''{0}'' is not of the right type. It does not have a property ''" + PROPERTY + "''", - getTarget())); - } - try { - IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Boolean.valueOf (getParameters ()[0])); - if (propertyValueChanging (property, acmeVal)) { - m_command = property.getCommandFactory ().propertyValueSetCommand (property, - acmeVal); - cmds.add (m_command); - } - } - catch (IllegalArgumentException e) { - throw new RainbowModelException (e.getMessage (), e); - } - return cmds; - - } - - - /** - * - * @return the property after the command has been executed - * @throws IllegalStateException - */ - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * A class representing the Acme command to activate a server in SWIM. + * This is represented using the property isActive + * + * @author Bradley Schmerl: schmerl + * @author gmoreno + * + */ +public class ActivateServerCmd extends SwimAcmeModelCommand { + + private static final String PROPERTY = "isActive"; + + + // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" + public ActivateServerCmd (String commandName, AcmeModelInstance model, String target, String enable) { + super (commandName, model, target, enable); + } + + /** + * Constructs the list of commands for activating the server by setting the isActive property + * + * @return the list of commands + * @throws RainbowModelException + * when the server cannot be found, is of the incorrect type, or the argument is malformed. + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + IAcmeProperty property = server.getProperty (PROPERTY); + if (property == null) { + throw new RainbowModelException(MessageFormat.format( + "The server ''{0}'' is not of the right type. It does not have a property ''" + PROPERTY + "''", + getTarget())); + } + try { + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Boolean.valueOf (getParameters ()[0])); + if (propertyValueChanging (property, acmeVal)) { + m_command = property.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + } + catch (IllegalArgumentException e) { + throw new RainbowModelException (e.getMessage (), e); + } + return cmds; + + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java index d78b964e6..f6bb8caf3 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java @@ -1,120 +1,120 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -/** - * A class representing the Acme command to add a server to SWIM - * - * @author gmoreno - */ -public class AddServerCmd extends SwimAcmeModelCommand { - - private static final String PROPERTY = "expectedActivationTime"; - - private String m_server; - - - /** - * Target is the server add - * - * Note that since in SWIM we just add a server (not add a particular server) - * the target must be the server not currently enabled with the lowest index. - * - * This command does not mark the server as enabled. It only sets its expected - * activation time. Enablement happens through the gauge when is reported by the - * probe. - * - * The target is the load balancer, and the server is the server to be added - */ - public AddServerCmd (AcmeModelInstance model, String target, String server) { - super ("addServer", model, target, server); - m_server = server; - } - - /** - * Constructs the list of commands for setting the expectedActivationTime property - * - * @return the list of commands - * @throws RainbowModelException - * when the server cannot be found, is of the incorrect type, or the argument is malformed. - */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - List> cmds = new LinkedList<> (); - IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", m_server)); - IAcmeProperty property = server.getProperty (PROPERTY); - if (property == null) { - throw new RainbowModelException(MessageFormat.format( - "The server ''{0}'' is not of the right type. It does not have a property ''{1}''", - m_server, PROPERTY)); - } - - IAcmeProperty prop = getModelContext().getModelInstance().getProperty("ADD_SERVER_LATENCY_SEC"); - int addServerLatency = ((Integer) PropertyHelper.toJavaVal(prop.getValue())).intValue(); - int expectedActivationTime = (int)(System.currentTimeMillis() / 1000) + addServerLatency; - - try { - IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Integer.valueOf(expectedActivationTime)); - if (propertyValueChanging (property, acmeVal)) { - m_command = property.getCommandFactory ().propertyValueSetCommand (property, - acmeVal); - cmds.add (m_command); - } - } - catch (IllegalArgumentException e) { - throw new RainbowModelException (e.getMessage (), e); - } - - return cmds; - - } - - - /** - * - * @return the property after the command has been executed - * @throws IllegalStateException - */ - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * A class representing the Acme command to add a server to SWIM + * + * @author gmoreno + */ +public class AddServerCmd extends SwimAcmeModelCommand { + + private static final String PROPERTY = "expectedActivationTime"; + + private String m_server; + + + /** + * Target is the server add + * + * Note that since in SWIM we just add a server (not add a particular server) + * the target must be the server not currently enabled with the lowest index. + * + * This command does not mark the server as enabled. It only sets its expected + * activation time. Enablement happens through the gauge when is reported by the + * probe. + * + * The target is the load balancer, and the server is the server to be added + */ + public AddServerCmd (String commandName, AcmeModelInstance model, String target, String server) { + super (commandName, model, target, server); + m_server = server; + } + + /** + * Constructs the list of commands for setting the expectedActivationTime property + * + * @return the list of commands + * @throws RainbowModelException + * when the server cannot be found, is of the incorrect type, or the argument is malformed. + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", m_server)); + IAcmeProperty property = server.getProperty (PROPERTY); + if (property == null) { + throw new RainbowModelException(MessageFormat.format( + "The server ''{0}'' is not of the right type. It does not have a property ''{1}''", + m_server, PROPERTY)); + } + + IAcmeProperty prop = getModelContext().getModelInstance().getProperty("ADD_SERVER_LATENCY_SEC"); + int addServerLatency = ((Integer) PropertyHelper.toJavaVal(prop.getValue())).intValue(); + int expectedActivationTime = (int)(System.currentTimeMillis() / 1000) + addServerLatency; + + try { + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Integer.valueOf(expectedActivationTime)); + if (propertyValueChanging (property, acmeVal)) { + m_command = property.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + } + catch (IllegalArgumentException e) { + throw new RainbowModelException (e.getMessage (), e); + } + + return cmds; + + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java index d4c28a719..225fef65b 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java @@ -1,107 +1,107 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -/** - * A class representing the Acme command to enable a server in Znn. Currently, this is modeled by setting the property - * "isArchEnabled" on the model. - * - * @author Bradley Schmerl: schmerl - * - */ -public class EnableServerCmd extends SwimAcmeModelCommand { - - // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" - public EnableServerCmd (AcmeModelInstance model, String target, String enable) { - super ("enableServer", model, target, enable); - } - - /** - * Constructs the list of commands for enabling the server by setting the isArchEnabled property - * - * @return the list of commands - * @throws RainbowModelException - * when the server cannot be found, is of the incorrect type, or the argument is malformed. - */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - List> cmds = new LinkedList<> (); - IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", getTarget ())); - if (!server.declaresType ("ArchElementT")) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' is not of the right type. It does not have a property ''isArchEnabled''", - getTarget ())); - IAcmeProperty property = server.getProperty ("isArchEnabled"); - try { - boolean enabled = Boolean.valueOf (getParameters ()[0]); - IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (enabled); - if (propertyValueChanging (property, acmeVal)) { - m_command = property.getCommandFactory ().propertyValueSetCommand (property, - acmeVal); - cmds.add (m_command); - } - if (!enabled) { - - // set the load to 0, so that it does not affect the average - IAcmeProperty loadProperty = server.getProperty ("load"); - IAcmeCommand newCommand = loadProperty.getCommandFactory ().propertyValueSetCommand (loadProperty, - PropertyHelper.toAcmeVal(0.0)); - cmds.add(newCommand); - } - } - catch (IllegalArgumentException e) { - throw new RainbowModelException (e.getMessage (), e); - } - return cmds; - - } - - - /** - * - * @return the property after the command has been executed - * @throws IllegalStateException - */ - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * A class representing the Acme command to enable a server in Znn. Currently, this is modeled by setting the property + * "isArchEnabled" on the model. + * + * @author Bradley Schmerl: schmerl + * + */ +public class EnableServerCmd extends SwimAcmeModelCommand { + + // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" + public EnableServerCmd (String commandName, AcmeModelInstance model, String target, String enable) { + super (commandName, model, target, enable); + } + + /** + * Constructs the list of commands for enabling the server by setting the isArchEnabled property + * + * @return the list of commands + * @throws RainbowModelException + * when the server cannot be found, is of the incorrect type, or the argument is malformed. + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + if (!server.declaresType ("ArchElementT")) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''isArchEnabled''", + getTarget ())); + IAcmeProperty property = server.getProperty ("isArchEnabled"); + try { + boolean enabled = Boolean.valueOf (getParameters ()[0]); + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (enabled); + if (propertyValueChanging (property, acmeVal)) { + m_command = property.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + if (!enabled) { + + // set the load to 0, so that it does not affect the average + IAcmeProperty loadProperty = server.getProperty ("load"); + IAcmeCommand newCommand = loadProperty.getCommandFactory ().propertyValueSetCommand (loadProperty, + PropertyHelper.toAcmeVal(0.0)); + cmds.add(newCommand); + } + } + catch (IllegalArgumentException e) { + throw new RainbowModelException (e.getMessage (), e); + } + return cmds; + + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java index b2f549565..50f8df3bc 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java @@ -1,79 +1,79 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import java.util.LinkedList; -import java.util.List; - -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -/** - * A class representing the Acme command to remove a server from SWIM - * - * @author gmoreno - */ -public class RemoveServerCmd extends SwimAcmeModelCommand { - - /** - * Target is the server add - * - * Note that since in SWIM we just remove a server (not a particular server) - * the target must be the server currently enabled with the highest index. - * - * This command does not mark the server as not enabled. That happens - * through the gauge when is reported by the probe. - * - * The target is the load balancer, and the server is the server to be removed - */ - public RemoveServerCmd (AcmeModelInstance model, String target, String server) { - super ("removeServer", model, target, server); - } - - /** - * Nothing is changed in the model, so the command is empty - * - * @return the list of commands - */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - List> cmds = new LinkedList<> (); - return cmds; - } - - - /** - * - * @return the property after the command has been executed - * @throws IllegalStateException - */ - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.LinkedList; +import java.util.List; + +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +/** + * A class representing the Acme command to remove a server from SWIM + * + * @author gmoreno + */ +public class RemoveServerCmd extends SwimAcmeModelCommand { + + /** + * Target is the server add + * + * Note that since in SWIM we just remove a server (not a particular server) + * the target must be the server currently enabled with the highest index. + * + * This command does not mark the server as not enabled. That happens + * through the gauge when is reported by the probe. + * + * The target is the load balancer, and the server is the server to be removed + */ + public RemoveServerCmd (String commandName, AcmeModelInstance model, String target, String server) { + super (commandName, model, target, server); + } + + /** + * Nothing is changed in the model, so the command is empty + * + * @return the list of commands + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + return cmds; + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java index 9911980f5..f19954ba2 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetArrivalRateCmd extends SetDoubleCmd { - private final static String COMMAND = "setArrivalRate"; - private final static String PROPERTY = "arrivalRate"; - - public SetArrivalRateCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetArrivalRateCmd extends SetDoubleCmd { + private final static String PROPERTY = "arrivalRate"; + + public SetArrivalRateCmd(String commandName, AcmeModelInstance model, String component, String value) { + super(commandName, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicResponseTimeCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicResponseTimeCmd.java index 0a0bdddce..f3646daae 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicResponseTimeCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicResponseTimeCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetBasicResponseTimeCmd extends SetDoubleCmd { - private final static String COMMAND = "setBasicResponseTime"; - private final static String PROPERTY = "basicResponseTime"; - - public SetBasicResponseTimeCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetBasicResponseTimeCmd extends SetDoubleCmd { + private final static String PROPERTY = "basicResponseTime"; + + public SetBasicResponseTimeCmd(String commandName, AcmeModelInstance model, String component, String value) { + super(commandName, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java index eb9947e06..8cf402035 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetBasicThroughputCmd extends SetDoubleCmd { - private final static String COMMAND = "setBasicThroughput"; - private final static String PROPERTY = "basicThroughput"; - - public SetBasicThroughputCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetBasicThroughputCmd extends SetDoubleCmd { + private final static String PROPERTY = "basicThroughput"; + + public SetBasicThroughputCmd(String commandName, AcmeModelInstance model, String component, String value) { + super(commandName, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java index 9b7403224..f4f04ab46 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetDimmerCmd extends SetDoubleCmd { - private final static String COMMAND = "setDimmer"; - private final static String PROPERTY = "dimmer"; - - public SetDimmerCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetDimmerCmd extends SetDoubleCmd { + private final static String PROPERTY = "dimmer"; + + public SetDimmerCmd(String commandName, AcmeModelInstance model, String component, String value) { + super(commandName, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java index 28ea340e5..cce8c3e5c 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java @@ -1,98 +1,98 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -public abstract class SetDoubleCmd extends SwimAcmeModelCommand { - - protected String m_property; - - private String m_component; - private double m_value; - - public SetDoubleCmd (String command, String property, AcmeModelInstance model, String component, String value) { - super (command, model, component, value); - m_component = component; - m_value = Double.valueOf (value); - m_property = property; - } - - /** - * This method can be overriden by derived classes to process the value - * before it is set in the model. - * - * @param value - * @return processed value to be set in the model - */ - public double processValue(double value) { - return value; - } - - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent server = getModelContext ().resolveInModel (m_component, IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", getTarget ())); - IAcmeProperty property = server.getProperty (m_property); - if (property == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' is not of the right type. It does not have a property ''{1}''", - getTarget (), m_property)); - - try { - IAcmeFloatingPointValue acmeVal = PropertyHelper.toAcmeVal (m_value); - List> cmds = new LinkedList<> (); - if (propertyValueChanging (property, acmeVal)) { - m_command = server.getCommandFactory ().propertyValueSetCommand (property, acmeVal); - cmds.add (m_command); - } - return cmds; - } - catch (Exception e) { - throw new RainbowModelException (MessageFormat.format ("Error setting ACME model property ''{0}.{1}: {3}", - getTarget(), m_property, e.getMessage())); - } - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +public abstract class SetDoubleCmd extends SwimAcmeModelCommand { + + protected String m_property; + + private String m_component; + private double m_value; + + public SetDoubleCmd (String command, String property, AcmeModelInstance model, String component, String value) { + super (command, model, component, value); + m_component = component; + m_value = Double.valueOf (value); + m_property = property; + } + + /** + * This method can be overriden by derived classes to process the value + * before it is set in the model. + * + * @param value + * @return processed value to be set in the model + */ + public double processValue(double value) { + return value; + } + + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent server = getModelContext ().resolveInModel (m_component, IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + IAcmeProperty property = server.getProperty (m_property); + if (property == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''{1}''", + getTarget (), m_property)); + + try { + IAcmeFloatingPointValue acmeVal = PropertyHelper.toAcmeVal (m_value); + List> cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = server.getCommandFactory ().propertyValueSetCommand (property, acmeVal); + cmds.add (m_command); + } + return cmds; + } + catch (Exception e) { + throw new RainbowModelException (MessageFormat.format ("Error setting ACME model property ''{0}.{1}: {3}", + getTarget(), m_property, e.getMessage())); + } + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetLoadCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetLoadCmd.java index 6751cad0d..6d24671de 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetLoadCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetLoadCmd.java @@ -27,11 +27,10 @@ public class SetLoadCmd extends SetDoubleCmd { - private final static String COMMAND = "setLoad"; private final static String PROPERTY = "load"; - public SetLoadCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); + public SetLoadCmd(String commandName, AcmeModelInstance model, String component, String value) { + super(commandName, PROPERTY, model, component, value); } public double processValue(double value) { diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java index 541ac8428..831302d25 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetOptResponseTimeCmd extends SetDoubleCmd { - private final static String COMMAND = "setOptResponseTime"; - private final static String PROPERTY = "optResponseTime"; - - public SetOptResponseTimeCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetOptResponseTimeCmd extends SetDoubleCmd { + private final static String PROPERTY = "optResponseTime"; + + public SetOptResponseTimeCmd(String commandName, AcmeModelInstance model, String component, String value) { + super(commandName, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java index 896dc6082..b2e426aad 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetOptThroughputCmd extends SetDoubleCmd { - private final static String COMMAND = "setOptThroughput"; - private final static String PROPERTY = "optThroughput"; - - public SetOptThroughputCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetOptThroughputCmd extends SetDoubleCmd { + private final static String PROPERTY = "optThroughput"; + + public SetOptThroughputCmd(String commandName, AcmeModelInstance model, String component, String value) { + super(commandName, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java index 4f838958d..2e78bfc0e 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java @@ -1,43 +1,43 @@ -/* - * The MIT License - * - * Copyright 2014 CMU Aimport org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.model.acme.AcmeModelInstance; -import org.sa.rainbow.model.acme.AcmeModelOperation; - "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.model.acme.AcmeModelOperation; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public abstract class SwimAcmeModelCommand extends AcmeModelOperation { - - public SwimAcmeModelCommand (String commandName, AcmeModelInstance model, String target, - String... parameters) { - super (commandName, model, target, parameters); - } - - - @Override - protected boolean checkModelValidForCommand (IAcmeSystem model) { - return model.declaresType ("SwimFam"); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU Aimport org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.AcmeModelOperation; + "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelOperation; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public abstract class SwimAcmeModelCommand extends AcmeModelOperation { + + public SwimAcmeModelCommand (String commandName, AcmeModelInstance model, String target, + String... parameters) { + super (commandName, model, target, parameters); + } + + + @Override + protected boolean checkModelValidForCommand (IAcmeSystem model) { + return model.declaresType ("SwimFam"); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java index b4d118920..b9634435a 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java @@ -1,19 +1,19 @@ -package org.sa.rainbow.model.acme.swim.commands; - -import java.util.Collections; -import java.util.List; - -/** - * Created by schmerl on 2/4/2016. - */ -public class SwimConstants { - public static final String SERVER_T_NAME = "ServerT"; - public static final String PROXY_CONN_T_NAME = "ProxyConnT"; - public static final String PROXY_FORWARD_PORT_T_NAME = "ProxyForwardPortT"; - public static final String HTTP_PORT_T_NAME = "HttpPortT"; - - static final List SERVER_TYPE = Collections.singletonList (SERVER_T_NAME); - static final List HTTP_CONN_T = Collections.singletonList (PROXY_CONN_T_NAME); - static final List PROXY_FORWARD_PORT = Collections.singletonList (PROXY_FORWARD_PORT_T_NAME); - static final List HTTP_PORT = Collections.singletonList (HTTP_PORT_T_NAME); -} +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.Collections; +import java.util.List; + +/** + * Created by schmerl on 2/4/2016. + */ +public class SwimConstants { + public static final String SERVER_T_NAME = "ServerT"; + public static final String PROXY_CONN_T_NAME = "ProxyConnT"; + public static final String PROXY_FORWARD_PORT_T_NAME = "ProxyForwardPortT"; + public static final String HTTP_PORT_T_NAME = "HttpPortT"; + + static final List SERVER_TYPE = Collections.singletonList (SERVER_T_NAME); + static final List HTTP_CONN_T = Collections.singletonList (PROXY_CONN_T_NAME); + static final List PROXY_FORWARD_PORT = Collections.singletonList (PROXY_FORWARD_PORT_T_NAME); + static final List HTTP_PORT = Collections.singletonList (HTTP_PORT_T_NAME); +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java index 0706576f6..7c245ff75 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java @@ -1,92 +1,92 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created November 1, 2006. - */ -package org.sa.rainbow.translator.swim.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Gauge for marking servers as active or not - * - * @author gmoreno - */ -public class ServerActiveGauge extends RegularPatternGauge { - - public static final String NAME = "G - ServerActive"; - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "activateServer" - }; - private static final String DEFAULT = "DEFAULT"; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public ServerActiveGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern (DEFAULT, Pattern.compile (".*")); - } - - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - int numServers = Integer.parseInt(m.group(0)); - int thisServer = (int) m_configParams.get("serverNum").getValue(); - - boolean serverActive = numServers >= thisServer; - - m_reportingPort.trace (getComponentType (), "Updating server active condition to " + serverActive); - if (m_commands.containsKey (valueNames[0])) { - IRainbowOperation cmd = getCommand (valueNames[0]); - Map parameterMap = new HashMap<> (); - parameterMap.put (cmd.getParameters ()[0], (serverActive) ? "true" : "false"); - issueCommand (cmd, parameterMap); - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.swim.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Gauge for marking servers as active or not + * + * @author gmoreno + */ +public class ServerActiveGauge extends RegularPatternGauge { + + public static final String NAME = "G - ServerActive"; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "activateServer" + }; + private static final String DEFAULT = "DEFAULT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public ServerActiveGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile (".*")); + } + + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + int numServers = Integer.parseInt(m.group(0)); + int thisServer = (int) m_configParams.get("serverNum").getValue(); + + boolean serverActive = numServers >= thisServer; + + m_reportingPort.trace (getComponentType (), "Updating server active condition to " + serverActive); + if (m_commands.containsKey (valueNames[0])) { + IRainbowOperation cmd = getCommand (valueNames[0]); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], (serverActive) ? "true" : "false"); + issueCommand (cmd, parameterMap); + } + } + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java index 83f165470..046629644 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java @@ -1,91 +1,91 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created November 1, 2006. - */ -package org.sa.rainbow.translator.swim.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Gauge for marking servers as enabled or not - * - * @author gmoreno - */ -public class ServerEnabledGauge extends RegularPatternGauge { - - public static final String NAME = "G - ServerEnabled"; - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "serverEnabled" - }; - private static final String DEFAULT = "DEFAULT"; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public ServerEnabledGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern (DEFAULT, Pattern.compile (".*")); - } - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - int numServers = Integer.parseInt(m.group(0)); - int thisServer = (int) m_configParams.get("serverNum").getValue(); - - boolean serverEnabled = numServers >= thisServer; - - m_reportingPort.trace (getComponentType (), "Updating server enablement to " + serverEnabled); - if (m_commands.containsKey (valueNames[0])) { - IRainbowOperation cmd = getCommand (valueNames[0]); - Map parameterMap = new HashMap<> (); - parameterMap.put (cmd.getParameters ()[0], (serverEnabled) ? "true" : "false"); - issueCommand (cmd, parameterMap); - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.swim.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Gauge for marking servers as enabled or not + * + * @author gmoreno + */ +public class ServerEnabledGauge extends RegularPatternGauge { + + public static final String NAME = "G - ServerEnabled"; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "serverEnabled" + }; + private static final String DEFAULT = "DEFAULT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public ServerEnabledGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile (".*")); + } + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + int numServers = Integer.parseInt(m.group(0)); + int thisServer = (int) m_configParams.get("serverNum").getValue(); + + boolean serverEnabled = numServers >= thisServer; + + m_reportingPort.trace (getComponentType (), "Updating server enablement to " + serverEnabled); + if (m_commands.containsKey (valueNames[0])) { + IRainbowOperation cmd = getCommand (valueNames[0]); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], (serverEnabled) ? "true" : "false"); + issueCommand (cmd, parameterMap); + } + } + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java b/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java index 11d6ba6d4..284439232 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java +++ b/deployments/rainbow-example/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java @@ -1,84 +1,84 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created November 1, 2006. - */ -package org.sa.rainbow.translator.swim.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Simple gauge: complete probe output passed as arg to command - * - * @author gmoreno - */ -public class SimpleGauge extends RegularPatternGauge { - - public static final String NAME = "G - SimpleGauge"; - - private static final String DEFAULT = "DEFAULT"; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public SimpleGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern (DEFAULT, Pattern.compile (".*")); - } - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - String value = m.group(0); - String commandName = m_commands.keySet().iterator().next(); - m_reportingPort.trace (getComponentType (), - "Updating component prop using command " - + commandName + " and value = " + value); - IRainbowOperation cmd = getCommand (commandName); - Map parameterMap = new HashMap<> (); - parameterMap.put (cmd.getParameters ()[0], value); - issueCommand (cmd, parameterMap); - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.swim.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Simple gauge: complete probe output passed as arg to command + * + * @author gmoreno + */ +public class SimpleGauge extends RegularPatternGauge { + + public static final String NAME = "G - SimpleGauge"; + + private static final String DEFAULT = "DEFAULT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public SimpleGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile (".*")); + } + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + String value = m.group(0); + String commandName = m_commands.keySet().iterator().next(); + m_reportingPort.trace (getComponentType (), + "Updating component prop using command " + + commandName + " and value = " + value); + IRainbowOperation cmd = getCommand (commandName); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], value); + issueCommand (cmd, parameterMap); + } + } + +} diff --git a/deployments/rainbow-example/src/main/resources/.gitignore b/deployments/rainbow-example/src/main/resources/.gitignore new file mode 100644 index 000000000..9e0adcc10 --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/.gitignore @@ -0,0 +1 @@ +/generated/ diff --git a/deployments/rainbow-example/src/main/resources/rbw/SwimModelFactory.rbw b/deployments/rainbow-example/src/main/resources/rbw/SwimModelFactory.rbw new file mode 100644 index 000000000..d7b81ac8a --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/rbw/SwimModelFactory.rbw @@ -0,0 +1,24 @@ +import acme "acme/swim.acme" + +model factory SWIM yields org.sa.rainbow.^model.^acme.swim.commands.SwimCommandFactory { + extends org.sa.rainbow.^model.^acme.AcmeModelCommandFactory + for org.sa.rainbow.^model.^acme.AcmeModelInstance + + command load is org.sa.rainbow.^model.^acme.swim.commands.SwimLoadModelCommand + command setDimmer(SwimFam.LoadBalancerT target, int dimmer) is org.sa.rainbow.^model.^acme.swim.commands.SetDimmerCmd; + command setLoad(SwimFam.ServerT target, double value) is org.sa.rainbow.^model.^acme.swim.^commands.SetLoadCmd; + command setArrivalRate(SwimFam.LoadBalancerT target, double value) is org.sa.rainbow.^model.^acme.swim.^commands.SetArrivalRateCmd; + command setBasicResponseTime(SwimFam.LoadBalancerT target, double value) is org.sa.rainbow.^model.^acme.swim.^commands.SetBasicResponseTimeCmd; + command setBasicThroughput(SwimFam.LoadBalancerT target, double value) is org.sa.rainbow.^model.^acme.swim.^commands.SetBasicThroughputCmd; + command setOptResponseTime(SwimFam.LoadBalancerT target, double value) is org.sa.rainbow.^model.^acme.swim.^commands.SetOptResponseTimeCmd; + command setOptThroughput(SwimFam.LoadBalancerT target, double value) is org.sa.rainbow.^model.^acme.swim.^commands.SetOptThroughputCmd + command enableServer(SwimFam.ServerT target, boolean enabled) is org.sa.rainbow.^model.^acme.swim.^commands.ActivateServerCmd; + command activateServer(SwimFam.ServerT target, boolean activated) is org.sa.rainbow.^model.^acme.swim.^commands.ActivateServerCmd; + command addServer(SwimFam.LoadBalancerT target, SwimFam.ServerT server) is org.sa.rainbow.^model.^acme.swim.^commands.AddServerCmd; + command removeServer(SwimFam.LoadBalancerT target, SwimFam.ServerT server) is org.sa.rainbow.^model.^acme.swim.^commands.RemoveServerCmd; + + + + +} + diff --git a/deployments/rainbow-example/src/main/resources/rbw/acme/swim.acme b/deployments/rainbow-example/src/main/resources/rbw/acme/swim.acme new file mode 100644 index 000000000..eb8eeadf9 --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/rbw/acme/swim.acme @@ -0,0 +1,189 @@ +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + Port Type PartPortT = { + + } + Port Type NetworkPortT = { + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Port Type ContainmentPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Role Type NetworkRoleT = { + + } + Role Type PartRoleT = { + + } + Role Type ContainerRoleT = { + + } + Connector Type MappingT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } +} + +Family SwimFam extends EnvType with { + + analysis Average(s : set{float}):float = + sum(s) / size(s); + + Port Type HttpPortT extends ArchPortT with { + + } + Port Type ProxyForwardPortT extends ArchPortT with { + + } + Port Type HttpReqPortT extends ArchPortT with { + + } + Component Type LoadBalancerT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property dimmer : float << default : float = 1.0; >> ; + + Property arrivalRate : float << default : float = 0.0; >> ; + + Property basicResponseTime : float << default : float = 0.0; >> ; + Property optResponseTime : float << default : float = 0.0; >> ; + Property basicThroughput : float << default : float = 0.0; >> ; + Property optThroughput : float << default : float = 0.0; >> ; + Property basicServiceTime : float << default : float = 0.0; >> ; + Property optServiceTime : float << default : float = 0.0; >> ; + } + Component Type ServerT extends ArchElementT with { + Port http0 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + Property index : int; + + Property isActive : boolean << default : boolean = true; >> ; + + Property expectedActivationTime : int << default : int = 0; >> ; + + Property reqServiceRate : float << default : float = 0.0; >> ; + + Property byteServiceRate : float << default : float = 0.0; >> ; + + Property cost : float << default : float = 1.0; >> ; + + } + Role Type ReceiverRoleT extends ArchRoleT with { + + } + Role Type RequestorRoleT extends ArchRoleT with { + + } + Connector Type ProxyConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + + + Property DIMMER_LEVELS : int << default : int = 5; >>; + Property DIMMER_MARGIN : float << default : float = 0.1; >>; + Property ADD_SERVER_LATENCY_SEC : int; + Property THREADS_PER_SERVER : int << default : int = 100; >>; + Property MAX_ARRIVAL_CAPACITY : float; + Property RT_THRESHOLD : float; +} + +System SwimSys : SwimFam = new SwimFam extended with { + + Component server1 : ServerT = new ServerT extended with { + Property deploymentLocation = "${customize.system.target.web0}"; + Property index = 1; + } + Component server2 : ServerT = new ServerT extended with { + Property deploymentLocation = "${customize.system.target.web1}"; + Property index = 2; + } + Component server3 : ServerT = new ServerT extended with { + Property deploymentLocation = "${customize.system.target.web2}"; + Property index = 3; + Property isArchEnabled = true; + } + + Component LB0 : LoadBalancerT = new LoadBalancerT extended with { + Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT; + Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT; + Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT; + + Property deploymentLocation = "${customize.system.target.lb}"; + + Property isArchEnabled = true; + } + Connector proxyConn_1_0 : ProxyConnT = new ProxyConnT; + Connector proxyConn_2_0 : ProxyConnT = new ProxyConnT; + Connector proxyConn_3_0 : ProxyConnT = new ProxyConnT; + + Attachment server1.http0 to proxyConn_1_0.rec; + Attachment server2.http0 to proxyConn_2_0.rec; + Attachment server3.http0 to proxyConn_3_0.rec; + Attachment LB0.fwd1 to proxyConn_1_0.req; + Attachment LB0.fwd2 to proxyConn_2_0.req; + Attachment LB0.fwd3 to proxyConn_3_0.req; + + Property DIMMER_LEVELS = 5; + Property MAX_ARRIVAL_CAPACITY = 22.458; + Property RT_THRESHOLD = 0.75; + Property ADD_SERVER_LATENCY_SEC = 120; + + rule GoodResponseTime = invariant LB0.basicResponseTime <= RT_THRESHOLD and LB0.optResponseTime <= RT_THRESHOLD; + rule NoOverloadedServer = invariant ! exists s :! ServerT in self.components | (s.isArchEnabled and s.load > 1); + rule SystemUtilized = invariant size(/self/components:!ServerT[isArchEnabled==true]) == 1 or !seqAverage(/self/components:!ServerT[isArchEnabled==true]/...load) < 0.3; +} + diff --git a/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/model/gauges.rbw b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/model/gauges.rbw new file mode 100644 index 000000000..6bbce55d9 --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/model/gauges.rbw @@ -0,0 +1,238 @@ +target rainbow-example +import properties "../properties.rbw" +import configuration "../system/probes.rbw" +import factory "../../SwimModelFactory.rbw" + +def int.pattern = "[0-9]+" +def double.pattern = "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?" + +gauge type LoadGaugeT = { + model factory ««SWIM»» + command ^load = "(?«double.pattern»)" -> ServerT.setLoad(double) + setup = { + targetIP = "localhost" + beaconPeriod = 20000 + generatedClass = "org.sa.rainbow.translator.swim.gauges.LoadGauge" + } + config = { + samplingFrequency = 5000 + targetProbe = ««GenericProbeT»» + } + comment = "LoadGaugeT measures and reports CPU load for the target host" +} + +gauge type DimmerGaugeT = { + model factory ««SWIM»» + command dimmer = "(?«double.pattern»)" -> LoadBalancerT.setDimmer(int) + setup = { + targetIP = "localhost" + beaconPeriod = 30000 + generatedClass = "org.sa.rainbow.translator.swim.gauges.DimmerGauge" + } + config = { + samplingFrequency = 1500 + } + comment = "DimmerGaugeT measures and reports the dimmer value of the system" +} + +gauge type ServerEnablementGaugeT = { + model factory ««SWIM»» + command serverEnabled = ServerT.enableServer(boolean) + setup = { + targetIP = "localhost" + beaconPeriod = 30000 + javaClass = org.sa.rainbow.translator.swim.gauges.ServerEnabledGauge + } + config = { + samplingFrequency = 10000 + serverNum = java.lang.Integer + } +} + +gauge type ServerActivationGaugeT = { + model factory ««SWIM»» + command activateServer = ServerT.activateServer(boolean) + setup = { + targetIP = "localhost" + beaconPeriod = 30000 + javaClass = org.sa.rainbow.translator.swim.gauges.ServerActiveGauge + } + config = { + samplingFrequency = 10000 + serverNum = java.lang.Integer + } + comment = "ServerActivationGaugeT reports if a server is active or not. serverNum is the server number (e.g., 1, 2 3), so that if there are N active servers, this server is active if N >= serverNum" +} + +gauge type BasicResponseTimeT = { + model factory ««SWIM»» + command basicResponseTime = "(?«double.pattern»)" -> LoadBalancerT.setBasicResponseTime(double) + setup = { + targetIP = "localhost" + beaconPeriod = 30000 + generatedClass = "org.sa.rainbow.translator.swim.gauges.BasicResponseTimeGauge" + } + config = { + samplingFrequency = 10000 + } +} + +gauge type OptResponseTimeT = { + model factory ««SWIM»» + command optResponseTime = "(?«double.pattern»)" -> LoadBalancerT.setOptResponseTime(double) + setup = { + targetIP = "localhost" + beaconPeriod = 30000 + generatedClass = "org.sa.rainbow.translator.swim.gauges.OptResponseTimeGauge" + } + config = { + samplingFrequency = 10000 + } +} + +gauge DimmerG0 -> DimmerGaugeT = { + model ««SwimSys»» + command dimmer = LB0.setDimmer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««DimmerProbe»» + } + comment = "DimmerG0 is associated with the component LB0 of the System, SwimSys, defined as an Acme model" +} + +gauge ServerEnabledG1 -> ServerEnablementGaugeT = { + model ««SwimSys»» + command serverEnabled = server1.enableServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««ServersProbe»» + serverNum = 1 + } +} + +gauge ServerEnabledG2 -> ServerEnablementGaugeT = { + model ««SwimSys»» + command serverEnabled = server2.enableServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««ServersProbe»» + serverNum = 2 + } +} + +gauge ServerEnabledG3 -> ServerEnablementGaugeT = { + model ««SwimSys»» + command serverEnabled = server3.enableServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««ServersProbe»» + serverNum = 3 + } +} + +gauge ServerActiveG1 -> ServerActivationGaugeT = { + model ««SwimSys»» + command activateServer = server1.activateServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««ActivateServersProbe»» + serverNum = 1 + } +} + +gauge ServerActiveG2 -> ServerActivationGaugeT = { + model ««SwimSys»» + command activateServer = server2.activateServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««ActivateServersProbe»» + serverNum = 2 + } +} + +gauge ServerActiveG3 -> ServerActivationGaugeT = { + model ««SwimSys»» + command activateServer = server3.activateServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««ActivateServersProbe»» + serverNum = 3 + } +} + +gauge BasicResponseTimeG0 -> BasicResponseTimeT = { + model ««SwimSys»» + command basicResponseTime = LB0.setBasicResponseTime($) + setup = { + targetIP = ««customize.system.^target.lb»» + beaconPeriod = 30000 + javaClass = org.sa.rainbow.translator.swim.gauges.SimpleGauge + } + config = { + targetProbe = ««BasicResponseTimeProbe»» + samplingFrequency = 15000 + } +} + +gauge OptResponseTimeG0 -> OptResponseTimeT = { + model ««SwimSys»» + command optResponseTime = LB0.setOptResponseTime($) + setup = { + targetIP = ««customize.system.^target.lb»» + beaconPeriod = 30000 + javaClass = org.sa.rainbow.translator.swim.gauges.SimpleGauge + } + config = { + targetProbe = ««OptResponseTimeProbe»» + samplingFrequency = 15000 + } +} + +gauge LoadG1 -> LoadGaugeT= { + model SwimSys::Acme + command ^load = server1.setLoad($<^load>) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««LoadProbe1»» + } +} + +gauge LoadG2 -> LoadGaugeT= { + model SwimSys::Acme + command ^load = server2.setLoad($<^load>) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««LoadProbe2»» + } +} + +gauge LoadG3 -> LoadGaugeT= { + model SwimSys::Acme + command ^load = server3.setLoad($<^load>) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««LoadProbe3»» + } +} + +export * to "model/gauges.yml" \ No newline at end of file diff --git a/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/model/swim.acme b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/model/swim.acme new file mode 100644 index 000000000..eb8eeadf9 --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/model/swim.acme @@ -0,0 +1,189 @@ +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + Port Type PartPortT = { + + } + Port Type NetworkPortT = { + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Port Type ContainmentPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Role Type NetworkRoleT = { + + } + Role Type PartRoleT = { + + } + Role Type ContainerRoleT = { + + } + Connector Type MappingT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } +} + +Family SwimFam extends EnvType with { + + analysis Average(s : set{float}):float = + sum(s) / size(s); + + Port Type HttpPortT extends ArchPortT with { + + } + Port Type ProxyForwardPortT extends ArchPortT with { + + } + Port Type HttpReqPortT extends ArchPortT with { + + } + Component Type LoadBalancerT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property dimmer : float << default : float = 1.0; >> ; + + Property arrivalRate : float << default : float = 0.0; >> ; + + Property basicResponseTime : float << default : float = 0.0; >> ; + Property optResponseTime : float << default : float = 0.0; >> ; + Property basicThroughput : float << default : float = 0.0; >> ; + Property optThroughput : float << default : float = 0.0; >> ; + Property basicServiceTime : float << default : float = 0.0; >> ; + Property optServiceTime : float << default : float = 0.0; >> ; + } + Component Type ServerT extends ArchElementT with { + Port http0 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + Property index : int; + + Property isActive : boolean << default : boolean = true; >> ; + + Property expectedActivationTime : int << default : int = 0; >> ; + + Property reqServiceRate : float << default : float = 0.0; >> ; + + Property byteServiceRate : float << default : float = 0.0; >> ; + + Property cost : float << default : float = 1.0; >> ; + + } + Role Type ReceiverRoleT extends ArchRoleT with { + + } + Role Type RequestorRoleT extends ArchRoleT with { + + } + Connector Type ProxyConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + + + Property DIMMER_LEVELS : int << default : int = 5; >>; + Property DIMMER_MARGIN : float << default : float = 0.1; >>; + Property ADD_SERVER_LATENCY_SEC : int; + Property THREADS_PER_SERVER : int << default : int = 100; >>; + Property MAX_ARRIVAL_CAPACITY : float; + Property RT_THRESHOLD : float; +} + +System SwimSys : SwimFam = new SwimFam extended with { + + Component server1 : ServerT = new ServerT extended with { + Property deploymentLocation = "${customize.system.target.web0}"; + Property index = 1; + } + Component server2 : ServerT = new ServerT extended with { + Property deploymentLocation = "${customize.system.target.web1}"; + Property index = 2; + } + Component server3 : ServerT = new ServerT extended with { + Property deploymentLocation = "${customize.system.target.web2}"; + Property index = 3; + Property isArchEnabled = true; + } + + Component LB0 : LoadBalancerT = new LoadBalancerT extended with { + Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT; + Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT; + Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT; + + Property deploymentLocation = "${customize.system.target.lb}"; + + Property isArchEnabled = true; + } + Connector proxyConn_1_0 : ProxyConnT = new ProxyConnT; + Connector proxyConn_2_0 : ProxyConnT = new ProxyConnT; + Connector proxyConn_3_0 : ProxyConnT = new ProxyConnT; + + Attachment server1.http0 to proxyConn_1_0.rec; + Attachment server2.http0 to proxyConn_2_0.rec; + Attachment server3.http0 to proxyConn_3_0.rec; + Attachment LB0.fwd1 to proxyConn_1_0.req; + Attachment LB0.fwd2 to proxyConn_2_0.req; + Attachment LB0.fwd3 to proxyConn_3_0.req; + + Property DIMMER_LEVELS = 5; + Property MAX_ARRIVAL_CAPACITY = 22.458; + Property RT_THRESHOLD = 0.75; + Property ADD_SERVER_LATENCY_SEC = 120; + + rule GoodResponseTime = invariant LB0.basicResponseTime <= RT_THRESHOLD and LB0.optResponseTime <= RT_THRESHOLD; + rule NoOverloadedServer = invariant ! exists s :! ServerT in self.components | (s.isArchEnabled and s.load > 1); + rule SystemUtilized = invariant size(/self/components:!ServerT[isArchEnabled==true]) == 1 or !seqAverage(/self/components:!ServerT[isArchEnabled==true]/...load) < 0.3; +} + diff --git a/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/properties.rbw b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/properties.rbw new file mode 100644 index 000000000..29ae2e2db --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/properties.rbw @@ -0,0 +1,198 @@ +target rainbow-example +import properties "model/gauges.rbw" +import acme "model/swim.acme" +import factory "../SwimModelFactory.rbw" +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. +def rainbow.path # Default property defined by rainbow + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +def logging.level = DEBUG +def event.log.path = "log" +def logging.path = "«event.log.path»/rainbow.out" +def monitoring.log.path = "«event.log.path»/rainbow-data.log" + + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +def rainbow.master.location.host = "rainbow-example" +#- Location information of the deployed delegate +def rainbow.deployment.location = "rainbow-example" +#- default registry port; change if port-tunneling +def rainbow.master.location.^port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +def rainbow.deployment.environment = "linux" + +def rainbow.delegate.beaconperiod = 10000 +def rainbow.deployment.^factory.class = org.sa.rainbow.core.ports.guava.GuavaRainbowPortFactory + +### Rainbow models + +# Rainbow Acme model of SWIM +def model SwimSys= { + ^type="Acme" + path="model/swim.acme" + ^factory=««SWIM»» + saveOnClose = true + saveLocation="model/swim-post.acme" +} + +# Rainbow Utility Model +def model USwimSys = { + name="SwimSys" + //^type="Utility" + path="stitch/utilities.yml" + ^factory=org.sa.rainbow.^model.^utility.UtilityCommandFactory +} + +### Rainbow analyses +def analysis ArchEvaluator = { + class = org.sa.rainbow.evaluator.^acme.ArchEvaluator +} + + +def adaptation-manager AdaptationManager = { + ^model=««SwimSys»» + class=org.sa.rainbow.^stitch.adaptation.AdaptationManager +} + +def executor StitchExecutor = { + ^model=««SwimSys»» + class=org.sa.rainbow.^stitch.adaptation.StitchExecutor +} + +def effector-manager AcmeEffectorManager = { + class = org.sa.rainbow.effectors.^acme.AcmeEffectorManager +} + +def gui rainbow.^gui = { + class = org.sa.rainbow.^gui.RainbowWindoe + specs = { + gauges = { + ^gauge = { + ^type = ««LoadGaugeT»» + ^command = "load" + value.parameter = 1 + upper = 1.0 + lower = 0.0 + category = "meter" + + } + ^gauge = { + ^type = ««DimmerGaugeT»» + ^command = "dimmer" + value.parameter = 1 + upper = 1.0 + lower = 0.0 + category = "meter" + } + ^gauge = { + ^type = ««BasicResponseTimeT»» + category = "timeseries" + ^command = "basicResponseTime" + upper = 10.0 + lower = 0.0 + value.parameter = 1 + } + ^gauge = { + ^type = ««OptResponseTimeT»» + ^command = "optResponseTime" + category = "timeseries" + upper = 10.0 + lower = 0.0 + value.parameter = 1 + } + ^gauge = { + ^type =««ServerEnablementGaugeT»» + ^command = "serverEnabled" + category = "onoff" + value.parameter = 1 + } + ^gauge = { + ^type = ««ServerActivationGaugeT»» + ^command = "activateServer" + category = "onoff" + value.parameter = 1 + } + } + analyzers = { + analyzer = { + ^for = ««ArchEvaluator»» + class = org.sa.rainbow.evaluator.^acme.^gui.ArchAnalyzerGUI + } + } + managers = { + manager = { + ^for = ««AdaptationManager»» + class = org.sa.rainbow.^stitch.^gui.manager.ArchStitchAdapationManager + } + } + executors = { + ^executor = { + ^for = ««StitchExecutor»» + class = org.sa.rainbow.^stitch.^gui.^executor.EventBasedStitchExecutorPanel + } + } + details = { + managers = org.sa.rainbow.^stitch.^gui.manager.StitchAdaptationManagerTabbedPane + executors = org.sa.rainbow.^stitch.^gui.^executor.StitchExecutorTabbedPane + } + } +} + + +def customize.^model.evaluate.period = 60000 +def customize.^model.timeseriespredictor.args="LES 0.8 0.15" +def customize.^model.timeseriespredictor.traininglength=15 + +## Translator customization +#- Gauge spec +def customize.gauges.path = "model/gauges.yml" +#- Probe spec +def customize.probes.path = "system/probes.yml" +#- Effector spec +def customize.effectors.path = "system/effectors.yml" +## Adaptation Manager +#- Directory of Stitch adaptation script +def customize.scripts.path = "stitch" +#- Utilities description file, Strategy evaluation config, and minimum score threshold +def customize.^utility.path = "stitch/utilities.yml" +def customize.^utility.trackStrategy = "uC" +def customize.^utility.score.minimum.threshold = 0.033 +def customize.^utility.scenario = "scenario 1" +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#def customize.prediction.enable = false + +## System configuration information +# These properties may be referred to in various files +# in the target (e.g., Acme, gauges, effectors, probes) +# and are replaced by Rainbow with the actual values. +# They may define deployment information (e.g., in terms of IPs and ports) +# among other things +def customize.system.^target.master = ««rainbow.deployment.location»» +def customize.system.^target.lb = ««rainbow.deployment.location»» +def customize.system.^target.lb.httpPort = 1081 +def customize.system.^target.web0 = 1 +def customize.system.^target.web0.httpPort = 1080 +def customize.system.^target.web1 = 2 +def customize.system.^target.web1.httpPort = 1080 +def customize.system.^target.web2 = 3 +def customize.system.^target.web2.httpPort=1080 + +export * to "rainbow-gui.properties" diff --git a/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/stitch/swimStrategies.s b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/stitch/swimStrategies.s new file mode 100644 index 000000000..d8ac198ef --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/stitch/swimStrategies.s @@ -0,0 +1,59 @@ +module swim.strategies; +import op "org.sa.rainbow.stitch.lib.*"; +import lib "swimTactics.t.s"; +import model "SwimSys:Acme" { SwimSys as M, SwimFam as T}; + + +define boolean HighRT =(M.LB0.basicResponseTime >= M.RT_THRESHOLD) || (M.LB0.optResponseTime >= M.RT_THRESHOLD); +define boolean Underloaded = M.seqAverage(/M.components:!T.ServerT[isArchEnabled==true]/...load) < 0.3; +define boolean ExtraServers = M.size(/M.components:!T.ServerT[isArchEnabled==false])>=1; +define boolean MoreThanOneActiveServer = M.size(/M.components:!T.ServerT[isArchEnabled==true])>1; +define boolean DimmerDecreasable = SwimUtils.dimmerFactorToLevel(M.LB0.dimmer, M.DIMMER_LEVELS,M.DIMMER_MARGIN) > 1; + + + +strategy LowerResponseTime1 [HighRT] { + t1: (HighRT && ExtraServers) -> TAddServer() @[30000] { + t1a: (HighRT) -> TDecDimmer() { + t1a1: (default) -> done; + } + t1b: (default) -> done; + } +} + +strategy LowerResponseTime2 [HighRT] { + t1: (HighRT && ExtraServers) -> TAddServer() @[30000] { + t1b: (HighRT) -> TAddServer() @[30000] { + t1b1: (default) -> done; + } + t1c: (HighRT) -> TDecDimmer() @[30000] { + t1c1: (default) -> done; + } + } +} + +strategy DecreaseCost [Underloaded && (MoreThanOneActiveServer || DimmerDecreasable)] { + t0: (Underloaded) -> TRemoveServer() @[10000]{ + t0a: (!Underloaded) -> done; + t0b: (Underloaded && MoreThanOneActiveServer) -> TRemoveServer() { + t0ba: (success) -> done; + } + t0c: (Underloaded && DimmerDecreasable) -> TIncDimmer() { + t0ca: (success) -> done; + } + } + t1: (Underloaded) -> TRemoveServer() @[10000]{ + t1a: (Underloaded) -> TIncDimmer() { + t1a1: (default) -> done; + } + t1b: (default) -> done; + } + t2: (Underloaded) -> TIncDimmer() { + t2a: (Underloaded) -> TRemoveServer() @[10000] { + t2a1: (default) -> done; + } + t2b: (default) -> done; + } +} + + diff --git a/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/stitch/swimTactics.t.s b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/stitch/swimTactics.t.s new file mode 100644 index 000000000..010edcc1d --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/stitch/swimTactics.t.s @@ -0,0 +1,72 @@ +module swim.tactics; + +import model "SwimSys:Acme" { SwimSys as M, SwimFam as T}; +import op "org.sa.rainbow.stitch.lib.SwimUtils"; +import op "org.sa.rainbow.model.acme.swim.Swim"; + +define int numberOfServers = Set.size(select s : T.ServerT in M.components | true); + +tactic TIncDimmer() { + int dimmerLevel = SwimUtils.dimmerFactorToLevel(M.LB0.dimmer, M.DIMMER_LEVELS,M.DIMMER_MARGIN); + condition { + + dimmerLevel < M.DIMMER_LEVELS; + } + action { + M.setDimmer(M.LB0, SwimUtils.dimmerLevelToFactor(SwimUtils.dimmerFactorToLevel(M.LB0.dimmer, M.DIMMER_LEVELS, M.DIMMER_MARGIN) + 1, M.DIMMER_LEVELS, M.DIMMER_MARGIN)); + } + effect @[16000] { + dimmerLevel' > dimmerLevel; + } +} + +tactic TDecDimmer() { + int dimmerLevel = SwimUtils.dimmerFactorToLevel(M.LB0.dimmer, M.DIMMER_LEVELS, M.DIMMER_MARGIN); + condition { + dimmerLevel > 1; + } + action { + M.setDimmer(M.LB0, SwimUtils.dimmerLevelToFactor(SwimUtils.dimmerFactorToLevel(M.LB0.dimmer, M.DIMMER_LEVELS, M.DIMMER_MARGIN) - 1, M.DIMMER_LEVELS, M.DIMMER_MARGIN)); + } + effect @[16000]{ + dimmerLevel' < dimmerLevel; + } +} + +tactic TAddServer() { + int unusedServers = Swim.availableServices(M, T.ServerT); + condition { + Swim.availableServices(M, T.ServerT) > 0; + } + action { + // add first server not enabled + // note that the associated effector adds the next server in the + // secuence, regardless of the one selected here + set servers = Swim.findServices(M, T.ServerT); + object newServer = SwimUtils.minOverProperty("index", servers); + M.addServer(M.LB0, newServer); + } + effect @[30000] { + unusedServers' == unusedServers - 1; + } +} + +tactic TRemoveServer() { + int availableServers = M.size(/M.components:!T.ServerT[isArchEnabled]); + + condition { + availableServers > 1; + } + action { + // remove the server with the highest index + // note that the associated effector removes the server with the highest index + // regardless of the one selected here + set servers = select s : T.ServerT in M.components | true; + object lastServer = SwimUtils.maxOverProperty("index", servers); + M.removeServer(M.LB0, lastServer); + } + effect @[30000] { + availableServers' == availableServers - 1; + } +} + diff --git a/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/stitch/utilities.rbw b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/stitch/utilities.rbw new file mode 100644 index 000000000..20ce68af1 --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/stitch/utilities.rbw @@ -0,0 +1,78 @@ +target rainbow-example +import properties "../properties.rbw" +import stitch "swimTactics.t.s" +def utility utilityModel = { + ^model = ««SwimSys»» + utilities = { + uR = { + label="Average Response Time" + mapping="[EXPR]LB0.optResponseTime" + description="Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" + ^utility=[ + [0.0,1], + [0.1,1], + [0.2,0.99], + [0.5,0.9], + [1.0,0.75], + [1.5,0.5], + [2.0,0.25], + [4.0,0] + ] + } + uC = { + label= "Average Server Cost" + mapping= "[EXPR]size(/self/components:ServerT[isArchEnabled])" + description= "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers. Adapted to a 3-server configuration." + ^utility=[ + [0, 1.00], + [1, 0.90], + [2, 0.30], + [3, 0.10] + ] + + } + uA = { + label= "Average User Annoyance" + mapping= "[CALL]org.sa.rainbow.stitch.lib.SwimUtils.dimmerFactorToLevel(LB0.dimmer,DIMMER_LEVELS,DIMMER_MARGIN)" + description= "Client experienced annoyance level, should be defined as an int property 'ClientT.annoyance' in the architecture, with a range 0-100" + ^utility = [ + [0, 0], + [5, 1] + ] + } + } + scenarios = [{ + name="scenario 1" + uR=0.1 + uC=0.2 + uA=0.7 + } + ] +} + + +impact ««utilityModel»» TAddServer = { + uR = -1.00 + uC = 1.00 + uA = 0 +} + +impact ««utilityModel»» TRemoveServer = { + uR= 1 + uC= -1 + uA= 0 +} + +impact ««utilityModel»» TIncDimmer = { + uR= -0.5 + uC= -0.1 + uA= 5 +} + +impact ««utilityModel»» TDecDimmer = { + uR= 5 + uC= 0.1 + uA= -5 +} + +export * to "stitch/utilities.yml" \ No newline at end of file diff --git a/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/system/effectors.rbw b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/system/effectors.rbw new file mode 100644 index 000000000..228d35f2f --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/system/effectors.rbw @@ -0,0 +1,35 @@ +target rainbow-example +import properties "../properties.rbw" +def effectors.commonPath = "«rainbow.path»/system/effectors" + +effector setDimmer = { + model ««SwimSys»» + command ««customize.system.^target.lb»».setDimmer($) + location = ««customize.system.^target.lb»» + script = { + path = "«effectors.commonPath»/setDimmer.sh" + argument = "{0}" + } +} + +effector addServer = { + model ««SwimSys»» + command ««customize.system.^target.lb»».addServer($) + location = ««customize.system.^target.lb»» + script = { + path = "«effectors.commonPath»/addServer.sh" + argument = "" + } +} + +effector removeServer = { + model ««SwimSys»» + command ««customize.system.^target.lb»».removeServer($) + location = ««customize.system.^target.lb»» + script = { + path = "«effectors.commonPath»/removeServer.sh" + argument = "" + } +} + +export * to "system/effectors.yml" \ No newline at end of file diff --git a/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/system/probes.rbw b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/system/probes.rbw new file mode 100644 index 000000000..da0456eb2 --- /dev/null +++ b/deployments/rainbow-example/src/main/resources/rbw/rainbow-example/system/probes.rbw @@ -0,0 +1,70 @@ +target rainbow-example // generates "system/probes.yml" +import properties "../properties.rbw" +def probes.commonPath = "«rainbow.path»/system/probes" + +probe type GenericProbeT = { + location = ««customize.system.^target.lb»» + script = { + mode = "continual" + path = "«probes.commonPath»/genericProbe.pl" + } +} + +probe DimmerProbe -> GenericProbeT = { + alias = "dimmer" + script = { + argument = "get_dimmer" + } +} + +probe ServersProbe -> GenericProbeT = { + alias = "servers" + script = { + argument = "get_servers" + } +} + +probe ActivateServersProbe -> GenericProbeT = { + alias = "activeServers" + script = { + argument="get_active_servers" + } +} + +probe LoadProbe1 -> GenericProbeT = { + alias="load1" + script = { + argument = "-d 5000 get_utilization server1" + } +} + +probe LoadProbe2 -> GenericProbeT = { + alias = "load2" + script = { + argument = "-d 5000 get_utilization server2" + } +} + +probe LoadProbe3 -> GenericProbeT = { + alias = "load3" + script = { + argument = "-d 5000 get_utilization server3" + } +} + +probe BasicResponseTimeProbe -> GenericProbeT = { + alias = "basicResponseTime" + script = { + argument = "get_basic_rt" + } +} + +probe OptResponseTimeProbe -> GenericProbeT = { + alias = "optResponseTime" + script = { + argument = "get_opt_rt" + } +} + +export * to "system/probes.yml" + diff --git a/deployments/rainbow-swim-hybrid/.classpath b/deployments/rainbow-swim-hybrid/.classpath new file mode 100644 index 000000000..78812b842 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/deployments/rainbow-swim-hybrid/.gitignore b/deployments/rainbow-swim-hybrid/.gitignore new file mode 100644 index 000000000..cf34e995c --- /dev/null +++ b/deployments/rainbow-swim-hybrid/.gitignore @@ -0,0 +1,3 @@ +*.log +*~ +target/ \ No newline at end of file diff --git a/deployments/rainbow-swim-hybrid/.project b/deployments/rainbow-swim-hybrid/.project new file mode 100644 index 000000000..5b18d86a6 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/.project @@ -0,0 +1,24 @@ + + + rainbow-swim-hybrid + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + org.eclipse.linuxtools.tmf.project.nature + + diff --git a/deployments/rainbow-swim-hybrid/.settings/org.eclipse.core.resources.prefs b/deployments/rainbow-swim-hybrid/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..ff0ac6e33 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +encoding//src/main/java=utf-8 +encoding//src/test/resources=utf-8 +encoding/=utf-8 diff --git a/deployments/rainbow-swim-hybrid/.settings/org.eclipse.jdt.core.prefs b/deployments/rainbow-swim-hybrid/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..62492222a --- /dev/null +++ b/deployments/rainbow-swim-hybrid/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/deployments/rainbow-swim-hybrid/.settings/org.eclipse.m2e.core.prefs b/deployments/rainbow-swim-hybrid/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 000000000..f897a7f1c --- /dev/null +++ b/deployments/rainbow-swim-hybrid/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/deployments/rainbow-swim-hybrid/.tracecompass/.project b/deployments/rainbow-swim-hybrid/.tracecompass/.project new file mode 100644 index 000000000..78711c1e0 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/.tracecompass/.project @@ -0,0 +1,12 @@ + + + .tracecompass-rainbow-swim + + + + + + + org.eclipse.linuxtools.tmf.project.nature + + diff --git a/deployments/rainbow-swim-hybrid/Dockerfile-swim b/deployments/rainbow-swim-hybrid/Dockerfile-swim new file mode 100644 index 000000000..4db3a9c57 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/Dockerfile-swim @@ -0,0 +1,96 @@ +FROM ubuntu:16.04 AS builder +#maven:3-jdk-8 AS builder +ARG rainbow_version=SWIM1.0 +RUN apt update && apt-get install --no-install-recommends -y software-properties-common zip unzip tar gzip libboost-all-dev libyaml-cpp-dev make automake autoconf g++ ant wget libpcre3-dev socat swig curl bash git-core + +# To ensure the right versions of the libraries in the build +# we need to FROM the same root, so that means installing Java +# and Maven manually + +#RUN \ +# echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && \ +# add-apt-repository -y ppa:webupd8team/java && \ +# apt-get update && \ +# apt-get install -y oracle-java8-installer --allow-unauthenticated && \ +# rm -rf /var/lib/apt/lists/* && \ +# rm -rf /var/cache/oracle-jdk8-installer + +RUN apt-get install -y openjdk-8-jdk + +# Install Maven +ARG MAVEN_VERSION=3.3.9 +ARG USER_HOME_DIR="/root" +RUN mkdir -p /usr/share/maven && \ +curl -fsSL http://apache.osuosl.org/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz | tar -xzC /usr/share/maven --strip-components=1 && \ +ln -s /usr/share/maven/bin/mvn /usr/bin/mvn +ENV MAVEN_HOME /usr/share/maven +ENV MAVEN_CONFIG "$USER_HOME_DIR/.m2" +# speed up Maven JVM a bit +ENV MAVEN_OPTS="-XX:+TieredCompilation -XX:TieredStopAtLevel=1" + +# Install pladapt +WORKDIR /root/ +RUN git clone https://github.com/cps-sei/pladapt.git + +WORKDIR /root/pladapt +RUN reach/build.sh + +RUN autoreconf -fvi && \ + mkdir build && \ + cd build && \ + ../configure && \ + make + +WORKDIR /root/pladapt/java +### Bug fix to get around the fact that uname returns unknown for maven:3-jdk-8 +RUN sed 's/$(shell uname -i)/x86_64/' Makefile > Makefile-bugfix && \ + make -f Makefile-bugfix mvn-install +# RUN make mvn-install +#RUN mvn install:install-file -Dfile=pladapt_wrap.jar -DgroupId=pladapt -DartifactId=pladapt_wrap -Dversion=1.0.1 -Dpackaging=jar +# Install Hogna and Opera +COPY deployments/rainbow-swim/deps . +RUN unzip hogna.zip libs/Hogna.jar libs/Opera.jar && \ + mvn install:install-file -Dfile=libs/Hogna.jar -DgroupId=opera -DartifactId=hogna -Dversion=1.0 -Dpackaging=jar && \ + mvn install:install-file -Dfile=libs/Opera.jar -DgroupId=opera -DartifactId=opera -Dversion=1.0 -Dpackaging=jar + +ADD deployments /root/rainbow/deployments +ADD libs /root/rainbow/libs +ADD ide /root/rainbow/ide +ADD rainbow /root/rainbow/rainbow +ADD targets /root/rainbow/targets +ADD license.html /root/rainbow +ADD build.sh /root/rainbow +ADD scripts /root/rainbow/scripts +WORKDIR /root/rainbow +RUN ls +RUN ./build.sh -s -d rainbow-swim -t swim i-v${rainbow_version} install +CMD [/bin/bash] + +FROM gabrielmoreno/swim:1.0 +RUN apt update && DEBIAN_FRONTEND=noninteractive apt-get -y install software-properties-common dbus dbus-x11 xorg xserver-xorg-legacy xinit xterm libboost-all-dev libyaml-cpp-dev libpcre3-dev socat + +RUN sed -i "s/allowed_users=console/allowed_users=anybody/;$ a needs_root_rights=yes" /etc/X11/Xwrapper.config + +#RUN \ +# echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && \ +# add-apt-repository -y ppa:webupd8team/java && \ +# apt-get update && \ +# apt-get install -y oracle-java8-installer --allow-unauthenticated && \ +# rm -rf /var/lib/apt/lists/* && \ +# rm -rf /var/cache/oracle-jdk8-installer +RUN apt-get install -y openjdk-8-jdk + + +ENV JAVA_HOME /usr/lib/jvm/java-8-oracle +RUN mkdir /rainbow +WORKDIR /rainbow +COPY --from=builder /root/pladapt ./pladapt +ENV PLADAPT /rainbow/pladapt +COPY --from=builder /root/rainbow/Rainbow-build . +RUN echo "export SOCAT_PORT=4242" >> /headless/.bashrc +COPY deployments/rainbow-swim/docker/rainbow.png /headless/ +COPY deployments/rainbow-swim/docker/SWIM.png /headless/ +COPY deployments/rainbow-swim/docker/Rainbow.desktop /headless/Desktop +COPY deployments/rainbow-swim/docker/SWIM.desktop /headless/Desktop +RUN chmod +x /headless/Desktop/Rainbow.desktop /headless/Desktop/SWIM.desktop +#ENTRYPOINT ["./rainbow-oracle.sh", "swim"] diff --git a/deployments/rainbow-swim-hybrid/README.md b/deployments/rainbow-swim-hybrid/README.md new file mode 100644 index 000000000..a5cd28007 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/README.md @@ -0,0 +1,109 @@ +Commands for both acme model update (rainbow side) and effector (swim) are both inside model/acme/swim/commands +model/acme/swim/SwimModelHelper.java implements a helper class that queries the acme model. Some calculations might need to be changed, such as dimmer leve, expected activation time, etc. +model/acme/swim/SwimCommandFactory.java defines how commands are constructed, server activation commands needs to be changed (for rainbow side) that directly adds to a server type. +AddServerWithTypeCmd, Dec(Inc)DimmerCmd, DivertTrafficCmd, RemoveServerWithTypeCmd are the ones used for swim effectors, the rest are for acme models. + +swim/adaptation/ folder has classes that define the hybrid planning algorithm +AdaptationManagerDummy.java is a dummy manager that only increases and decreases server every period without doing planning +HPAdaptationManager.java is the implemented planning class. Important functions include: +initializeAdaptationMgr: executed at init, can put test code here for testing that is executed once at the start +computeDecisionHorizon: the way horizon calculation might needs to be modified, which is done here +EnvironmentDTMCPartitioned: defines the parameters that generates the DTMC +get_initial_state_str: some minor details regarding initial state string +checkAdaptationImpl: the function that implements the HP algorithm, which uses the two classes Reactive and Deliberative, which can be called on separate threads. +runAction: the function that gets called each period. calls checkAdaptationImpl + +SwimExtendedPlan: defines a plan class that gets extended +The plan classes are in this folder as well + + + +# PLA Adaptation Manager for Rainbow +This adaptation manager for Rainbow has two variants of Proactive Latency-Aware (PLA) adaptation managers: PLA-SDP, PLA-SB, described in + +Gabriel A. Moreno. _Adaptation Timing in Self-Adaptive Systems_. PhD Thesis, Carnegie Mellon University (2017) [[link]](http://works.bepress.com/gabriel_moreno/30/) + +It is intended to be used with SWIM as the target system, which is described in + +Gabriel A. Moreno, Bradley Schmerl and David Garlan. "SWIM: an exemplar for evaluation and comparison of self-adaptation approaches for web applications" _Proceedings of the 13th International Conference on Software Engineering for Adaptive and Self-Managing Systems_ (2018) [[link]](http://works.bepress.com/gabriel_moreno/35/) + +SWIM is available [here](https://github.com/cps-sei/swim) + +You can use this in two ways +1. Build as described below +2. Run the demo as a Docker image, as described [here](docker/INSTRUCTIONS.md) + +## Building the Adaptation Manager for SWIM +The following instructions have been tested in Ubuntu 16.04 LTS. + +### Installing Dependencies +To install the required packages execute this command: + +``` +sudo apt update && sudo apt install --no-install-recommends maven libboost-all-dev libyaml-cpp-dev make automake autoconf g++ default-jdk ant wget libpcre3-dev socat +``` + +The main dependency for this adaptation manager is the [PLADAT library](https://github.com/cps-sei/pladapt). Follow the instructions included with the library for compiling it, and make sure to compile and install the Java wrapper. + +When using the PLA-SB variant of this adaptation manager, it is necessary to have the PRISM model checker installed and in the execution path. PRISM can be downloaded from its [website](http://www.prismmodelchecker.org/). This has been tested with PRISM version 4.3.1 and PRISM 4.4. + +Additional required third-party libraries must be installed executing this script + +``` +deployments/rainbow-swim/deps/installdeps.sh +``` + +### Building Rainbow and the PLA Adaptation Manager +Rainbow and the adaptation manager can be built with the following command: + +``` +./build.sh -s -d rainbow-swim -t swim +``` + +After running this command, Rainbow with the adaptation manager and the files necessary to use SWIM as a target system can be found in `Rainbow-build` + +## Running Rainbow with SWIM +The Rainbow adaptation manager for SWIM has a model of the target system simulated by SWIM. +This model includes some parameters that have to match the corresponding parameters in the simulation. +The values of the following properties in the model `Rainbow-build/targets/swim/model/swim.acme` have to match those in `swim/simulations/swim/swim.ini`. The following table shows the names of the corresponding properties in the two files. (*Note:* these properties already match in the default configurations) + +| swim.acme | swim.ini | +| ---------------------- | ---------------------------- | +| DIMMER\_LEVELS | \*.numberOfBrownoutLevels | +| DIMMER\_MARGIN | \*.dimmerMargin | +| THREADS\_PER\_SERVER | \*\*.server\*.server.threads | +| MAX\_ARRIVAL\_CAPACITY | \*.maxServiceRate | +| RT\_THRESHOLD | \*.responseTimeThreshold | + + +It is important to select the appropriate run number when running SWIM so that the latency to add a server matches in the adaptation manager and in SWIM. SWIM includes two traces of user requests. Each row in the following table shows the run number to be used for a particular latency for the addition of a server with each trace. + +| trace\latency | 0 | 60 | 120 | 180 | 240 | +| ------------- | --- | --- | --- | --- | --- | +| WorldCup | 0 | 1 | 2 | 3 | 4 | +| ClarkNet | 5 | 6 | 7 | 8 | 9 | + +In `Rainbow-build/targets/swim/model/swim.acme`, the latency to add a server is set in the property `ADD_SERVER_LATENCY_SEC` + +SWIM has to be run following its [instructions to run it with an another external adaptation manager](https://github.com/cps-sei/swim#how-to-run-simulation-with-another-external-adaptation-manager). For example, to run SWIM with the WorldCup trace and a latency for the addition of a server of 120 seconds, we have to execute the following command in `swim/simulations/swim`: + +``` +./run.sh sim 2 +``` +After SWIM is started, Rainbow can be started with the following commands in another terminal, assuming that Rainbow is installed in the directory specified in the environment variable `RAINBOW`. + +``` +cd $RAINBOW/Rainbow-build +./run-oracle.sh -p rainbow.properties swim +``` +Once the Rainbow graphical user interface opens, select `Delegate|Start Probes`. + +After the simulation run of SWIM finishes, Rainbow can be closed, and the results of the simulation can be plotted or processed following the instructions provided with SWIM. + +The previous command ran Rainbow with the PLA-SDP adaptation manager. It is also possible to run Rainbow with the PLA-SB adaptation manager using the following command. *Note:* this requires [PRISM](http://www.prismmodelchecker.org/) installed and its `bin` directory in the PATH environment variable. + +``` +cd $RAINBOW/Rainbow-build +./run-oracle.sh -p rainbow-sb.properties swim +``` + diff --git a/deployments/rainbow-swim-hybrid/deps/hogna.zip b/deployments/rainbow-swim-hybrid/deps/hogna.zip new file mode 100644 index 000000000..4641869dd Binary files /dev/null and b/deployments/rainbow-swim-hybrid/deps/hogna.zip differ diff --git a/deployments/rainbow-swim-hybrid/deps/installdeps.sh b/deployments/rainbow-swim-hybrid/deps/installdeps.sh new file mode 100755 index 000000000..c8a2cb60b --- /dev/null +++ b/deployments/rainbow-swim-hybrid/deps/installdeps.sh @@ -0,0 +1,18 @@ +#!/bin/sh + +CWD=`pwd` + +cd `dirname $0` +echo "Installing Hogna (see http://www.ceraslabs.com/hogna)..." +unzip hogna.zip libs/Hogna.jar libs/Opera.jar +mvn install:install-file -Dfile=libs/Hogna.jar -DgroupId=opera -DartifactId=hogna -Dversion=1.0 -Dpackaging=jar +mvn install:install-file -Dfile=libs/Opera.jar -DgroupId=opera -DartifactId=opera -Dversion=1.0 -Dpackaging=jar + +# make sure we're removing the right directory +if [ -f libs/Hogna.jar ]; then + rm -rf libs +fi + +echo "done" + +cd $CWD diff --git a/deployments/rainbow-swim-hybrid/docker/INSTRUCTIONS.md b/deployments/rainbow-swim-hybrid/docker/INSTRUCTIONS.md new file mode 100644 index 000000000..dda557661 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/docker/INSTRUCTIONS.md @@ -0,0 +1,57 @@ +# Rainbow-SWIM example + +This document provides instructions on how to build and run the docker container for a demonstration of Rainbow and SWIM. + +## SWIM - A Simulator of Web Infrastructure and Management + +SWIM is a self-adaptive exemplar that simulates a web application. SWIM can be used as a target system with an external adaptation manager interacting with it through its TCP-based interface or with an adaptation manager built as a simulation module. More details can be found on [the SWIM website](https://hub.docker.com/r/gabrielmoreno/swim). + +This demonstration uses the SWIM simulator with Rainbow as the Self-Adaptive Platform + +## Building SWIM-Rainbow + +In the root Rainbow directory (i.e., the one that contains `deployments`, `libs`, `rainbow` etc., build the docker image using the following command: + +``` +> docker build -t rainbow-swim -f deploymens/rainbow-swim/Dockerfile-swim . +``` + +This is a multi-stage docker build file that will first build a Rainbow release targeted for SWIM and (currently) using the predictive latency-aware (PLA) version of Rainbow described in [''Flexible and Efficient Decision-Making for Proactive Latency-Aware Self-Adaptation''](http://acme.able.cs.cmu.edu/pubs/show.php?id=544). + +## Running Rainbow and SWIM + +1. Run the docker container: + ``` + > docker run -it --rm -p 6901:6901 --hostname rainbow-swim rainbow-swim + ``` +2. Log into the docker container from a browser by connecting to `http://localhost:6901` (assuming you are connecting from the Docker host). You will be prompted for a password. Use `vncpassword`. After logging in, the screen should look like: + + ![Rainbow SWIM desktop](images/swim-login-screen.png) + +3. To start SWIM, double-click the SWIM logo: ![SWIM](SWIM.png). This starts the web simulation running with three initial servers responding to the Trace 1. + +4. To start Rainbow, double-click on the Rainbow logo: ![Rainbow](rainbow.png). This will bring up the Rainbow UI, which should look like: + + ![Rainbow UI](images/rainbow-ui-1.png) + + To get more details on each element (probes, models, gauges, etc.) you need to select `Rainbow>Populate Panels`: + + ![Populatae Panels](images/rainbow-ui-2.png) + + The Rainbow UI window is divided into eight separate panels. These panels are enumerated below: + + ![Rainbow Panels](images/rainbow-ui-3.png) + + 1. **Probe Panel**: This panel displays probe data from each probe in the system. Each probe has its own tab; the _All_ tab prints the log information from every probe. + 2. **Gauge Panel**: Gauges in Rainbow take system information emitted from probes, and converts them into model information in the form of operations on those models. The _All_ panel displays log information. Each other tab represents the operations that are emitted from the gauge and sent to the Models Manager. + 3. **Models Manager**: The Models Manager manages operations on the models represented in Rainbow, that are used to reason about adaptations on the system. Each tab is a separate model, organzed as a table of model operations that have been executed. + 4. **Analyzers**: Represents the elements that analyze the model and synthesize them to either detect errors or opportunities for adaptation. The log information from each analyzer is organized as a tab. (In this demo, the analyzer and adaptation manager are fused, and so Rainbow does not have any analyzer.) + 5. **Adaptation Managers**: This panel shows all the elements that make the decision about what adaptation to do. If there is only one adaptation manager (the norm), then all the information will be displayed in the _All_ tab. + 6. **Executors**: This panel has output from components that manage the execution of adaptations strategies that are chosen by an adaptation manager. + 7. **Effectors**: This panel displays output from effectors. + 8. **Rainbow Master**: This panel displays health and output about Rainbow generally. In this demo, the output is about heartbeat information from Rainbow to the manager. + +5. To start Rainbow adaptation, you must start the probes manually so that Rainbow starts receiving information. To do this, click on `Delegates>Start Probes`. You will start seeing information appearing in all tabs except the Rainbow Master and Analyzers. + +There is not much feedback from SWIM about what it is doing, but you should see probes, gauges, and the model changing. Initially, the adaptation manager will decide that there are too many servers given the current predicted load, and so will scale back by removing servers. You should see the removeServer effector firing eventually. + diff --git a/deployments/rainbow-swim-hybrid/docker/Rainbow.desktop b/deployments/rainbow-swim-hybrid/docker/Rainbow.desktop new file mode 100644 index 000000000..5243bbfbd --- /dev/null +++ b/deployments/rainbow-swim-hybrid/docker/Rainbow.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Version=1.0 +Type=Application +Name=Rainbow +Comment=Rainbow system for managing SWIM simulation +Exec=xterm -e "./run-oracle.sh -a -p rainbow-swim.properties swim | tee rainbow-console.out" +Icon=/headless/rainbow.png +Path=/rainbow +Terminal=false +StartupNotify=false diff --git a/deployments/rainbow-swim-hybrid/docker/SWIM.desktop b/deployments/rainbow-swim-hybrid/docker/SWIM.desktop new file mode 100644 index 000000000..a28d09aca --- /dev/null +++ b/deployments/rainbow-swim-hybrid/docker/SWIM.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Version=1.0 +Type=Application +Name=SWIM +Comment=The SWIM Rubis Simulator +Exec=xterm -e "./run.sh sim 1 | tee swim-console.out" +Icon=/headless/SWIM.png +Path=/headless/seams-swim/swim/simulations/swim +Terminal=false +StartupNotify=false diff --git a/deployments/rainbow-swim-hybrid/docker/SWIM.png b/deployments/rainbow-swim-hybrid/docker/SWIM.png new file mode 100755 index 000000000..befb3161c Binary files /dev/null and b/deployments/rainbow-swim-hybrid/docker/SWIM.png differ diff --git a/deployments/rainbow-swim-hybrid/docker/images/rainbow-ui-1.png b/deployments/rainbow-swim-hybrid/docker/images/rainbow-ui-1.png new file mode 100755 index 000000000..5e00b0983 Binary files /dev/null and b/deployments/rainbow-swim-hybrid/docker/images/rainbow-ui-1.png differ diff --git a/deployments/rainbow-swim-hybrid/docker/images/rainbow-ui-2.png b/deployments/rainbow-swim-hybrid/docker/images/rainbow-ui-2.png new file mode 100755 index 000000000..78e2bc281 Binary files /dev/null and b/deployments/rainbow-swim-hybrid/docker/images/rainbow-ui-2.png differ diff --git a/deployments/rainbow-swim-hybrid/docker/images/rainbow-ui-3.png b/deployments/rainbow-swim-hybrid/docker/images/rainbow-ui-3.png new file mode 100755 index 000000000..c1b787c7e Binary files /dev/null and b/deployments/rainbow-swim-hybrid/docker/images/rainbow-ui-3.png differ diff --git a/deployments/rainbow-swim-hybrid/docker/images/swim-login-screen.png b/deployments/rainbow-swim-hybrid/docker/images/swim-login-screen.png new file mode 100755 index 000000000..caa05b70a Binary files /dev/null and b/deployments/rainbow-swim-hybrid/docker/images/swim-login-screen.png differ diff --git a/deployments/rainbow-swim-hybrid/docker/rainbow.png b/deployments/rainbow-swim-hybrid/docker/rainbow.png new file mode 100755 index 000000000..492e66e2a Binary files /dev/null and b/deployments/rainbow-swim-hybrid/docker/rainbow.png differ diff --git a/deployments/rainbow-swim-hybrid/pom.xml b/deployments/rainbow-swim-hybrid/pom.xml new file mode 100644 index 000000000..39539d70d --- /dev/null +++ b/deployments/rainbow-swim-hybrid/pom.xml @@ -0,0 +1,516 @@ + + 4.0.0 + rainbow + rainbow-swim + jar + 2.1.1-SNAPSHOT + + utf-8 + + + + + + + + + Not yet defined. + + + manual + + Unknown + + + + + + + We + + http://www.we.com + + + + + + + + schmerl + + Bradley Schmerl + + schmerl@cs.cmu.edu + + CMU + + -5 + + + + + + + + pasc + Paulo Casanova + paulo.casanova@cs.cmu.edu + CMU + 0 + + + + + + + + + + + + + + + + + + scm:svn:svn://acme.able.cs.cmu.edu/rainbow/v2/trunk + + + + scm:svn:svn://acme.able.cs.cmu.edu/rainbow/v2/trunk + + + svn://acme.able.cs.cmu.edu/rainbow/v2/trunk + + + + + + org.apache.maven.wagon + wagon-webdav + 1.0-beta-2 + + + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.2 + + + + + + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.4 + + + http://svn.homenet/svn/projects/incubator/tags + + + + + + + org.codehaus.mojo + buildnumber-maven-plugin + 1.1 + + + validate + + create + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + test-jar + + + + + + + + true + + + + + ${buildNumber} + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12.4 + + -XX:-UseSplitVerifier + true + + + ${basedir} + + + + + + + + maven-dependency-plugin + + + install + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy + install + + copy + + + + + pladapt + libpladapt_wrap + 1.0.1 + so + x86_64 + ${project.build.directory}/lib + libpladapt_wrap.so + + + + + + + + + + + + + + + able.maven.repository + + dav:http://acme.able.cs.cmu.edu/maven-repository + + + + + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + + maven-javadoc-plugin + 2.9 + + true + + + + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 2.12.4 + + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.5.2 + + + + + org.apache.maven.plugins + maven-changes-plugin + 2.8 + + + + + org.codehaus.mojo + taglist-maven-plugin + 2.4 + + + TODO + FIXME + IDEA + @todo + @deprecated + + + + + + + org.apache.maven.plugins + maven-pmd-plugin + 2.7.1 + + true + iso8859-1 + 100 + 1.6 + + **/*Bean.java + **/generated/*.java + + + + + + + org.codehaus.mojo + findbugs-maven-plugin + 2.5.2 + + + + + + + + + + + + + + + + able.maven.repository + ABLE maven repository + + dav:http://acme.able.cs.cmu.edu/maven-repository + + + + + + + + + + dev-std + + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*Test.java + **/*TestCase.java + + + + + + + + full-test + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*Test.java + **/*TestCase.java + **/*TestSlow.java + + + + + + + + no-tests + + + + org.apache.maven.plugins + maven-surefire-plugin + + + TestIgnore + + + + + + + + + + + rainbow + rainbow-acme-model + 2.1.3-SNAPSHOT + + + rainbow + rainbow-stitch + 2.2-SNAPSHOT + + + rainbow + rainbow-utility-model + 2.0.1-SNAPSHOT + + + rainbow + rainbow-gui + 1.0.0-SNAPSHOT + + + + opera + hogna + 1.0 + + + opera + opera + 1.0 + + + xerces + xercesImpl + 2.9.1 + + + pladapt + pladapt_wrap + 1.0.1 + + + pladapt + libpladapt_wrap + 1.0.1 + runtime + so + x86_64 + + + diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/gui/RainbowControl.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/gui/RainbowControl.java new file mode 100644 index 000000000..0c6baa7ad --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/gui/RainbowControl.java @@ -0,0 +1,56 @@ +package org.sa.rainbow.gui; + +import java.text.MessageFormat; +import java.util.EnumSet; + +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.globals.ExitState; +import org.sa.rainbow.core.ports.IMasterCommandPort; +import org.sa.rainbow.core.ports.IMasterConnectionPort.ReportType; +import org.sa.rainbow.core.ports.IRainbowReportingSubscriberPort; +import org.sa.rainbow.core.ports.IRainbowReportingSubscriberPort.IRainbowReportingSubscriberCallback; +import org.sa.rainbow.core.ports.RainbowPortFactory; + +public class RainbowControl { + + private static void usage() { + String usage = MessageFormat.format( + "Usage: {0} command\n\tcommand='{startprobes|killprobes|terminate}'", RainbowControl.class.getSimpleName()); + System.out.println(usage); + } + + public static void main (String[] args) throws RainbowConnectionException { + if (args.length != 1) { + usage(); + return; + } + + IMasterCommandPort master = RainbowPortFactory.createMasterCommandPort (); + IRainbowReportingSubscriberPort reportingSubscriberPort = RainbowPortFactory + .createReportingSubscriberPort (new IRainbowReportingSubscriberCallback () { + + @Override + public void report (RainbowComponentT component, ReportType type, String message) { + if (type == ReportType.ERROR || type == ReportType.FATAL || type == ReportType.WARNING) { + System.out.println (type.name () + ": " + message); + } + if (component == RainbowComponentT.GAUGE) { + System.out.println ("Gauge: " + message); + } + } + }); + reportingSubscriberPort.subscribe (EnumSet.allOf (RainbowComponentT.class), EnumSet.allOf (ReportType.class)); + + if (args[0].equals("startprobes")) { + master.startProbes (); + } else if (args[0].equals("killprobes")) { + master.killProbes(); + } else if (args[0].equals("terminate")) { + master.terminate (ExitState.DESTRUCT); + } else { + usage(); + } + System.exit (1); + } +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java new file mode 100644 index 000000000..c6d4870e2 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java @@ -0,0 +1,114 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim; + +import java.util.HashSet; +import java.util.Set; +import java.util.Stack; + +import org.acmestudio.acme.core.resource.RegionManager; +import org.acmestudio.acme.element.IAcmeElementInstance; +import org.acmestudio.acme.element.IAcmeElementType; +import org.acmestudio.acme.environment.error.AcmeError; +import org.acmestudio.acme.rule.AcmeSet; +import org.acmestudio.acme.rule.node.IExpressionNode; +import org.acmestudio.acme.type.verification.NodeScopeLookup; +import org.acmestudio.acme.type.verification.RuleTypeChecker; +import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; + +/** + * This class provides SWIM-specific operators that can be referred to in strategies and tactics. This class can be + * imported into Stitch and the static members called from there. + * + * @author Bradley Schmerl: schmerl + * @author gmoreno + */ +public class Swim { + // Acme expressions for evaluating the methods + private static final String FIND_SERVICES_EXPR = "/self/components:T[!isArchEnabled]"; + private static final String AVAILABLE_SERVICES_EXPR = "size (" + FIND_SERVICES_EXPR + ")"; + // Holder objects for caching parsed Acme expressions + private static IExpressionNode s_availableServicesExpr = null; + private static IExpressionNode s_findServicesExpression; + + /** + * Returns the number services of a particular type that are available. Availability here means that they are not + * yet marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type + * + * @param model + * The model to find availabile services in + * @param elemType + * The type of service to find + * @return the number of services that are available. + * @throws Exception + */ + public static int availableServices (SwimModelUpdateOperatorsImpl model, IAcmeElementType elemType) + throws Exception { + if (s_availableServicesExpr == null) { + s_availableServicesExpr = StandaloneLanguagePackHelper.defaultLanguageHelper () + .designRuleExpressionFromString ( + AVAILABLE_SERVICES_EXPR, new RegionManager ()); + } + + // Add "T" as a name in scope, referring to the type that we are looking for + NodeScopeLookup nameLookup = new NodeScopeLookup (); + nameLookup.put ("T", elemType); + return RuleTypeChecker.evaluateAsInt (model.getModelInstance (), null, s_availableServicesExpr, + new Stack (), + nameLookup); + } + + /** + * Returns the services of a particular type that are available. Availability here means that they are not yet + * marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type + * + * @param model + * The model to find availabile services in + * @param type + * The type of service to find + * @return the number of services that are available. + * @throws Exception + */ + public static Set> findServices (SwimModelUpdateOperatorsImpl model, + IAcmeElementType type) + throws Exception { + if (s_findServicesExpression == null) { + s_findServicesExpression = StandaloneLanguagePackHelper.defaultLanguageHelper () + .designRuleExpressionFromString (FIND_SERVICES_EXPR, new RegionManager ()); + } + NodeScopeLookup nameLookup = new NodeScopeLookup (); + nameLookup.put ("T", type); + AcmeSet set = RuleTypeChecker.evaluateAsSet (model.getModelInstance (), null, s_findServicesExpression, + new Stack (), + nameLookup); + + Set> retSet = new HashSet<> (); + for (Object o : set.getValues ()) { + if (o instanceof IAcmeElementInstance) { + retSet.add ((IAcmeElementInstance )o); + } + } + return retSet; + } +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/SwimModelHelper.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/SwimModelHelper.java new file mode 100644 index 000000000..f8fe2f699 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/SwimModelHelper.java @@ -0,0 +1,232 @@ +package org.sa.rainbow.model.acme.swim; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.stitch.lib.SwimUtils; + +import pladapt.GenericConfiguration; + +/** + * Helper to query SWIM ACME model + * + * @author gmoreno + */ +public class SwimModelHelper { + private static final String LOAD_BALANCER = "LB0"; + public static final String CONFIG_ADD_SERVER_PROGRESS = "addServerProgress"; + public static final String CONFIG_DIMMER = "d"; + public static final String CONFIG_SERVERS = "s"; + public static final String ENV_ARRIVAL_RATE_MEAN = "m"; // as defined in pladapt.i (libadaptmgr) + public static final String ENV_ARRIVAL_RATE_VARIANCE = "v"; // as defined in pladapt.i (libadaptmgr) + //Might need to duplicate, look more into syntax + private static final String PROP_NUM_SERVERS = "[EXPR]size(/self/components:ServerT[isArchEnabled])"; + private static final String PROP_NUM_ACTIVE_SERVERS = "[EXPR]size(/self/components:ServerT[isArchEnabled and isActive])"; + private static final String PROP_MAX_SERVERS = "[EXPR]size(/self/components:ServerT)"; + private static final String PROP_MAX_SERVER_ACTIVATION_TIME = "[Max]ServerT.expectedActivationTime"; + private static final String PROP_ARRIVAL_RATE = "arrivalRate"; + private static final String PROP_AVG_TRAFFIC = "[EXPR]seqAverage()"; + + private AcmeModelInstance m_model = null; + private double m_estimatedBasicServiceTime; + private double m_estimatedBasicServiceTimeVariance; + private double m_estimatedOptServiceTime; + private double m_estimatedOptServiceTimeVariance; + + public double getEstimatedBasicServiceTime() { + return m_estimatedBasicServiceTime; + } + + public void setEstimatedBasicServiceTime(double mean, double variance) { + m_estimatedBasicServiceTime = mean; + m_estimatedBasicServiceTimeVariance = variance; + } + + public double getEstimatedOptServiceTime() { + return m_estimatedOptServiceTime; + } + + public void setEstimatedOptServiceTime(double mean, double variance) { + m_estimatedOptServiceTime = mean; + m_estimatedOptServiceTimeVariance = variance; + } + + public double getEstimatedBasicServiceTimeVariance() { + return m_estimatedBasicServiceTimeVariance; + } + + public double getEstimatedOptServiceTimeVariance() { + return m_estimatedOptServiceTimeVariance; + } + + public SwimModelHelper(AcmeModelInstance model) { + m_model = model; + } + + public double getDoubleProperty(String expr, double defaultValue) { + double val = defaultValue; + Object propValue = m_model.getProperty(expr); + if (propValue != null) { + if (propValue instanceof Float) { + val = ((Float) propValue).doubleValue(); + } else { + val = ((Double) propValue).doubleValue(); + } + } + return val; + } + + public int getIntegerProperty(String expr, int defaultValue) { + int val = defaultValue; + Integer propValue = (Integer) m_model.getProperty(expr); + if (propValue != null) { + val = propValue.intValue(); + } + return val; + } + + + public int getAddServerLatencySec() { + IAcmeProperty prop = m_model.getModelInstance().getProperty("ADD_SERVER_LATENCY_SEC"); + return ((Integer) PropertyHelper.toJavaVal(prop.getValue())).intValue(); + } + + public int getAddServerLatencyPeriods() { + int latencySec = getAddServerLatencySec(); + double periodMsec = Double.parseDouble(Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD)); + return (int) Math.ceil(latencySec * 1000 / periodMsec); + } + + public int getDimmerLevels() { + IAcmeProperty prop = m_model.getModelInstance().getProperty("DIMMER_LEVELS"); + return ((Integer) PropertyHelper.toJavaVal(prop.getValue())).intValue(); + } + + public double getDimmerMargin() { + IAcmeProperty prop = m_model.getModelInstance().getProperty("DIMMER_MARGIN"); + return ((Double) PropertyHelper.toJavaVal(prop.getValue())).doubleValue(); + } + + public double getMaximumCapacity() { + IAcmeProperty prop = m_model.getModelInstance().getProperty("MAX_ARRIVAL_CAPACITY"); + return ((Double) PropertyHelper.toJavaVal(prop.getValue())).doubleValue(); + } + + public double getRTThreshold() { + IAcmeProperty prop = m_model.getModelInstance().getProperty("RT_THRESHOLD"); + return ((Double) PropertyHelper.toJavaVal(prop.getValue())).doubleValue(); + } + + public double getCurrentDimmer() { + IAcmeProperty prop = m_model.getModelInstance().getComponent(LOAD_BALANCER).getProperty("dimmer"); + return ((Double) PropertyHelper.toJavaVal(prop.getValue())).doubleValue(); + } + + // public int getCurrentDimmerLevel() { + // double dimmer = getCurrentDimmer(); + // int dimmerLevels = getDimmerLevels(); + // double dimmerMargin = getDimmerMargin(); + // int level = SwimUtils.dimmerFactorToLevel(dimmer, dimmerLevels, dimmerMargin); + // return level; + // } + + //new level calculation + public int getCurrentDimmerLevel() { + return (int) (1 + (getDimmerLevels() - 1) * getCurrentDimmer()); + } + + public int getAddServerTacticProgress() { + + /* + * This assumes that only one server can be added at a time + */ + int latencyPeriods = getAddServerLatencyPeriods(); + if (getNumActiveServers() == getNumServers()) { + return latencyPeriods; // add completed already + } + + long expectedActivationTime = (long) getDoubleProperty(PROP_MAX_SERVER_ACTIVATION_TIME, 0); + long timeToCompletionMsec = expectedActivationTime - System.currentTimeMillis(); + if (timeToCompletionMsec <= 0) { + return latencyPeriods - 1; // because it hasn't finished, so we assume it will have by the next period + } + int remainingPeriods = (int) Math.ceil(timeToCompletionMsec / (1000 * getAddServerLatencySec())); + return latencyPeriods - remainingPeriods; + } + + public int getNumServers() { + return (int) getDoubleProperty(PROP_NUM_SERVERS, 1); + } + + public int getNumActiveServers() { + return (int) getDoubleProperty(PROP_NUM_ACTIVE_SERVERS, 1); + } + + public int getMaxServers() { + return (int) getDoubleProperty(PROP_MAX_SERVERS, 1); + } + + public double getArrivalRate() { + IAcmeProperty prop = m_model.getModelInstance().getComponent(LOAD_BALANCER).getProperty(PROP_ARRIVAL_RATE); + return ((Double) PropertyHelper.toJavaVal(prop.getValue())).doubleValue(); + } + + public int getNumServers(GenericConfiguration config) { + int numServers = getNumActiveServers(config); + if (config.getInt(CONFIG_ADD_SERVER_PROGRESS) < getAddServerLatencyPeriods()) { + + // there's a server booting + numServers++; + } + return numServers; + } + + public int getNumActiveServers(GenericConfiguration config) { + return config.getInt(CONFIG_SERVERS) + 1; + } + + public double getDimmer(GenericConfiguration config) { + int level = config.getInt(CONFIG_DIMMER) + 1; + int dimmerLevels = getDimmerLevels(); + double dimmerMargin = getDimmerMargin(); + return SwimUtils.dimmerLevelToFactor(level, dimmerLevels, dimmerMargin); + } + + public double getAverageResponseTime() { + IAcmeProperty prop = m_model.getModelInstance().getComponent(LOAD_BALANCER).getProperty("averageResponseTime"); + return ((Double) PropertyHelper.toJavaVal(prop.getValue())).doubleValue(); + } + + public double getBasicThroughput() { + IAcmeProperty prop = m_model.getModelInstance().getComponent(LOAD_BALANCER).getProperty("basicThroughput"); + return ((Double) PropertyHelper.toJavaVal(prop.getValue())).doubleValue(); + } + + + public double getOptResponseTime() { + IAcmeProperty prop = m_model.getModelInstance().getComponent(LOAD_BALANCER).getProperty("optResponseTime"); + return ((Double) PropertyHelper.toJavaVal(prop.getValue())).doubleValue(); + } + + public double getOptThroughput() { + IAcmeProperty prop = m_model.getModelInstance().getComponent(LOAD_BALANCER).getProperty("optThroughput"); + return ((Double) PropertyHelper.toJavaVal(prop.getValue())).doubleValue(); + } + + public int getNumThreadsPerServer() { + IAcmeProperty prop = m_model.getModelInstance().getProperty("THREADS_PER_SERVER"); + return ((Integer) PropertyHelper.toJavaVal(prop.getValue())).intValue(); + } + + public double getAvgTraffic() { + + /* + * PROP_AVG_TRAFFIC gets the average over all the servers in the model + * The load for inactive servers will be 0, so we have to compensate to get + * the average over the active servers + */ + return getDoubleProperty(PROP_AVG_TRAFFIC, 0.0); + } +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/SwimModelUpdateOperatorsImpl.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/SwimModelUpdateOperatorsImpl.java new file mode 100644 index 000000000..bcac948c7 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/SwimModelUpdateOperatorsImpl.java @@ -0,0 +1,205 @@ +/* + * The MIT License + * + * Copyright 2import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory; +oftware"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.Vector; + +import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; +import org.acmestudio.acme.core.type.IAcmeIntValue; +import org.acmestudio.acme.element.IAcmeElementInstance; +import org.acmestudio.acme.element.IAcmeElementType; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.DefaultAcmeModel; +import org.acmestudio.acme.type.AcmeTypeHelper; +import org.apache.commons.lang.NotImplementedException; +import org.apache.log4j.Logger; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.swim.commands.SwimCommandFactory; + +/** + * An Acme model that embodies the SWIM architecture and the associated style-specific operations + * + * @author Bradley Schmerl: schmerl + * @author gmoreno + */ +public class SwimModelUpdateOperatorsImpl extends AcmeModelInstance { + private static final String MAX_KEY = "[Max]"; + private static final String AVG_KEY = "[Avg]"; + + private final Logger LOGGER = Logger.getLogger (this.getClass ()); + + private SwimCommandFactory m_commandFactory; + + public SwimModelUpdateOperatorsImpl (IAcmeSystem system, String source) { + super (system, source); + // Make sure it is the right family + } + + @Override + public SwimCommandFactory getCommandFactory () { + if (m_commandFactory == null) { + m_commandFactory = new SwimCommandFactory (this); + } + return m_commandFactory; + } + + @Override + protected AcmeModelInstance generateInstance (IAcmeSystem sys) { + return new SwimModelUpdateOperatorsImpl (sys, getOriginalSource ()); + } + + @Override + public Object getProperty(String id) { + if (getModelInstance () == null) return null; + Object prop = null; + if (id.startsWith (MAX_KEY) || id.startsWith(AVG_KEY)) { + prop = internalGetProperty(id, 0); + } else { + prop = super.getProperty(id); + } + return prop; + } + + + /** + * Gets current or predicted property, depending on whether prediction is enabled and future duration is greater + * than 0. + * + * @param id + * the identifier for the property to get value for + * @param dur + * duration into the future to predict value, if applicable + * @return the Object that represents the value of the sought property. + */ + private Object internalGetProperty (String id, long dur) { + if (dur > 0) throw new NotImplementedException ("Prediction is not implemented"); + if (getModelInstance () == null) return null; + Object prop = null; + if (id.startsWith (MAX_KEY)) { + // the property id is expected to be of the form . + int idxStart = MAX_KEY.length (); + int idxDot = id.indexOf ("."); + if (idxDot == -1) { // property ID is not of expected form + LOGGER.error ("Unrecognized form of Max Property Name!" + id); + return null; + } + String typeName = id.substring (idxStart, idxDot); + String propName = id.substring (idxDot + 1); + + List propValues = collectInstancePropValues (typeName, propName); + if (propValues.size () > 0) { + + // find the maximum value of the property + double max = -Double.MAX_VALUE; + for (Double v : propValues) { + max = Math.max(max, v); + } + prop = max; + } + if (LOGGER.isTraceEnabled ()) { + LOGGER.trace ("Max Prop " + id + (dur > 0 ? "(+" + dur + ") " : "") + " requested == " + prop); + } + } else if (id.startsWith (AVG_KEY)) { + // the property id is expected to be of the form . + int idxStart = AVG_KEY.length (); + int idxDot = id.indexOf ("."); + if (idxDot == -1) { // property ID is not of expected form + LOGGER.error ("Unrecognized form of Average Property Name!" + id); + return null; + } + String typeName = id.substring (idxStart, idxDot); + String propName = id.substring (idxDot + 1); + + List propValues = collectInstancePropValues (typeName, propName); + if (propValues.size () > 0) { + + // find the average value of the property + double sum = 0.0; + for (Double v : propValues) { + sum += v; + } + prop = sum / propValues.size(); + } + if (LOGGER.isTraceEnabled ()) { + LOGGER.trace ("Avg Prop " + id + (dur > 0 ? "(+" + dur + ") " : "") + " requested == " + prop); + } + } + + return prop; + } + + /** + * Iterates through model's systems to collect all instances that either declares or instantiates the specified type + * name, then for all instances found that also have the specified property names, collect the property values + * + * @param typeName + * the specified element type name + * @param propName + * the specified property name within relevant instance + * @return the list of property values + */ + + private List collectInstancePropValues (String typeName, String propName) { + Vector values = new Vector<> (); + boolean useSatisfies = false; + if (typeName.startsWith ("!")) { + typeName = typeName.substring (1); + useSatisfies = true; + } + // Object elemObj = m_acme.findNamedObject(m_acme, typeName); + // if (! (elemObj instanceof IAcmeElementType)) { + // Debug.errorln("Element type of Average Property requested NOT found! " + // + typeName); + // return propKeys; + // } + IAcmeSystem sys = getModelInstance (); + Set> children = new HashSet<> (); + children.addAll (sys.getComponents ()); + children.addAll (sys.getConnectors ()); + children.addAll (sys.getPorts ()); + children.addAll (sys.getRoles ()); + for (IAcmeElementInstance child : children) { + + // seek element with specified type AND specified property + if ((useSatisfies && AcmeTypeHelper.satisfiesElementType (child, + ((IAcmeElementType )child.lookupName (typeName, true)), null)) + || child.declaresType (typeName) || child.instantiatesType (typeName)) { + IAcmeProperty childProp = child.getProperty (propName); + childProp.getValue(); + if (childProp != null) { + if (childProp.getType() == DefaultAcmeModel.defaultIntType()) { + values.add((double) ((IAcmeIntValue) childProp.getValue()).getValue()); + } else if (childProp.getType() == DefaultAcmeModel.defaultFloatType()) { + values.add(((IAcmeFloatingPointValue) childProp.getValue()).getDoubleValue()); + } + } + } + } + return values; + } +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java new file mode 100644 index 000000000..3466b28e5 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java @@ -0,0 +1,116 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * A class representing the Acme command to activate a server in SWIM. + * This is represented using the property isActive + * + * @author Bradley Schmerl: schmerl + * @author gmoreno + * + */ +public class ActivateServerCmd extends SwimAcmeModelCommand { + + private static final String PROPERTY = "isActive"; + + + // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" + public ActivateServerCmd (AcmeModelInstance model, String target, String enable) { + super ("activateServer", model, target, enable); + } + + /** + * Constructs the list of commands for activating the server by setting the isActive property + * + * @return the list of commands + * @throws RainbowModelException + * when the server cannot be found, is of the incorrect type, or the argument is malformed. + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + IAcmeProperty property = server.getProperty (PROPERTY); + if (property == null) { + throw new RainbowModelException(MessageFormat.format( + "The server ''{0}'' is not of the right type. It does not have a property ''" + PROPERTY + "''", + getTarget())); + } + try { + String str = getParameters ()[0]; + boolean activate = Boolean.valueOf (getParameters ()[0]); + + //if (str.equals("1")) { + // activate = true; + //} + + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (activate); + + //System.out.println("New value for isActive for server " + this.getTarget() + " is " + activate + // + " #### Current value = " + property.getValue () + // + " %%%% Boolean.valueOf (getParameters ()[0]) = " + str); + + if (propertyValueChanging (property, acmeVal)) { + m_command = property.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + } + catch (IllegalArgumentException e) { + throw new RainbowModelException (e.getMessage (), e); + } + + return cmds; + + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java new file mode 100644 index 000000000..2947128cd --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java @@ -0,0 +1,120 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * A class representing the Acme command to add a server to SWIM + * + * @author gmoreno + */ +public class AddServerCmd extends SwimAcmeModelCommand { + + private static final String PROPERTY = "expectedActivationTime"; + + private String m_server; + + + /** + * Target is the server add + * + * Note that since in SWIM we just add a server (not add a particular server) + * the target must be the server not currently enabled with the lowest index. + * + * This command does not mark the server as enabled. It only sets its expected + * activation time. Enablement happens through the gauge when is reported by the + * probe. + * + * The target is the load balancer, and the server is the server to be added + */ + public AddServerCmd (AcmeModelInstance model, String target, String server) { + super ("addServer", model, target, server); + m_server = server; + } + + /** + * Constructs the list of commands for setting the expectedActivationTime property + * + * @return the list of commands + * @throws RainbowModelException + * when the server cannot be found, is of the incorrect type, or the argument is malformed. + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", m_server)); + IAcmeProperty property = server.getProperty (PROPERTY); + if (property == null) { + throw new RainbowModelException(MessageFormat.format( + "The server ''{0}'' is not of the right type. It does not have a property ''{1}''", + m_server, PROPERTY)); + } + + IAcmeProperty prop = getModelContext().getModelInstance().getProperty("ADD_SERVER_LATENCY_SEC"); + int addServerLatency = ((Integer) PropertyHelper.toJavaVal(prop.getValue())).intValue(); + int expectedActivationTime = (int)(System.currentTimeMillis() / 1000) + addServerLatency; + + try { + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Integer.valueOf(expectedActivationTime)); + if (propertyValueChanging (property, acmeVal)) { + m_command = property.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + } + catch (IllegalArgumentException e) { + throw new RainbowModelException (e.getMessage (), e); + } + + return cmds; + + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerWithTypeCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerWithTypeCmd.java new file mode 100644 index 000000000..edb612a83 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerWithTypeCmd.java @@ -0,0 +1,34 @@ +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.List; + +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class AddServerWithTypeCmd extends SwimAcmeModelCommand { + + private String m_server; + + public AddServerWithTypeCmd(AcmeModelInstance model, String target, String server) { + super("addServer", model, target, server); + m_server = server; + } + + @Override + public IAcmeProperty getResult() throws IllegalStateException { + // TODO Auto-generated method stub + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + // This command cannot be executed on acme system, return null + // Only serves as place holder on bus to signal effector + @Override + protected List> doConstructCommand() throws RainbowModelException { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/DecDimmerCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/DecDimmerCmd.java new file mode 100644 index 000000000..c9f08fa34 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/DecDimmerCmd.java @@ -0,0 +1,38 @@ +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.List; + +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class DecDimmerCmd extends SwimAcmeModelCommand{ + + private static final String PROPERTY = "dimmer"; + + //private String m_server; + + // Target is the load balancer + public DecDimmerCmd(AcmeModelInstance model, String target) { + super("decDimmer", model, target, ""); + // TODO Auto-generated constructor stub + } + + + @Override + public IAcmeProperty getResult() throws IllegalStateException { + // TODO Auto-generated method stub + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + // This command cannot be executed on acme system, return null + // Only serves as place holder on bus to signal effector + @Override + protected List> doConstructCommand() throws RainbowModelException { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/DivertTrafficCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/DivertTrafficCmd.java new file mode 100644 index 000000000..b9536b443 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/DivertTrafficCmd.java @@ -0,0 +1,34 @@ +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.List; + +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class DivertTrafficCmd extends SwimAcmeModelCommand { + + private String m_divertCommand; + + public DivertTrafficCmd(AcmeModelInstance model, String target, String divertCommand) { + super("divertTraffic", model, target, divertCommand); + m_divertCommand = divertCommand; + } + + @Override + public IAcmeProperty getResult() throws IllegalStateException { + // TODO Auto-generated method stub + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + // This command cannot be executed on acme system, return null + // Only serves as place holder on bus to signal effector + @Override + protected List> doConstructCommand() throws RainbowModelException { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java new file mode 100644 index 000000000..233db9875 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java @@ -0,0 +1,114 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * A class representing the Acme command to enable a server in Znn. Currently, this is modeled by setting the property + * "isArchEnabled" on the model. + * + * @author Bradley Schmerl: schmerl + * + */ +public class EnableServerCmd extends SwimAcmeModelCommand { + + // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" + public EnableServerCmd (AcmeModelInstance model, String target, String enable) { + super ("enableServer", model, target, enable); + } + + /** + * Constructs the list of commands for enabling the server by setting the isArchEnabled property + * + * @return the list of commands + * @throws RainbowModelException + * when the server cannot be found, is of the incorrect type, or the argument is malformed. + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + if (!server.declaresType ("ArchElementT")) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''isArchEnabled''", + getTarget ())); + IAcmeProperty property = server.getProperty ("isArchEnabled"); + try { + boolean enabled = Boolean.valueOf (getParameters ()[0]); + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (enabled); + + String str = getParameters ()[0]; + + //System.out.println("New value for isArchEnabled for server " + this.getTarget() + " is " + enabled + // + " #### Current value = " + property.getValue () + // + " %%%% Boolean.valueOf (getParameters ()[0]) = " + str); + + if (propertyValueChanging (property, acmeVal)) { + m_command = property.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + + if (!enabled) { + // set the traffic to 0, so that it does not affect the average + IAcmeProperty trafficProperty = server.getProperty ("traffic"); + IAcmeCommand newCommand = trafficProperty.getCommandFactory ().propertyValueSetCommand (trafficProperty, + PropertyHelper.toAcmeVal(0.0)); + cmds.add(newCommand); + } + } + catch (IllegalArgumentException e) { + throw new RainbowModelException (e.getMessage (), e); + } + return cmds; + + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/IncDimmerCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/IncDimmerCmd.java new file mode 100644 index 000000000..379c488b1 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/IncDimmerCmd.java @@ -0,0 +1,38 @@ +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.List; + +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class IncDimmerCmd extends SwimAcmeModelCommand{ + + private static final String PROPERTY = "dimmer"; + + //private String m_server; + + // Target is the load balancer + public IncDimmerCmd(AcmeModelInstance model, String target) { + super("incDimmer", model, target, ""); + // TODO Auto-generated constructor stub + } + + + @Override + public IAcmeProperty getResult() throws IllegalStateException { + // TODO Auto-generated method stub + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + // This command cannot be executed on acme system, return null + // Only serves as place holder on bus to signal effector + @Override + protected List> doConstructCommand() throws RainbowModelException { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java new file mode 100644 index 000000000..17eb557e1 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java @@ -0,0 +1,79 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.LinkedList; +import java.util.List; + +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +/** + * A class representing the Acme command to remove a server from SWIM + * + * @author gmoreno + */ +public class RemoveServerCmd extends SwimAcmeModelCommand { + + /** + * Target is the server add + * + * Note that since in SWIM we just remove a server (not a particular server) + * the target must be the server currently enabled with the highest index. + * + * This command does not mark the server as not enabled. That happens + * through the gauge when is reported by the probe. + * + * The target is the load balancer, and the server is the server to be removed + */ + public RemoveServerCmd (AcmeModelInstance model, String target, String server) { + super ("removeServer", model, target, server); + } + + /** + * Nothing is changed in the model, so the command is empty + * + * @return the list of commands + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + return cmds; + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerWithTypeCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerWithTypeCmd.java new file mode 100644 index 000000000..3ff9a89e9 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerWithTypeCmd.java @@ -0,0 +1,34 @@ +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.List; + +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class RemoveServerWithTypeCmd extends SwimAcmeModelCommand { + + private String m_server; + + public RemoveServerWithTypeCmd(AcmeModelInstance model, String target, String server) { + super("removeServer", model, target, server); + m_server = server; + } + + @Override + public IAcmeProperty getResult() throws IllegalStateException { + // TODO Auto-generated method stub + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + // This command cannot be executed on acme system, return null + // Only serves as place holder on bus to signal effector + @Override + protected List> doConstructCommand() throws RainbowModelException { + // TODO Auto-generated method stub + return null; + } + +} \ No newline at end of file diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java new file mode 100644 index 000000000..498bc4ee8 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java @@ -0,0 +1,36 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetArrivalRateCmd extends SetDoubleCmd { + private final static String COMMAND = "setArrivalRate"; + private final static String PROPERTY = "arrivalRate"; + + public SetArrivalRateCmd(AcmeModelInstance model, String component, String value) { + super(COMMAND, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetAverageResponseTimeCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetAverageResponseTimeCmd.java new file mode 100644 index 000000000..d018f455a --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetAverageResponseTimeCmd.java @@ -0,0 +1,36 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetAverageResponseTimeCmd extends SetDoubleCmd { + private final static String COMMAND = "setAverageResponseTime"; + private final static String PROPERTY = "averageResponseTime"; + + public SetAverageResponseTimeCmd(AcmeModelInstance model, String component, String value) { + super(COMMAND, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java new file mode 100644 index 000000000..6c95b5e39 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java @@ -0,0 +1,36 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetBasicThroughputCmd extends SetDoubleCmd { + private final static String COMMAND = "setBasicThroughput"; + private final static String PROPERTY = "basicThroughput"; + + public SetBasicThroughputCmd(AcmeModelInstance model, String component, String value) { + super(COMMAND, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java new file mode 100644 index 000000000..dec45e722 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java @@ -0,0 +1,36 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetDimmerCmd extends SetDoubleCmd { + private final static String COMMAND = "setDimmer"; + private final static String PROPERTY = "dimmer"; + + public SetDimmerCmd(AcmeModelInstance model, String component, String value) { + super(COMMAND, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java new file mode 100644 index 000000000..cce8c3e5c --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java @@ -0,0 +1,98 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +public abstract class SetDoubleCmd extends SwimAcmeModelCommand { + + protected String m_property; + + private String m_component; + private double m_value; + + public SetDoubleCmd (String command, String property, AcmeModelInstance model, String component, String value) { + super (command, model, component, value); + m_component = component; + m_value = Double.valueOf (value); + m_property = property; + } + + /** + * This method can be overriden by derived classes to process the value + * before it is set in the model. + * + * @param value + * @return processed value to be set in the model + */ + public double processValue(double value) { + return value; + } + + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent server = getModelContext ().resolveInModel (m_component, IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + IAcmeProperty property = server.getProperty (m_property); + if (property == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''{1}''", + getTarget (), m_property)); + + try { + IAcmeFloatingPointValue acmeVal = PropertyHelper.toAcmeVal (m_value); + List> cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = server.getCommandFactory ().propertyValueSetCommand (property, acmeVal); + cmds.add (m_command); + } + return cmds; + } + catch (Exception e) { + throw new RainbowModelException (MessageFormat.format ("Error setting ACME model property ''{0}.{1}: {3}", + getTarget(), m_property, e.getMessage())); + } + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java new file mode 100644 index 000000000..dffdf881b --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java @@ -0,0 +1,36 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetOptResponseTimeCmd extends SetDoubleCmd { + private final static String COMMAND = "setOptResponseTime"; + private final static String PROPERTY = "optResponseTime"; + + public SetOptResponseTimeCmd(AcmeModelInstance model, String component, String value) { + super(COMMAND, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java new file mode 100644 index 000000000..aa0ad3f3b --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java @@ -0,0 +1,36 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetOptThroughputCmd extends SetDoubleCmd { + private final static String COMMAND = "setOptThroughput"; + private final static String PROPERTY = "optThroughput"; + + public SetOptThroughputCmd(AcmeModelInstance model, String component, String value) { + super(COMMAND, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetTrafficCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetTrafficCmd.java new file mode 100644 index 000000000..1a973ce01 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetTrafficCmd.java @@ -0,0 +1,45 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetTrafficCmd extends SetDoubleCmd { + + private final static String COMMAND = "setTraffic"; + private final static String PROPERTY = "traffic"; + + public SetTrafficCmd(AcmeModelInstance model, String component, String value) { + super(COMMAND, PROPERTY, model, component, value); + } + + public double processValue(double value) { + + /* + * We can get -1 reported by the probe for a server that is not present + * in the system (but is disabled or inactive in the architecture) + */ + return (value < 0) ? 0 : value; + } +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java new file mode 100644 index 000000000..2e78bfc0e --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java @@ -0,0 +1,43 @@ +/* + * The MIT License + * + * Copyright 2014 CMU Aimport org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.AcmeModelOperation; + "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelOperation; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public abstract class SwimAcmeModelCommand extends AcmeModelOperation { + + public SwimAcmeModelCommand (String commandName, AcmeModelInstance model, String target, + String... parameters) { + super (commandName, model, target, parameters); + } + + + @Override + protected boolean checkModelValidForCommand (IAcmeSystem model) { + return model.declaresType ("SwimFam"); + } + +} diff --git a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimCommandFactory.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimCommandFactory.java similarity index 69% rename from deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimCommandFactory.java rename to deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimCommandFactory.java index 72239b8b5..86ddcd3a7 100644 --- a/deployments/rainbow-example/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimCommandFactory.java +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimCommandFactory.java @@ -1,169 +1,212 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import java.io.InputStream; - -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.model.acme.AcmeModelCommandFactory; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import incubator.pval.Ensure; - -public class SwimCommandFactory extends AcmeModelCommandFactory { - - - public static SwimLoadModelCommand loadCommand (ModelsManager modelsManager, - String modelName, - InputStream stream, - String source) { - return new SwimLoadModelCommand (modelName, modelsManager, stream, source); - } - - public SwimCommandFactory (AcmeModelInstance modelInstance) { - super (modelInstance); - } - - @Override - protected void fillInCommandMap () { - super.fillInCommandMap (); - m_commandMap.put("SetDimmer".toLowerCase (), SetDimmerCmd.class); - m_commandMap.put("SetLoad".toLowerCase (), SetLoadCmd.class); - m_commandMap.put("SetArrivalRate".toLowerCase (), SetArrivalRateCmd.class); - m_commandMap.put("SetBasicResponseTime".toLowerCase (), SetBasicResponseTimeCmd.class); - m_commandMap.put("SetOptResponseTime".toLowerCase (), SetOptResponseTimeCmd.class); - m_commandMap.put("SetBasicThroughput".toLowerCase (), SetBasicThroughputCmd.class); - m_commandMap.put("SetOptThroughput".toLowerCase (), SetOptThroughputCmd.class); - m_commandMap.put("SetOptThroughput".toLowerCase (), SetOptThroughputCmd.class); - m_commandMap.put("EnableServer".toLowerCase (), EnableServerCmd.class); - m_commandMap.put("ActivateServer".toLowerCase (), ActivateServerCmd.class); - m_commandMap.put("AddServer".toLowerCase (), AddServerCmd.class); - m_commandMap.put("RemoveServer".toLowerCase (), RemoveServerCmd.class); - } - - - public SetDimmerCmd setDimmerCmd (IAcmeComponent loadBalancer, double dimmer) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetDimmerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (dimmer)); - } - - public SetLoadCmd setLoadCmd (IAcmeComponent server, double value) { - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetLoadCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - Double.toString (value)); - } - - public SetArrivalRateCmd setArrivalRateCmd (IAcmeComponent loadBalancer, double value) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetArrivalRateCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (value)); - } - - public SetBasicResponseTimeCmd setBasicResponseTimeCmd (IAcmeComponent loadBalancer, double value) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetBasicResponseTimeCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (value)); - } - - public SetOptResponseTimeCmd setOptResponseTimeCmd (IAcmeComponent loadBalancer, double value) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetOptResponseTimeCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (value)); - } - - public SetBasicThroughputCmd setBasicThroughputCmd (IAcmeComponent loadBalancer, double value) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetBasicThroughputCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (value)); - } - - public SetOptThroughputCmd setOptThroughputCmd (IAcmeComponent loadBalancer, double value) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetOptThroughputCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (value)); - } - - public EnableServerCmd enableServerCmd (IAcmeComponent server, boolean enabled) { - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new EnableServerCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - Boolean.toString (enabled)); - } - - public ActivateServerCmd activateServerCmd (IAcmeComponent server, boolean enabled) { - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new ActivateServerCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - Boolean.toString (enabled)); - } - - public AddServerCmd addServerCmd (IAcmeComponent loadBalancer, IAcmeComponent server) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new AddServerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - server.getQualifiedName()); - } - - public RemoveServerCmd removeServerCmd (IAcmeComponent loadBalancer, IAcmeComponent server) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new RemoveServerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - server.getQualifiedName()); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import java.io.InputStream; + +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.model.acme.AcmeModelCommandFactory; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import incubator.pval.Ensure; + +public class SwimCommandFactory extends AcmeModelCommandFactory { + + + public static SwimLoadModelCommand loadCommand (ModelsManager modelsManager, + String modelName, + InputStream stream, + String source) { + return new SwimLoadModelCommand (modelName, modelsManager, stream, source); + } + + public SwimCommandFactory (AcmeModelInstance modelInstance) { + super (modelInstance); + } + + @Override + protected void fillInCommandMap () { + super.fillInCommandMap (); + m_commandMap.put("SetDimmer".toLowerCase (), SetDimmerCmd.class); + m_commandMap.put("SetTraffic".toLowerCase (), SetTrafficCmd.class); + m_commandMap.put("SetArrivalRate".toLowerCase (), SetArrivalRateCmd.class); + m_commandMap.put("SetAverageResponseTime".toLowerCase (), SetAverageResponseTimeCmd.class); + //m_commandMap.put("SetOptResponseTime".toLowerCase (), SetOptResponseTimeCmd.class); + //m_commandMap.put("SetBasicThroughput".toLowerCase (), SetBasicThroughputCmd.class); + //m_commandMap.put("SetOptThroughput".toLowerCase (), SetOptThroughputCmd.class); + //m_commandMap.put("SetOptThroughput".toLowerCase (), SetOptThroughputCmd.class); + m_commandMap.put("EnableServer".toLowerCase (), EnableServerCmd.class); + m_commandMap.put("ActivateServer".toLowerCase (), ActivateServerCmd.class); + m_commandMap.put("AddServer".toLowerCase (), AddServerCmd.class); + m_commandMap.put("RemoveServer".toLowerCase (), RemoveServerCmd.class); + m_commandMap.put("IncDimmer".toLowerCase (), IncDimmerCmd.class); + m_commandMap.put("DecDimmer".toLowerCase (), IncDimmerCmd.class); + //m_commandMap.put("DivertTraffic".toLowerCase (), DivertTrafficCmd.class); + } + + + public SetDimmerCmd setDimmerCmd (IAcmeComponent loadBalancer, double dimmer) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetDimmerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (dimmer)); + } + + public SetTrafficCmd setTrafficCmd (IAcmeComponent server, double value) { + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetTrafficCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + Double.toString (value)); + } + + public SetArrivalRateCmd setArrivalRateCmd (IAcmeComponent loadBalancer, double value) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetArrivalRateCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (value)); + } + + public SetAverageResponseTimeCmd setAverageResponseTimeCmd (IAcmeComponent loadBalancer, double value) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetAverageResponseTimeCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (value)); + } + + public SetOptResponseTimeCmd setOptResponseTimeCmd (IAcmeComponent loadBalancer, double value) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetOptResponseTimeCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (value)); + } + + public SetBasicThroughputCmd setBasicThroughputCmd (IAcmeComponent loadBalancer, double value) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetBasicThroughputCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (value)); + } + + public SetOptThroughputCmd setOptThroughputCmd (IAcmeComponent loadBalancer, double value) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetOptThroughputCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (value)); + } + + public EnableServerCmd enableServerCmd (IAcmeComponent server, boolean enabled) { + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new EnableServerCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + Boolean.toString (enabled)); + } + + public ActivateServerCmd activateServerCmd (IAcmeComponent server, boolean enabled) { + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new ActivateServerCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + Boolean.toString (enabled)); + } + + public AddServerCmd addServerCmd (IAcmeComponent loadBalancer, IAcmeComponent server) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new AddServerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + server.getQualifiedName()); + } + + public RemoveServerCmd removeServerCmd (IAcmeComponent loadBalancer, IAcmeComponent server) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new RemoveServerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + server.getQualifiedName()); + } + + public IncDimmerCmd incDimmerCmd (IAcmeComponent loadBalancer) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new IncDimmerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName ()); + } + + public DecDimmerCmd decDimmerCmd (IAcmeComponent loadBalancer) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new DecDimmerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName ()); + } + + public DivertTrafficCmd divertTrafficCmd (IAcmeComponent loadBalancer, String divertCommand) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new DivertTrafficCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), divertCommand); + } + + public AddServerWithTypeCmd addServerWithTypeCmd (IAcmeComponent loadBalancer, String server) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new AddServerWithTypeCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), server); + } + + public RemoveServerWithTypeCmd removeServerWithTypeCmd (IAcmeComponent loadBalancer, String server) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new RemoveServerWithTypeCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), server); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java new file mode 100644 index 000000000..b9634435a --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java @@ -0,0 +1,19 @@ +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.Collections; +import java.util.List; + +/** + * Created by schmerl on 2/4/2016. + */ +public class SwimConstants { + public static final String SERVER_T_NAME = "ServerT"; + public static final String PROXY_CONN_T_NAME = "ProxyConnT"; + public static final String PROXY_FORWARD_PORT_T_NAME = "ProxyForwardPortT"; + public static final String HTTP_PORT_T_NAME = "HttpPortT"; + + static final List SERVER_TYPE = Collections.singletonList (SERVER_T_NAME); + static final List HTTP_CONN_T = Collections.singletonList (PROXY_CONN_T_NAME); + static final List PROXY_FORWARD_PORT = Collections.singletonList (PROXY_FORWARD_PORT_T_NAME); + static final List HTTP_PORT = Collections.singletonList (HTTP_PORT_T_NAME); +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimLoadModelCommand.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimLoadModelCommand.java new file mode 100644 index 000000000..e022f9735 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimLoadModelCommand.java @@ -0,0 +1,146 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.core.exception.AcmeException; +import org.acmestudio.acme.core.exception.AcmeVisitorException; +import org.acmestudio.acme.core.resource.IAcmeResource; +import org.acmestudio.acme.core.resource.ParsingFailureException; +import org.acmestudio.acme.core.type.IAcmeStringValue; +import org.acmestudio.acme.element.AbstractAcmeElementVisitor; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.acmestudio.acme.model.util.core.UMStringValue; +import org.acmestudio.standalone.resource.StandaloneResourceProvider; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; +import org.sa.rainbow.model.acme.swim.SwimModelUpdateOperatorsImpl; +import org.sa.rainbow.util.Util; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedList; +import java.util.List; + +public class SwimLoadModelCommand extends AbstractLoadModelCmd { + + public class AcmePropertySubstitutionVisitor extends AbstractAcmeElementVisitor { + + protected List> m_commands = new LinkedList<> (); + + public IAcmeCommand getCommand () { + if (m_commands.isEmpty ()) return null; + if (m_commands.size () == 1) return m_commands.get (0); + return m_commands.get (0).getCommandFactory ().compoundCommand (m_commands); + } + + @Override + public Object visitIAcmeProperty (IAcmeProperty property, Object data) throws AcmeVisitorException { + if (property.getValue () instanceof IAcmeStringValue) { + IAcmeStringValue val = (IAcmeStringValue )property.getValue (); + String origVal = val.getValue (); + String newVal = Util.evalTokens (origVal); + if (!newVal.equals (origVal)) { + IAcmePropertyCommand cmd = property.getCommandFactory ().propertyValueSetCommand (property, + new UMStringValue (newVal)); + m_commands.add (cmd); + } + } + return data; + } + } + + private String m_systemName; + private SwimModelUpdateOperatorsImpl m_result; + + public SwimLoadModelCommand (String systemName, IModelsManager mm, InputStream is, String source) { + super ("loadSwimModel", mm, systemName, is, source); + m_systemName = systemName; + } + + @Override + public ModelReference getModelReference () { + return new ModelReference (m_systemName, "Acme"); + } + + + @Override + protected void subExecute () throws RainbowException { + try { + IAcmeResource resource = StandaloneResourceProvider.instance () + .acmeResourceForObject ( + new File (getOriginalSource ())); + m_result = new SwimModelUpdateOperatorsImpl (resource.getModel ().getSystem (m_systemName), + getOriginalSource ()); + + // Do property substitution + try { + AcmePropertySubstitutionVisitor visitor = new AcmePropertySubstitutionVisitor (); + m_result.getModelInstance ().visit (visitor, null); + IAcmeCommand cmd = visitor.getCommand (); + cmd.execute (); + } + catch (IllegalStateException | AcmeException e) { + e.printStackTrace (); + } + + doPostExecute (); + } + catch (ParsingFailureException | IOException e) { + throw new RainbowException (e); + } + } + + @Override + protected void subRedo () throws RainbowException { + doPostExecute (); + } + + @Override + protected void subUndo () throws RainbowException { + doPostUndo (); + } + + @Override + public IModelInstance getResult () { + return m_result; + } + + @Override + public String getName () { + return "LoadSwimModel"; + } + + @Override + protected boolean checkModelValidForCommand (Object model) { + return true; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/stitch/lib/SwimUtils.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/stitch/lib/SwimUtils.java new file mode 100644 index 000000000..4b398084c --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/stitch/lib/SwimUtils.java @@ -0,0 +1,82 @@ +package org.sa.rainbow.stitch.lib; + +import org.acmestudio.acme.core.IAcmeType; +import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; +import org.acmestudio.acme.core.type.IAcmeIntValue; +import org.acmestudio.acme.element.IAcmeElementInstance; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.DefaultAcmeModel; + +public abstract class SwimUtils { + + public static int dimmerFactorToLevel(double dimmer, int dimmerLevels, double dimmerMargin) { + int level = 1 + (int) Math.round((dimmer - dimmerMargin) * (dimmerLevels - 1) / (1.0 - 2 * dimmerMargin)); + return level; + } + + public static double dimmerLevelToFactor(int level, int dimmerLevels, double dimmerMargin) { + double factor = dimmerMargin + (1.0 - 2 * dimmerMargin) * (level - 1.0) / (dimmerLevels - 1.0); + return factor; + } + + /** + * Find the element with the minimum value of the property "property" + * @param set + * @return element + */ + public static E minOverProperty(String property, java.util.Set set) { + E min = null; + double minValue = Double.MAX_VALUE; + + for (E e : set) { + if (!(e instanceof IAcmeElementInstance)) { + continue; + } + double value = 0; + IAcmeProperty prop = ((IAcmeElementInstance) e).getProperty(property); + IAcmeType type = prop.getType(); + IAcmePropertyValue val = prop.getValue(); + if (type == DefaultAcmeModel.defaultIntType()) { + value = ((IAcmeIntValue) val).getValue(); + } else if (type == DefaultAcmeModel.defaultFloatType()) { + value = ((IAcmeFloatingPointValue) val).getDoubleValue(); + } + if (min == null || value < minValue) { + min = e; + minValue = value; + } + } + return min; + } + + /** + * Find the element with the maximum value of the property "property" + * @param set + * @return element + */ + public static E maxOverProperty(String property, java.util.Set set) { + E max = null; + double maxValue = -Double.MAX_VALUE; + + for (E e : set) { + if (!(e instanceof IAcmeElementInstance)) { + continue; + } + double value = 0; + IAcmeProperty prop = ((IAcmeElementInstance) e).getProperty(property); + IAcmeType type = prop.getType(); + IAcmePropertyValue val = prop.getValue(); + if (type == DefaultAcmeModel.defaultIntType()) { + value = ((IAcmeIntValue) val).getValue(); + } else if (type == DefaultAcmeModel.defaultFloatType()) { + value = ((IAcmeFloatingPointValue) val).getDoubleValue(); + } + if (max == null || value < maxValue) { + max = e; + maxValue = value; + } + } + return max; + } +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManager.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManager.java new file mode 100644 index 000000000..6c018cf27 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManager.java @@ -0,0 +1,103 @@ +package org.sa.rainbow.swim.adaptation; + +import java.util.HashMap; + +import org.ho.yaml.Yaml; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.AdaptationExecutionOperatorT; +import org.sa.rainbow.core.adaptation.AdaptationTree; +import org.sa.rainbow.model.acme.swim.SwimModelHelper; +import org.sa.rainbow.stitch.core.Strategy; + +import pladapt.EnvironmentDTMCPartitioned; +import pladapt.GenericConfiguration; +import pladapt.GenericConfigurationManager; +import pladapt.JavaSDPAdaptationManager; +import pladapt.SDPAdaptationManager; +import pladapt.StringVector; + +public class AdaptationManager extends AdaptationManagerBase { + private static final String PLASDP_REACH_PATH = "rainbow.adaptation.plasdp.reachPath"; + private static final String PLASDP_REACH_MODEL = "rainbow.adaptation.plasdp.reachModel"; + private JavaSDPAdaptationManager m_adaptMgr; + + public AdaptationManager() { + // TODO Auto-generated constructor stub + } + + protected void initializeAdaptationMgr(SwimModelHelper swimModel) { + log("Starting PLA-SDP Adaptation Manager initialization"); + super.initializeAdaptationMgr(swimModel); + m_adaptMgr = new JavaSDPAdaptationManager(); + + // define configuration space + GenericConfigurationManager configMgr = new GenericConfigurationManager(); + GenericConfiguration configTemplate = configMgr.getConfigurationTemplate(); + configTemplate.setInt(SwimModelHelper.CONFIG_SERVERS, 0); + configTemplate.setInt(SwimModelHelper.CONFIG_DIMMER, 0); + configTemplate.setInt(SwimModelHelper.CONFIG_ADD_SERVER_PROGRESS, 0); + + int maxServers = swimModel.getMaxServers(); + int addServerLatencyPeriods = swimModel.getAddServerLatencyPeriods(); + + for (int dimmerLevels = 0; dimmerLevels < swimModel.getDimmerLevels(); dimmerLevels++) { + for (int servers = 0; servers < maxServers; servers++) { + for (int bootProgress = 0; bootProgress <= addServerLatencyPeriods; bootProgress++) { + GenericConfiguration config = configMgr.addNewConfiguration(); + config.setInt(SwimModelHelper.CONFIG_SERVERS, servers); + config.setInt(SwimModelHelper.CONFIG_DIMMER, dimmerLevels); + config.setInt(SwimModelHelper.CONFIG_ADD_SERVER_PROGRESS, bootProgress); + } + } + } + + // create configuration parameters. + // the following hardcoded values are like the constants above + HashMap params = new HashMap<>(); + params.put(SDPAdaptationManager.getNO_LATENCY(), Boolean.FALSE); + params.put(SDPAdaptationManager.getREACH_PATH(), getRainbowPropertyWithEnv(PLASDP_REACH_PATH)); + params.put(SDPAdaptationManager.getREACH_MODEL(), getRainbowPropertyWithEnv(PLASDP_REACH_MODEL)); + params.put(SDPAdaptationManager.getREACH_SCOPE(), + "S=" + maxServers + " TAP#=" + addServerLatencyPeriods + " D=" + swimModel.getDimmerLevels()); + String yamlParams = Yaml.dump(params); + + m_adaptMgr.initialize(configMgr, yamlParams); + log("PLA-SDP Adaptation Manager Initialized"); + } + + protected AdaptationTree checkAdaptationImpl(SwimModelHelper swimModel, + EnvironmentDTMCPartitioned env) { + AdaptationTree at = null; + + GenericConfiguration currentConfig = new GenericConfiguration(); + currentConfig.setInt(SwimModelHelper.CONFIG_SERVERS, swimModel.getNumActiveServers() - 1); + currentConfig.setInt(SwimModelHelper.CONFIG_DIMMER, swimModel.getCurrentDimmerLevel() - 1); + int progress = swimModel.getAddServerTacticProgress(); + currentConfig.setInt(SwimModelHelper.CONFIG_ADD_SERVER_PROGRESS, progress); + + log("current configuration is " + currentConfig); + + SwimUtilityFunction utilityFunction = new SwimUtilityFunction(m_model, swimModel); + + m_adaptMgr.setDebug(true); + StringVector tactics = m_adaptMgr.evaluate(currentConfig, env, utilityFunction, m_horizon); + + if (tactics.isEmpty()) { + log("no adaptation required"); + } else { +// at = new AdaptationTree (getStrategy(tactics.get(0))); + at = new AdaptationTree (getStrategy("IncDimmer")); +// at = new AdaptationTree(AdaptationExecutionOperatorT.PARALLEL); + log("In AM"); + for (int t = 0; t < tactics.size(); t++) { + log(tactics.get(t)); + Strategy strategy = getStrategy(tactics.get(t)); // Strategy has tactic name + at.addLeaf(strategy); + } + } + + return at; + } + + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerBase.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerBase.java new file mode 100644 index 000000000..14f8c785d --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerBase.java @@ -0,0 +1,832 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.swim.adaptation; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.acmestudio.acme.element.IAcmeSystem; +import org.apache.commons.lang.time.StopWatch; +import org.sa.rainbow.core.AbstractRainbowRunnable; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.adaptation.AdaptationTree; +import org.sa.rainbow.core.adaptation.DefaultAdaptationTreeWalker; +import org.sa.rainbow.core.adaptation.IAdaptationManager; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.health.IRainbowHealthProtocol; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.UtilityFunction; +import org.sa.rainbow.core.models.UtilityPreferenceDescription; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IRainbowAdaptationEnqueuePort; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.AcmeRainbowOperationEvent.CommandEventT; +import org.sa.rainbow.model.acme.swim.SwimModelHelper; +import org.sa.rainbow.stitch.Ohana; +import org.sa.rainbow.stitch.core.Strategy; +import org.sa.rainbow.stitch.core.Tactic; +import org.sa.rainbow.stitch.error.DummyStitchProblemHandler; +import org.sa.rainbow.stitch.error.IStitchProblem; +import org.sa.rainbow.stitch.error.StitchProblem; +import org.sa.rainbow.stitch.visitor.Stitch; +import org.sa.rainbow.timeseriespredictor.model.TimeSeriesPredictorModel; +import org.sa.rainbow.timeseriespredictor.model.TimeSeriesPredictorModelInstance; +import org.sa.rainbow.util.Beacon; +import org.sa.rainbow.util.Util; + +import pladapt.EnvironmentDTMCPartitioned; + +/** + * PLA Adaptation Manager Base + * + * @author gmoreno + */ +public abstract class AdaptationManagerBase extends AbstractRainbowRunnable + implements IAdaptationManager, IRainbowModelChangeCallback { + + private static final String PLA_OPERA_CONFIG = "rainbow.adaptation.pla.operaConfig"; + private static final String TSP_MODEL = "ArrivalRate"; + + public enum Mode { + SERIAL, MULTI_PRONE + } + + public static final String NAME = "PLA Adaptation Manager"; + public static final double FAILURE_RATE_THRESHOLD = 0.95; + public static final double MIN_UTILITY_THRESHOLD = 0.40; + public static final long FAILURE_EFFECTIVE_WINDOW = 2000 /* ms */; + public static final long FAILURE_WINDOW_CHUNK = 1000 /* ms */; + + private Mode m_mode = Mode.SERIAL; + protected AcmeModelInstance m_model = null; + private boolean m_adaptNeeded = false; // treat as synonymous with + // constraint being violated + private boolean m_adaptEnabled = true; // by default, we adapt + protected List m_repertoire = null; + private List> m_pendingStrategies = null; + + // track history + private String m_historyTrackUtilName = null; + private Map m_historyCnt = null; + private Map m_failTimer = null; + private IRainbowAdaptationEnqueuePort m_enqueuePort = null; + private IModelChangeBusSubscriberPort m_modelChangePort = null; + private IModelsManagerPort m_modelsManagerPort = null; + private String m_modelRef; + private FileChannel m_strategyLog = null; + private IRainbowChangeBusSubscription m_modelTypecheckingChanged = new IRainbowChangeBusSubscription () { + + @Override + public boolean matches (IRainbowMessage message) { + String type = (String) message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); + String modelName = (String) message.getProperty (IModelChangeBusPort.MODEL_NAME_PROP); + String modelType = (String) message.getProperty (IModelChangeBusPort.MODEL_TYPE_PROP); + try { + CommandEventT ct = CommandEventT.valueOf (type); + return (ct.isEnd () + && "setTypecheckResult".equals (message.getProperty (IModelChangeBusPort.COMMAND_PROP)) + && m_modelRef.equals (Util.genModelRef (modelName, modelType))); + } catch (Exception e) { + return false; + } + } + }; + //private UtilityPreferenceDescription m_utilityModel; + + protected int m_horizon; + private TimeSeriesPredictorModelInstance m_tspModel; + private OperaWrapper m_opera; + private double m_lastBasicResponseTime; + private double m_lastOptResponseTime; + protected boolean m_isInitialized = false; + + /** + * Default constructor. + */ + public AdaptationManagerBase () { + super (NAME); + + m_repertoire = new ArrayList (); + m_pendingStrategies = new ArrayList> (); + m_historyTrackUtilName = Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_TRACK_STRATEGY); + if (m_historyTrackUtilName != null) { + m_historyCnt = new HashMap (); + m_failTimer = new HashMap (); + } + + //setSleepTime (SLEEP_TIME); + String per = Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (per != null) { + setSleepTime (Long.parseLong (per)); + } else { // default to using the long sleep value + setSleepTime (IRainbowRunnable.LONG_SLEEP_TIME); + } + } + + @Override + public void initialize (IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize (port); + initConnectors (); + + } + + private void initConnectors () throws RainbowConnectionException { + m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort (); + m_modelChangePort.subscribe (m_modelTypecheckingChanged, this); + m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort (); + } + + @Override + public void setModelToManage (ModelReference model) { + m_modelRef = model.getModelName () + ":" + model.getModelType (); + try { + m_strategyLog = new FileOutputStream (new File (new File (Rainbow.instance ().getTargetPath (), "log"), + model.getModelName () + "-adaptation.log")).getChannel (); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace (); + } + m_model = (AcmeModelInstance) m_modelsManagerPort.getModelInstance (model); + if (m_model == null) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, + MessageFormat.format ("Could not find reference to {0}", model.toString ())); + } + m_enqueuePort = RainbowPortFactory.createAdaptationEnqueuePort (model); +// ModelReference utilityModelRef = new ModelReference (model.getModelName (), "UtilityModel"); +// IModelInstance modelInstance = m_modelsManagerPort +// .getModelInstance (utilityModelRef); +// if (modelInstance == null) { +// m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, +// MessageFormat.format ( +// "There is no utility model associated with this model. Expecting to find " + +// "''{0}''. Perhaps it is not specified in the rainbow.properties " + +// "file?", +// utilityModelRef.toString ())); +// +// } else { +// m_utilityModel = modelInstance.getModelInstance (); +// } + + initAdaptationRepertoire (); + + SwimModelHelper swimModel = new SwimModelHelper(m_model); + if (!m_isInitialized) { + initializeAdaptationMgr(swimModel); + } + } + + /* + * (non-Javadoc) + * + * @see org.sa.rainbow.core.IDisposable#dispose() + */ + @Override + public void dispose () { + for (Stitch stitch : m_repertoire) { + stitch.dispose (); + } + Ohana.instance ().dispose (); + m_repertoire.clear (); + m_pendingStrategies.clear (); + if (m_historyTrackUtilName != null) { + m_historyCnt.clear (); + m_failTimer.clear (); + m_historyCnt = null; + m_failTimer = null; + } + + if (m_enqueuePort != null) { + m_enqueuePort.dispose (); + } + m_modelChangePort.dispose (); + + // null-out data members + m_repertoire = null; + m_pendingStrategies = null; + m_historyTrackUtilName = null; + m_model = null; + if (m_strategyLog != null) { + try { + m_strategyLog.close (); + } catch (IOException ignored) { + } + m_strategyLog = null; + } + } + + @Override + protected void doTerminate () { + if (m_strategyLog != null) { + try { + m_strategyLog.close (); + } catch (IOException ignore) { + } + m_strategyLog = null; + } + super.doTerminate (); + } + + protected void finalize() { + if (m_strategyLog != null) { + try { + m_strategyLog.close (); + } catch (IOException ignore) { + } + m_strategyLog = null; + } + } + + /* + * (non-Javadoc) + * + * @see org.sa.rainbow.core.AbstractRainbowRunnable#log(java.lang.String) + */ + @Override + protected void log (String txt) { + m_reportingPort.info (RainbowComponentT.ADAPTATION_MANAGER, txt); + } + + protected void error (String txt) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, txt); + } + + @Override + public boolean isEnabled () { + return m_adaptEnabled; + } + + public void setAdaptationEnabled (boolean b) { + m_adaptEnabled = b; + } + + public boolean adaptationInProgress () { + return m_adaptNeeded; + } + + /** + * Removes a Strategy from the list of pending strategies, marking it as being completed (doesn't incorporate + * outcome). + * + * @param strategy the strategy to mark as being executed. + */ + @Override + public void markStrategyExecuted (AdaptationTree strategy) { + //log("****marking strategy " + strategy); + if (m_pendingStrategies.contains (strategy)) { + m_pendingStrategies.remove (strategy); + final List strategiesExecuted = new LinkedList<> (); + + StrategyAdaptationResultsVisitor resultCollector = new StrategyAdaptationResultsVisitor + (strategy, strategiesExecuted); + strategy.visit (resultCollector); + + for (Strategy str : strategiesExecuted) { + String s = str.getName () + ";" + str.outcome (); + log ("*S* outcome: " + s); + Util.dataLogger ().info (IRainbowHealthProtocol.DATA_ADAPTATION_STRATEGY + s); + tallyStrategyOutcome (str); + } + + } + if (m_pendingStrategies.size () == 0) { + Util.dataLogger ().info (IRainbowHealthProtocol.DATA_ADAPTATION_END); + // reset adaptation flags + m_adaptNeeded = false; +// m_model.clearConstraintViolated (); + } + } + + /* + * (non-Javadoc) + * + * @see org.sa.rainbow.core.AbstractRainbowRunnable#runAction() + */ + @Override + protected void runAction () { + if (m_adaptEnabled) { + if (m_mode == Mode.SERIAL && m_pendingStrategies.size () > 0) { + // Only go if there are no pending strategies + + log("Pending strategies. Skipping adaptation decision"); + return; + } + Util.dataLogger ().info (IRainbowHealthProtocol.DATA_ADAPTATION_SELECTION_BEGIN); + AdaptationTree at = checkAdaptation (); + Util.dataLogger ().info (IRainbowHealthProtocol.DATA_ADAPTATION_SELECTION_END); + if (at != null) { + //log (">> do strategy: " + at); + m_pendingStrategies.add (at); + m_enqueuePort.offerAdaptation (at, null); + String logMessage = at.toString (); + strategyLog(logMessage); + } + } + } + + private void strategyLog (String logMessage) { + if (m_strategyLog != null) { + Date d = new Date (); + String log = MessageFormat.format ("{0,number,#},queuing,{1}\n", d.getTime (), + logMessage); + try { + m_strategyLog.write (java.nio.ByteBuffer.wrap (log.getBytes ())); + } catch (IOException e) { + reportingPort ().error (getComponentType (), "Failed to write " + log + " to log file"); + } + } + } + + /** + * For JUnit testing, used to set a stopwatch object used to time duration. + */ + StopWatch _stopWatchForTesting = null; + + /** + * For JUnit testing, allows fetching the strategy repertoire. NOT for public use! + * + * @return list of Stitch objects loaded at initialization from stitch file. + */ + List _retrieveRepertoireForTesting () { + return m_repertoire; + } + + + /** + * For JUnit testing, allows re-invoking defineAttributes to artificially increase the number of quality dimensions + * in tactic attribute vectors. + */ + void _defineAttributesFromTester (Stitch stitch, Map> attrVectorMap) { + defineAttributes (stitch, attrVectorMap); + } + + + private void computeDecisionHorizon(SwimModelHelper swimModel) { + m_horizon = (int) Math.max(5.0, + swimModel.getAddServerLatencyPeriods() * (swimModel.getMaxServers() - 1) + 1); + + // set value in tsp model + ModelReference modelRef = new ModelReference(TSP_MODEL, TimeSeriesPredictorModelInstance.MODEL_TYPE); + m_tspModel = (TimeSeriesPredictorModelInstance) m_modelsManagerPort.getModelInstance (modelRef); + try { + m_tspModel.getModelInstance().setHorizon(m_horizon); + } catch (RainbowException e) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, e.toString()); + } + } + + /** + * load PLADAPT wrapper + */ + static { + System.loadLibrary("pladapt_wrap"); + } + + private void initOpera() { + log("Initializing Opera"); + File operaConfigFile = Util.getRelativeToPath (Rainbow.instance ().getTargetPath (), + Rainbow.instance ().getProperty (PLA_OPERA_CONFIG)); + m_opera = new OperaWrapper(); + m_opera.configure(operaConfigFile); + log("Opera initialized"); + } + + /** + * update KF using Opera model + */ + private void updateOperaKF(SwimModelHelper swimModel) { + + // update KF + // utilization and arrival rate have to be normalized to a single server (we assumed all are identical) + //double obsBasicThroughput = swimModel.getBasicThroughput(); + //double obsOptThroughput = swimModel.getOptThroughput(); + double obsAverageResponseTime = swimModel.getAverageResponseTime(); + //double obsOptResponseTime = swimModel.getOptResponseTime(); + + int activeServers = swimModel.getNumActiveServers(); + double avgTraffic = swimModel.getAvgTraffic(); + double basicResponseTime = 0; + //if (obsBasicThroughput > 0.0) { + if (true) { + basicResponseTime = obsAverageResponseTime; + m_lastBasicResponseTime = basicResponseTime; + } else { + basicResponseTime = m_lastBasicResponseTime; + } + double optResponseTime = 0; + //if (obsOptThroughput > 0.0) { + if (true) { + //optResponseTime = obsOptResponseTime; + m_lastOptResponseTime = optResponseTime; + } else { + optResponseTime = m_lastOptResponseTime; + } + + double arrivalRate = swimModel.getArrivalRate(); + double dimmer = swimModel.getCurrentDimmer(); + double normalArrivalRate = arrivalRate * dimmer; + double lowArrivalRate = arrivalRate * (1 - dimmer); + + + log("KF update : servers=" + activeServers + + " avgutil=" + avgTraffic + + " normalAR=" + normalArrivalRate + + " normalRT=" + optResponseTime + //+ " normalTP=" + obsOptThroughput + + " low: AR=" + lowArrivalRate + + " RT=" + basicResponseTime); + //+ " TP=" + obsBasicThroughput); + m_opera.updateModel(activeServers, avgTraffic, + //normalArrivalRate, optResponseTime, obsOptThroughput, + //lowArrivalRate, basicResponseTime, obsBasicThroughput); + normalArrivalRate, optResponseTime, 0.0, + lowArrivalRate, basicResponseTime, 0.0); + + double[] results = m_opera.getParamEstimates(); + double estBasicServiceTime = results[1]; + double estOptServiceTime = results[0]; + + log("KF output X low(" + estBasicServiceTime + ')' + + ", normal(" + estOptServiceTime + ')'); + swimModel.setEstimatedBasicServiceTime(estBasicServiceTime, Math.pow(estBasicServiceTime, 2)); + swimModel.setEstimatedOptServiceTime(estOptServiceTime, Math.pow(estOptServiceTime, 2)); + } + + + private EnvironmentDTMCPartitioned generateEnvironmentModel() { + return m_tspModel.getModelInstance().generateEnvironmentDTMC(2, m_horizon); + } + + protected Strategy getStrategy(String name) { + Strategy strategy = null; + for (Stitch stitch : m_repertoire) { + log(stitch.toString()); + if (!stitch.script.isApplicableForSystem (m_model)) { + m_reportingPort.trace (getComponentType (), "x. skipping " + stitch.script.getName ()); + continue; // skip checking this script + } + for (Strategy t : stitch.script.strategies) { + if (t.getName().equals(name)) { + strategy = t; + break; + } + } + } + + if (strategy == null) { + m_reportingPort.error(RainbowComponentT.ADAPTATION_MANAGER, + "Script for strategy ''" + name + "'' not found"); + } + return strategy; + } + + /** + * Subclasses overriding this for their own initialization must invoke this method + */ + protected void initializeAdaptationMgr(SwimModelHelper swimModel) { + computeDecisionHorizon(swimModel); + initOpera(); + m_isInitialized = true; + } + + /** + * Select (or generate) strategy for adaptation + * @return strategy to execute or null for no adaptation + */ + protected AdaptationTree checkAdaptation () { + boolean decide = true; + AdaptationTree at = null; + log ("New Checking if adaptation is required."); + if (_stopWatchForTesting != null) { + _stopWatchForTesting.start (); + } + + SwimModelHelper swimModel = new SwimModelHelper(m_model); + if (!m_isInitialized) { + initializeAdaptationMgr(swimModel); + } + + updateOperaKF(swimModel); + + log ("Updated Opera KF"); + + // the env generation is part of the decision as in OMNeT + long start = System.currentTimeMillis(); + EnvironmentDTMCPartitioned env = generateEnvironmentModel(); + + log ("Got EnvironmentDTMCPartitioned"); + + if (env == null) { + log("No environment observations available. Can't make adaptation decision"); + decide = false; + } + + if (decide) { + at = checkAdaptationImpl (swimModel, env); + long durationMsec = System.currentTimeMillis() - start; + log("Adaptation decision time (ms) = " + durationMsec); + } + + if (_stopWatchForTesting != null) { + _stopWatchForTesting.stop (); + } + + log ("About to return at"); + return at; + } + + protected abstract AdaptationTree checkAdaptationImpl(SwimModelHelper swimModel, + EnvironmentDTMCPartitioned env); + + @SuppressWarnings("unused") + private AdaptationTree checkAdaptationTest () { + AdaptationTree at = null; + log ("Test Checking if adaptation is required."); + if (_stopWatchForTesting != null) { + _stopWatchForTesting.start (); + } + + at = new AdaptationTree(getStrategy("IncDimmer")); +// StringVector tactics = new StringVector(); +// tactics.add("IncDimmer"); +// tactics.add("AddServer"); +// at = new AdaptationTree(AdaptationExecutionOperatorT.PARALLEL); +// for (int t = 0; t < tactics.size(); t++) { +// log(tactics.get(t)); +// Strategy strategy = getStrategy(tactics.get(t)); // Strategy has tactic name +// at.addLeaf(strategy); +// } + + if (_stopWatchForTesting != null) { + _stopWatchForTesting.stop (); + } + log ("About to return."); + return at; + } + + /** + * Retrieves the adaptation repertoire; for each tactic, store the respective tactic attribute vectors. + */ + private void initAdaptationRepertoire () { + File stitchPath = Util.getRelativeToPath (Rainbow.instance ().getTargetPath (), + Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_SCRIPT_PATH)); + if (stitchPath == null) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, "The stitch path is not set!"); + } else if (stitchPath.exists () && stitchPath.isDirectory ()) { + FilenameFilter ff = new FilenameFilter () { // find only ".s" files + @Override + public boolean accept (File dir, String name) { + return name.endsWith (".s"); + } + }; + for (File f : stitchPath.listFiles (ff)) { + try { + + // don't load .t.s files: these are tactics imported from .s files + if (f.getName().endsWith(".t.s")) { + continue; + } + // don't duplicate loading of script files + Stitch stitch = Ohana.instance ().findStitch (f.getCanonicalPath ()); + if (stitch == null) { + DummyStitchProblemHandler stitchProblemHandler = new DummyStitchProblemHandler (); + stitch = Stitch.newInstance (f.getCanonicalPath (), stitchProblemHandler); + Ohana.instance ().parseFile (stitch); +// StitchTypechecker behavior = (StitchTypechecker )stitch.getBehavior (Stitch.TYPECHECKER_PASS); + + reportProblems (f, stitchProblemHandler); + + // apply attribute vectors to tactics, if available +// defineAttributes (stitch, m_utilityModel.attributeVectors); + m_repertoire.add (stitch); + log ("Parsed script " + stitch.path); + } else { + log ("Previously known script " + stitch.path); + } + } catch (IOException e) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, + "Obtaining file canonical path failed! " + f.getName (), e); + } + } + } + } + + private void reportProblems (File f, DummyStitchProblemHandler sph) { + + Collection problem = sph.getProblems (); + if (!problem.isEmpty ()) { + log ("Errors exist in strategy: " + f.getName () + ", or one of its included files"); + } + for (IStitchProblem p : problem) { + StringBuilder out = new StringBuilder (); + switch (p.getSeverity ()) { + case StitchProblem.ERROR: + out.append ("ERROR: "); + break; + case StitchProblem.WARNING: + out.append ("WARNING: "); + break; + case StitchProblem.FATAL: + out.append ("FATAL ERROR: "); + break; + case StitchProblem.UNKNOWN: + out.append ("UNKNOWN PROBLEM: "); + break; + } + out.append ("Line: ").append (p.getLine ()); + out.append (", "); + out.append (" Column: ").append (p.getColumn ()); + out.append (": ").append (p.getMessage ()); + log (out.toString ()); + } + sph.clearProblems (); + } + + private void defineAttributes (Stitch stitch, Map> attrVectorMap) { + for (Tactic t : stitch.script.tactics) { + Map attributes = attrVectorMap.get (t.getName ()); + if (attributes != null) { + // found attribute def for tactic, save all key-value pairs + m_reportingPort.trace (getComponentType (), + "Found attributes for tactic " + t.getName () + ", saving pairs..."); + for (Map.Entry e : attributes.entrySet ()) { + t.putAttribute (e.getKey (), e.getValue ()); + m_reportingPort.trace (getComponentType (), " - (" + e.getKey () + ", " + e.getValue () + ")"); + } + } + } + } + + private static final int I_RUN = 0; + private static final int I_SUCCESS = 1; + private static final int I_FAIL = 2; + private static final int I_OTHER = 3; + private static final int CNT_I = 4; + + private void tallyStrategyOutcome (Strategy s) { + if (m_historyTrackUtilName == null) return; + + String name = s.getName (); + // mark timer of failure, if applicable + Beacon timer = m_failTimer.get (name); + if (timer == null) { + timer = new Beacon (); + m_failTimer.put (name, timer); + } + // get the stats array for this strategy + int[] stat = m_historyCnt.get (name); + if (stat == null) { + stat = new int[CNT_I]; + stat[I_RUN] = 0; + stat[I_SUCCESS] = 0; + stat[I_FAIL] = 0; + stat[I_OTHER] = 0; + m_historyCnt.put (name, stat); + } + // tally outcome counts + ++stat[I_RUN]; + switch (s.outcome ()) { + case SUCCESS: + ++stat[I_SUCCESS]; + break; + case FAILURE: + ++stat[I_FAIL]; + timer.mark (); + break; + default: + ++stat[I_OTHER]; + break; + } + String str = name + Arrays.toString (stat); + log ("History: " + str); + Util.dataLogger ().info (IRainbowHealthProtocol.DATA_ADAPTATION_STAT + str); + } + + + @Override + public void onEvent (ModelReference mr, IRainbowMessage message) { + // Because of the subscription, the model should be the model ref so no need to check + String typecheckSt = (String) message.getProperty (IModelChangeBusPort.PARAMETER_PROP + "0"); + Boolean typechecks = Boolean.valueOf (typecheckSt); + // Cause the thread to wake up if it is sleeping + if (!typechecks) { + activeThread ().interrupt (); + } + } + + @Override + public RainbowComponentT getComponentType () { + return RainbowComponentT.ADAPTATION_MANAGER; + } + + @Override + public void setEnabled (boolean enabled) { + m_reportingPort.info (getComponentType (), + MessageFormat.format ("Turning adaptation {0}.", (enabled ? "on" : "off"))); + if (!enabled && !m_pendingStrategies.isEmpty ()) { + m_reportingPort.info (getComponentType (), "There is an adaptation in progress. This will finish."); + } + m_adaptEnabled = enabled; + } + + private class StrategyAdaptationResultsVisitor extends DefaultAdaptationTreeWalker { + private final List m_strategiesExecuted; + + public StrategyAdaptationResultsVisitor (AdaptationTree strategy, + List strategiesExecuted) { + super (strategy); + m_strategiesExecuted = strategiesExecuted; + } + + @Override + protected void evaluate (Strategy adaptation) { + if (adaptation.outcome () != Strategy.Outcome.UNKNOWN) { + synchronized (m_strategiesExecuted) { + m_strategiesExecuted.add (adaptation); + } + } + } + + + } + + + /** + * This wraps Rainbow.instance().getProperty() so that environment variables can be used + * in property values. + * + * For example: reachPath = ${PLADAPT}/reach/reach.sh + * where PLADAPT is an environment variable + * + * @param key property name + * @return property value with environment variables replaced with their values + */ + protected String getRainbowPropertyWithEnv(String key) { + String value = Rainbow.instance().getProperty(key); + if (null == key) { + return null; + } + + Pattern p = Pattern.compile("\\$\\{(\\w+)\\}|\\$(\\w+)"); + Matcher m = p.matcher(value); + StringBuffer sb = new StringBuffer(); + while (m.find()) { + String envVarName = null == m.group(1) ? m.group(2) : m.group(1); + String envVarValue = System.getenv(envVarName); + if (null == envVarValue) { + error("Environment variable " + envVarName + " is not defined"); + } + m.appendReplacement(sb, + null == envVarValue ? "" : Matcher.quoteReplacement(envVarValue)); + } + m.appendTail(sb); + return sb.toString(); + } +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerDummy.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerDummy.java new file mode 100644 index 000000000..62f456abd --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerDummy.java @@ -0,0 +1,385 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.swim.adaptation; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import org.acmestudio.acme.element.IAcmeSystem; +import org.apache.commons.lang.time.StopWatch; +import org.sa.rainbow.core.AbstractRainbowRunnable; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.adaptation.AdaptationExecutionOperatorT; +import org.sa.rainbow.core.adaptation.AdaptationTree; +import org.sa.rainbow.core.adaptation.DefaultAdaptationTreeWalker; +import org.sa.rainbow.core.adaptation.IAdaptationManager; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.health.IRainbowHealthProtocol; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.UtilityFunction; +import org.sa.rainbow.core.models.UtilityPreferenceDescription; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IRainbowAdaptationEnqueuePort; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.AcmeRainbowOperationEvent.CommandEventT; +import org.sa.rainbow.model.acme.swim.SwimModelHelper; +import org.sa.rainbow.stitch.Ohana; +import org.sa.rainbow.stitch.core.Strategy; +import org.sa.rainbow.stitch.core.Tactic; +import org.sa.rainbow.stitch.error.DummyStitchProblemHandler; +import org.sa.rainbow.stitch.error.IStitchProblem; +import org.sa.rainbow.stitch.error.StitchProblem; +import org.sa.rainbow.stitch.visitor.Stitch; +import org.sa.rainbow.util.Beacon; +import org.sa.rainbow.util.Util; + + +public final class AdaptationManagerDummy extends AbstractRainbowRunnable + implements IAdaptationManager, IRainbowModelChangeCallback { + + + public static final String NAME = "Swim Extended Adaptation Manager Dummy"; + // The thread "sleep" time. runAction will be called every 10 seconds in this case + public static final int SLEEP_TIME = 60000 /*ms*/; + + // Port to query with any models in models manager + private IModelsManagerPort m_modelsManagerPort; + private IModelChangeBusSubscriberPort m_modelChangePort; + private ModelReference m_modelRef; + private IRainbowAdaptationEnqueuePort m_adaptationEnqueuePort; + private boolean m_adaptationEnabled = true; + private boolean m_adaptationNeeded = false; + private boolean m_errorDetected = false; + private FileChannel m_strategyLog = null; + private boolean m_executingPlan = false; + + protected AcmeModelInstance m_model = null; + + protected boolean m_isInitialized = false; + + + private IRainbowChangeBusSubscription m_modelTypecheckingChanged = new IRainbowChangeBusSubscription () { + + @Override + public boolean matches (IRainbowMessage message) { + String type = (String) message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); + String modelName = (String) message.getProperty (IModelChangeBusPort.MODEL_NAME_PROP); + String modelType = (String) message.getProperty (IModelChangeBusPort.MODEL_TYPE_PROP); + try { + CommandEventT ct = CommandEventT.valueOf (type); + return (ct.isEnd () + && "setTypecheckResult".equals (message.getProperty (IModelChangeBusPort.COMMAND_PROP)) + && m_modelRef.equals (Util.genModelRef (modelName, modelType))); + } catch (Exception e) { + return false; + } + } + }; + + public AdaptationManagerDummy () { + super (NAME); + String per = Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (per != null) { + setSleepTime (Long.parseLong (per)); + } + else { + setSleepTime (SLEEP_TIME); + } + } + + @Override + public void initialize (IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize(port); + initConnectors (); + } + + private void initConnectors () throws RainbowConnectionException { + // Create port to query models manager + m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort (); + m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort (); + m_modelChangePort.subscribe (m_modelTypecheckingChanged, this); + } + + @Override + public void setModelToManage(ModelReference modelRef) { + m_modelRef = modelRef; + try { + m_strategyLog = new FileOutputStream (new File (new File (Rainbow.instance ().getTargetPath (), "log"), + modelRef.getModelName () + "-adaptation.log")).getChannel (); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + m_model = (AcmeModelInstance) m_modelsManagerPort.getModelInstance (modelRef); + if (m_model == null) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, + MessageFormat.format ("Could not find reference to {0}", modelRef.toString ())); + } + m_adaptationEnqueuePort = RainbowPortFactory.createAdaptationEnqueuePort (modelRef); + SwimModelHelper swimModel = new SwimModelHelper(m_model); + if (!m_isInitialized) { + initializeAdaptationMgr(swimModel); + } + } + + protected void initializeAdaptationMgr(SwimModelHelper swimModel) { + m_isInitialized = true; + } + + @Override + public void dispose() { + if (m_adaptationEnqueuePort != null) { + m_adaptationEnqueuePort.dispose (); + } + if (m_modelChangePort != null) { + m_modelChangePort.dispose (); + } + + // null-out data members + m_model = null; + } + + @Override + protected void log(String txt) { + m_reportingPort.info (RainbowComponentT.ADAPTATION_MANAGER, txt); + } + + protected void error (String txt) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, txt); + } + + public void setAdaptationEnabled (boolean b) { + m_adaptationEnabled = b; + } + + public boolean adaptationInProgress () { + return m_adaptationNeeded; + } + + + @Override + public void markStrategyExecuted(AdaptationTree plan) { + AdaptationResultsVisitor v = new AdaptationResultsVisitor (plan); + plan.visit(v); + if (v.m_allOk) { + log("Finished adapting the system"); + } else { + log("Something in the adaptation plan failed to execute."); + } + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + m_executingPlan = false; + } + + + @Override + public void onEvent(ModelReference reference, IRainbowMessage message) { + // Because of the subscription, the model should be the model ref so no need to check + String typecheckSt = (String) message.getProperty (IModelChangeBusPort.PARAMETER_PROP + "0"); + Boolean typechecks = Boolean.valueOf (typecheckSt); + // Cause the thread to wake up if it is sleeping + if (!typechecks) { + activeThread ().interrupt (); + } + } + + + + + + @Override + public void setEnabled(boolean enabled) { + m_reportingPort.info (getComponentType (), + MessageFormat.format ("Turning adaptation {0}.", (enabled ? "on" : "off"))); + // if (!enabled && !m_pendingStrategies.isEmpty ()) { + // m_reportingPort.info (getComponentType (), "There is an adaptation in progress. This will finish."); + // } + // m_adaptEnabled = enabled; + } + + + @Override + public boolean isEnabled() { + return true; + } + + + private int adaptTestCt = 0; + @Override + protected void runAction() { + SwimExtendedPlan incDim = new IncDimmerPlan(m_model); + SwimExtendedPlan decDim = new DecDimmerPlan(m_model); + SwimExtendedPlan divTrf = new DivertTrafficPlan(m_model, "divert_100_0_0"); + SwimExtendedPlan addSev = new AddServerPlan(m_model, "2"); + SwimExtendedPlan remSev = new RemoveServerPlan(m_model, "2"); + AdaptationTree at = new AdaptationTree<>(AdaptationExecutionOperatorT.PARALLEL); + //at = at.addLeaf(incDim); at = at.getParent(); + //at = at.addLeaf(decDim); at = at.getParent(); + //at = at.addLeaf(divTrf); at = at.getParent(); + switch (adaptTestCt++){ + // case 0: + // at = at.addLeaf(addSev); at = at.getParent(); + // break; + // case 1: + // at = at.addLeaf(incDim); at = at.getParent(); + // break; + // case 2: + // at = at.addLeaf(incDim); at = at.getParent(); + // break; + // case 3: + // at = at.addLeaf(decDim); at = at.getParent(); + // break; + // case 4: + // at = at.addLeaf(remSev); at = at.getParent(); + // break; + // case 5: + // at = at.addLeaf(decDim); at = at.getParent(); + // break; + default: + at = at.addLeaf(decDim); at = at.getParent(); + at = at.addLeaf(incDim); at = at.getParent(); + break; + } + log(at.toString()); + log("New plan generated. Enqueueing..."); + m_adaptationEnqueuePort.offerAdaptation(at, new Object[0]); + m_executingPlan = true; + String logInfo = ""; + logInfo += "Load Balancer:\n"; + logInfo += "deploymentLocation: " + m_model.getModelInstance().getComponent("LB0").getProperty("deploymentLocation").getValue().toString(); + logInfo += "\ndimmer: " + m_model.getModelInstance().getComponent("LB0").getProperty("dimmer").getValue().toString(); + logInfo += "\narrivalRate: " + m_model.getModelInstance().getComponent("LB0").getProperty("arrivalRate").getValue().toString(); + logInfo += "\naverageResponseTime: " + m_model.getModelInstance().getComponent("LB0").getProperty("averageResponseTime").getValue().toString(); + logInfo += "\nServer 1:\n"; + logInfo += "traffic: " + m_model.getModelInstance().getComponent("server1").getProperty("traffic").getValue().toString(); + logInfo += "\nmax_arrival_capacity: " + m_model.getModelInstance().getComponent("server1").getProperty("max_arrival_capacity").getValue().toString(); + logInfo += "\nmax_arrival_capacity_low: " + m_model.getModelInstance().getComponent("server1").getProperty("max_arrival_capacity_low").getValue().toString(); + logInfo += "\nindex: " + m_model.getModelInstance().getComponent("server1").getProperty("index").getValue().toString(); + logInfo += "\nisActive: " + m_model.getModelInstance().getComponent("server1").getProperty("isActive").getValue().toString(); + logInfo += "\nexpectedActivationTime: " + m_model.getModelInstance().getComponent("server1").getProperty("expectedActivationTime").getValue().toString(); + logInfo += "\nreqServiceRate: " + m_model.getModelInstance().getComponent("server1").getProperty("reqServiceRate").getValue().toString(); + logInfo += "\nbyteServiceRate: " + m_model.getModelInstance().getComponent("server1").getProperty("byteServiceRate").getValue().toString(); + logInfo += "\ncost: " + m_model.getModelInstance().getComponent("server1").getProperty("cost").getValue().toString(); + logInfo += "\nServer 2:\n"; + logInfo += "traffic: " + m_model.getModelInstance().getComponent("server2").getProperty("traffic").getValue().toString(); + logInfo += "\nmax_arrival_capacity: " + m_model.getModelInstance().getComponent("server2").getProperty("max_arrival_capacity").getValue().toString(); + logInfo += "\nmax_arrival_capacity_low: " + m_model.getModelInstance().getComponent("server2").getProperty("max_arrival_capacity_low").getValue().toString(); + logInfo += "\nindex: " + m_model.getModelInstance().getComponent("server2").getProperty("index").getValue().toString(); + logInfo += "\nisActive: " + m_model.getModelInstance().getComponent("server2").getProperty("isActive").getValue().toString(); + logInfo += "\nexpectedActivationTime: " + m_model.getModelInstance().getComponent("server2").getProperty("expectedActivationTime").getValue().toString(); + logInfo += "\nreqServiceRate: " + m_model.getModelInstance().getComponent("server2").getProperty("reqServiceRate").getValue().toString(); + logInfo += "\nbyteServiceRate: " + m_model.getModelInstance().getComponent("server2").getProperty("byteServiceRate").getValue().toString(); + logInfo += "\ncost: " + m_model.getModelInstance().getComponent("server2").getProperty("cost").getValue().toString(); + logInfo += "\nServer 3:\n"; + logInfo += "traffic: " + m_model.getModelInstance().getComponent("server3").getProperty("traffic").getValue().toString(); + logInfo += "\nmax_arrival_capacity: " + m_model.getModelInstance().getComponent("server3").getProperty("max_arrival_capacity").getValue().toString(); + logInfo += "\nmax_arrival_capacity_low: " + m_model.getModelInstance().getComponent("server3").getProperty("max_arrival_capacity_low").getValue().toString(); + logInfo += "\nindex: " + m_model.getModelInstance().getComponent("server3").getProperty("index").getValue().toString(); + logInfo += "\nisActive: " + m_model.getModelInstance().getComponent("server3").getProperty("isActive").getValue().toString(); + logInfo += "\nexpectedActivationTime: " + m_model.getModelInstance().getComponent("server3").getProperty("expectedActivationTime").getValue().toString(); + logInfo += "\nreqServiceRate: " + m_model.getModelInstance().getComponent("server3").getProperty("reqServiceRate").getValue().toString(); + logInfo += "\nbyteServiceRate: " + m_model.getModelInstance().getComponent("server3").getProperty("byteServiceRate").getValue().toString(); + logInfo += "\ncost: " + m_model.getModelInstance().getComponent("server3").getProperty("cost").getValue().toString(); + String logInfoNew = ""; + logInfoNew += "Load Balancer:"; + logInfoNew += "\ndimmer: "; + + log(logInfo); + } + + private void strategyLog (String logMessage) { + if (m_strategyLog != null) { + Date d = new Date (); + String log = MessageFormat.format ("{0,number,#},queuing,{1}\n", d.getTime (), + logMessage); + try { + m_strategyLog.write (java.nio.ByteBuffer.wrap (log.getBytes ())); + } catch (IOException e) { + reportingPort ().error (getComponentType (), "Failed to write " + log + " to log file"); + } + } + } + + @Override + public RainbowComponentT getComponentType() { + return RainbowComponentT.ADAPTATION_MANAGER; + } + + + private class AdaptationResultsVisitor extends DefaultAdaptationTreeWalker { + + public AdaptationResultsVisitor (AdaptationTree adt) { + super (adt); + } + + boolean m_allOk = true; + + @Override + protected void evaluate (SwimExtendedPlan adaptation) { + m_allOk &= adaptation.getOutcome (); + } + + } + + +} + + + + + + + + + + diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerStrategyBased.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerStrategyBased.java new file mode 100644 index 000000000..b69661236 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerStrategyBased.java @@ -0,0 +1,225 @@ +package org.sa.rainbow.swim.adaptation; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.adaptation.AdaptationTree; +import org.sa.rainbow.model.acme.swim.SwimModelHelper; +import org.sa.rainbow.stitch.core.Strategy; +import org.sa.rainbow.stitch.visitor.Stitch; +import org.sa.rainbow.util.Util; + +import pladapt.EnvironmentDTMCPartitioned; + +public class AdaptationManagerStrategyBased extends AdaptationManagerBase { + private static final String NO_OP_STRATEGY = "NoOp"; + private static final String PRISM_TEMPLATE = "rainbow.adaptation.plasb.prismTemplate"; + private static final String PRISM_RESULT_PREFIX = "Result:"; + private static final String ENVIRONMENT_TAG = "//#environment"; + private static final String INIT_TAG = "//#init"; + + public AdaptationManagerStrategyBased() { + // TODO Auto-generated constructor stub + } + + protected void initializeAdaptationMgr(SwimModelHelper swimModel) { + log("Starting SB-PLA Adaptation Manager initialization"); + super.initializeAdaptationMgr(swimModel); + log("SB-PLA Adaptation Manager Initialized"); + } + + + /** + * Generates a complete PRISM model injecting the environment and the + * initialization sections + * + * @throws IOException + */ + protected File getPrismModelFile(String strategy, String initPRISM, String envPRISM) throws IOException { + File stitchPath = Util.getRelativeToPath(Rainbow.instance().getTargetPath(), + Rainbow.instance().getProperty(RainbowConstants.PROPKEY_SCRIPT_PATH)); + File templatePath = new File(stitchPath, Rainbow.instance().getProperty(PRISM_TEMPLATE)); + if (!templatePath.exists()) { + return null; + } + + File strategyModel = new File(stitchPath, strategy + ".prism"); + if (!strategyModel.exists()) { + return null; + } + + BufferedReader in = new BufferedReader(new FileReader(templatePath)); + File modelPath = new File(stitchPath, strategy + "-complete.prism"); + FileWriter out = new FileWriter(modelPath); + + String line; + while ((line = in.readLine()) != null) { + if (line.startsWith(ENVIRONMENT_TAG)) { + out.write(envPRISM); + } else if (line.startsWith(INIT_TAG)) { + out.write(initPRISM); + } else { + out.write(line); + } + out.write('\n'); + } + in.close(); + + // append strategy PRISM model + BufferedReader strategyIn = new BufferedReader(new FileReader(strategyModel)); + while ((line = strategyIn.readLine()) != null) { + out.write(line); + out.write('\n'); + } + strategyIn.close(); + + out.close(); + return modelPath; + } + + /** + * Invokes PRISM to evaluate a strategy + * @throws RuntimeException + */ + protected double evaluateStrategy(String strategy, String initPRISM, String envPRISM) throws RuntimeException { + boolean hasResult = false; + double result = 0; + try { + File modelPath = getPrismModelFile(strategy, initPRISM, envPRISM); + if (modelPath != null && modelPath.exists()) { + ArrayList command = new ArrayList(); + command.add("prism"); + command.add(modelPath.getPath()); + command.add("-pctl"); + command.add("R=? [ F \"final\" ]"); + command.add("-ex"); + String[] commandArray = command.toArray(new String[command.size()]); + Process p = Runtime.getRuntime().exec(commandArray); + BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); + String line; + while ((line = input.readLine()) != null) { + if (line.startsWith(PRISM_RESULT_PREFIX)) { + result = Double.parseDouble(line.substring(PRISM_RESULT_PREFIX.length()).trim().split(" ")[0]); + hasResult = true; + } + } + input.close(); + //modelPath.delete(); + } + } catch (Exception e) { + m_reportingPort.error(RainbowComponentT.ADAPTATION_MANAGER, e.toString()); + } + + if (!hasResult) { + throw new RuntimeException("Could not get value of strategy " + strategy); + } + + return result; + } + + protected AdaptationTree checkAdaptationImpl(SwimModelHelper swimModel, + EnvironmentDTMCPartitioned env) { + AdaptationTree at = null; + Map applicableStrategies = new HashMap (); + for (Stitch stitch : m_repertoire) { + if (!stitch.script.isApplicableForSystem (m_model)) { + m_reportingPort.trace (getComponentType (), "x. skipping " + stitch.script.getName ()); + continue; // skip checking this script + } + for (Strategy strategy : stitch.script.strategies) { + // check condition of Strategy applicability + if (strategy.isApplicable (new HashMap())) { + applicableStrategies.put (strategy.getName(), strategy); + } + } + } + if (applicableStrategies.size () == 0) { // can't do adaptation + log ("No applicable Strategies to do an adaptation!"); + return null; + } + + // add NoOp strategy + applicableStrategies.put(NO_OP_STRATEGY, null); + + String envPRISM = pladapt.PMCAdaptationManager.generateEnvironmentDTMC(env); + String init = generateInitBlock(swimModel); + + String bestStrategy = NO_OP_STRATEGY; // default to not adapting + double bestValue = -Double.MAX_VALUE; + for (String strategy : applicableStrategies.keySet()) { + double value = evaluateStrategy(strategy, init, envPRISM); + log("**** value of " + strategy + " = " + value); + if (value > bestValue) { + bestStrategy = strategy; + bestValue = value; + } + } + log("Selected strategy " + bestStrategy); + Strategy selectedStrategy = applicableStrategies.get(bestStrategy); + if (selectedStrategy != null) { // it's not NoOp + at = new AdaptationTree (selectedStrategy); + } + + return at; + } + + protected String generateInitBlock(SwimModelHelper swimModel) { + StringBuilder init = new StringBuilder(); + init.append("const int TAddServer_LATENCY = "); + init.append(swimModel.getAddServerLatencyPeriods()); + + init.append(";\nconst int HORIZON = "); + init.append(m_horizon); + + init.append(";\nconst double PERIOD = "); + double periodMsec = Double + .parseDouble(Rainbow.instance().getProperty(RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD)); + init.append(periodMsec / 1000); + + init.append(";\nconst int DIMMER_LEVELS = "); + init.append(swimModel.getDimmerLevels()); + + init.append(";\nconst double DIMMER_MARGIN = "); + init.append(swimModel.getDimmerMargin()); + + init.append(";\nconst int MAX_SERVERS = "); + init.append(swimModel.getMaxServers()); + + init.append(";\nconst double RT_THRESHOLD = "); + init.append(swimModel.getRTThreshold()); + + init.append(";\nconst int ini_servers = "); + init.append(swimModel.getNumActiveServers()); + + init.append(";\nconst int ini_dimmer = "); + init.append(swimModel.getCurrentDimmerLevel()); + + init.append(";\nconst double serviceTimeMean = "); + init.append(swimModel.getEstimatedOptServiceTime()); + + init.append(";\nconst double serviceTimeVariance = "); + init.append(swimModel.getEstimatedOptServiceTimeVariance()); + + init.append(";\nconst double lowServiceTimeMean = "); + init.append(swimModel.getEstimatedBasicServiceTime()); + + init.append(";\nconst double lowServiceTimeVariance = "); + init.append(swimModel.getEstimatedBasicServiceTimeVariance()); + + init.append(";\nconst int threads = "); + init.append(swimModel.getNumThreadsPerServer()); + init.append(";\n"); + return init.toString(); + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerTest.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerTest.java new file mode 100644 index 000000000..9604f0408 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AdaptationManagerTest.java @@ -0,0 +1,658 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.swim.adaptation; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import org.acmestudio.acme.element.IAcmeSystem; +import org.apache.commons.lang.time.StopWatch; +import org.sa.rainbow.core.AbstractRainbowRunnable; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.adaptation.AdaptationExecutionOperatorT; +import org.sa.rainbow.core.adaptation.AdaptationTree; +import org.sa.rainbow.core.adaptation.DefaultAdaptationTreeWalker; +import org.sa.rainbow.core.adaptation.IAdaptationManager; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.health.IRainbowHealthProtocol; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.UtilityFunction; +import org.sa.rainbow.core.models.UtilityPreferenceDescription; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IRainbowAdaptationEnqueuePort; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.AcmeRainbowOperationEvent.CommandEventT; +import org.sa.rainbow.stitch.Ohana; +import org.sa.rainbow.stitch.core.Strategy; +import org.sa.rainbow.stitch.core.Tactic; +import org.sa.rainbow.stitch.error.DummyStitchProblemHandler; +import org.sa.rainbow.stitch.error.IStitchProblem; +import org.sa.rainbow.stitch.error.StitchProblem; +import org.sa.rainbow.stitch.visitor.Stitch; +import org.sa.rainbow.util.Beacon; +import org.sa.rainbow.util.Util; + +/** + * PLA Adaptation Manager + * + * @author gmoreno + */ +public final class AdaptationManagerTest extends AbstractRainbowRunnable + implements IAdaptationManager, IRainbowModelChangeCallback { + + public enum Mode { + SERIAL, MULTI_PRONE + } + + public static final String NAME = "PLA Adaptation Manager"; + public static final double FAILURE_RATE_THRESHOLD = 0.95; + public static final double MIN_UTILITY_THRESHOLD = 0.40; + public static final long FAILURE_EFFECTIVE_WINDOW = 2000 /* ms */; + public static final long FAILURE_WINDOW_CHUNK = 1000 /* ms */; + + private Mode m_mode = Mode.SERIAL; + private AcmeModelInstance m_model = null; + private boolean m_adaptNeeded = false; // treat as synonymous with + // constraint being violated + private boolean m_adaptEnabled = true; // by default, we adapt + private List m_repertoire = null; + private List> m_pendingStrategies = null; + + // track history + private String m_historyTrackUtilName = null; + private Map m_historyCnt = null; + private Map m_failTimer = null; + private IRainbowAdaptationEnqueuePort m_enqueuePort = null; + private IModelChangeBusSubscriberPort m_modelChangePort = null; + private IModelsManagerPort m_modelsManagerPort = null; + private String m_modelRef; + private FileChannel m_strategyLog = null; + private IRainbowChangeBusSubscription m_modelTypecheckingChanged = new IRainbowChangeBusSubscription () { + + @Override + public boolean matches (IRainbowMessage message) { + String type = (String) message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); + String modelName = (String) message.getProperty (IModelChangeBusPort.MODEL_NAME_PROP); + String modelType = (String) message.getProperty (IModelChangeBusPort.MODEL_TYPE_PROP); + try { + CommandEventT ct = CommandEventT.valueOf (type); + return (ct.isEnd () + && "setTypecheckResult".equals (message.getProperty (IModelChangeBusPort.COMMAND_PROP)) + && m_modelRef.equals (Util.genModelRef (modelName, modelType))); + } catch (Exception e) { + return false; + } + } + }; + private UtilityPreferenceDescription m_utilityModel; + + /** + * Default constructor. + */ + public AdaptationManagerTest () { + super (NAME); + + m_repertoire = new ArrayList (); + m_pendingStrategies = new ArrayList> (); + m_historyTrackUtilName = Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_TRACK_STRATEGY); + if (m_historyTrackUtilName != null) { + m_historyCnt = new HashMap (); + m_failTimer = new HashMap (); + } + + //setSleepTime (SLEEP_TIME); + String per = Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (per != null) { + setSleepTime (Long.parseLong (per)); + } else { // default to using the long sleep value + setSleepTime (IRainbowRunnable.LONG_SLEEP_TIME); + } + } + + @Override + public void initialize (IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize (port); + initConnectors (); + + } + + private void initConnectors () throws RainbowConnectionException { + m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort (); + m_modelChangePort.subscribe (m_modelTypecheckingChanged, this); + m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort (); + } + + @Override + public void setModelToManage (ModelReference model) { + m_modelRef = model.getModelName () + ":" + model.getModelType (); + try { + m_strategyLog = new FileOutputStream (new File (new File (Rainbow.instance ().getTargetPath (), "log"), + model.getModelName () + "-adaptation.log")).getChannel (); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace (); + } + m_model = (AcmeModelInstance) m_modelsManagerPort.getModelInstance (model); + if (m_model == null) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, + MessageFormat.format ("Could not find reference to {0}", model.toString ())); + } + m_enqueuePort = RainbowPortFactory.createAdaptationEnqueuePort (model); + ModelReference utilityModelRef = new ModelReference (model.getModelName (), "UtilityModel"); + IModelInstance modelInstance = m_modelsManagerPort + .getModelInstance (utilityModelRef); + if (modelInstance == null) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, + MessageFormat.format ( + "There is no utility model associated with this model. Expecting to find " + + "''{0}''. Perhaps it is not specified in the rainbow.properties " + + "file?", + utilityModelRef.toString ())); + + } else { + m_utilityModel = modelInstance.getModelInstance (); + } + + initAdaptationRepertoire (); + } + + /* + * (non-Javadoc) + * + * @see org.sa.rainbow.core.IDisposable#dispose() + */ + @Override + public void dispose () { + for (Stitch stitch : m_repertoire) { + stitch.dispose (); + } + Ohana.instance ().dispose (); + m_repertoire.clear (); + m_pendingStrategies.clear (); + if (m_historyTrackUtilName != null) { + m_historyCnt.clear (); + m_failTimer.clear (); + m_historyCnt = null; + m_failTimer = null; + } + + if (m_enqueuePort != null) { + m_enqueuePort.dispose (); + } + m_modelChangePort.dispose (); + + // null-out data members + m_repertoire = null; + m_pendingStrategies = null; + m_historyTrackUtilName = null; + m_model = null; + if (m_strategyLog != null) { + try { + m_strategyLog.close (); + } catch (IOException ignored) { + } + m_strategyLog = null; + } + } + + @Override + protected void doTerminate () { + if (m_strategyLog != null) { + try { + m_strategyLog.close (); + } catch (IOException ignore) { + } + m_strategyLog = null; + } + super.doTerminate (); + } + + protected void finalize() { + if (m_strategyLog != null) { + try { + m_strategyLog.close (); + } catch (IOException ignore) { + } + m_strategyLog = null; + } + } + + /* + * (non-Javadoc) + * + * @see org.sa.rainbow.core.AbstractRainbowRunnable#log(java.lang.String) + */ + @Override + protected void log (String txt) { + m_reportingPort.info (RainbowComponentT.ADAPTATION_MANAGER, txt); + } + + @Override + public boolean isEnabled () { + return m_adaptEnabled; + } + + public void setAdaptationEnabled (boolean b) { + m_adaptEnabled = b; + } + + public boolean adaptationInProgress () { + return m_adaptNeeded; + } + + /** + * Removes a Strategy from the list of pending strategies, marking it as being completed (doesn't incorporate + * outcome). + * + * @param strategy the strategy to mark as being executed. + */ + @Override + public void markStrategyExecuted (AdaptationTree strategy) { + if (m_pendingStrategies.contains (strategy)) { + m_pendingStrategies.remove (strategy); + final List strategiesExecuted = new LinkedList<> (); + StrategyAdaptationResultsVisitor resultCollector = new StrategyAdaptationResultsVisitor + (strategy, strategiesExecuted); + strategy.visit (resultCollector); + + for (Strategy str : strategiesExecuted) { + String s = str.getName () + ";" + str.outcome (); + log ("*S* outcome: " + s); + Util.dataLogger ().info (IRainbowHealthProtocol.DATA_ADAPTATION_STRATEGY + s); + tallyStrategyOutcome (str); + } + + } + if (m_pendingStrategies.size () == 0) { + Util.dataLogger ().info (IRainbowHealthProtocol.DATA_ADAPTATION_END); + // reset adaptation flags + m_adaptNeeded = false; +// m_model.clearConstraintViolated (); + } + } + + /** + * Computes instantaneous utility of target system given current conditions. + * + * @return double the instantaneous utility of current conditions + */ + public double computeSystemInstantUtility () { + Map weights = m_utilityModel.weights + .get (Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_SCENARIO)); + double[] conds = new double[m_utilityModel.getUtilityFunctions ().size ()]; + int i = 0; + double score = 0.0; + for (String k : new ArrayList (m_utilityModel.getUtilityFunctions ().keySet ())) { + double v = 0.0; + // find the applicable utility function + UtilityFunction u = m_utilityModel.getUtilityFunctions ().get (k); + // add attribute value from current condition to accumulated agg + // value + Object condVal = m_model.getProperty (u.mapping ()); + if (condVal != null) { + double val = 0.0; + if (condVal instanceof Double) { + val = (Double) condVal; + } else if (condVal instanceof Float) { + val = ((Float) condVal).doubleValue (); + } else if (condVal instanceof Integer) { + val = ((Integer) condVal).doubleValue (); + } + m_reportingPort.trace (getComponentType (), "Avg value of prop: " + u.mapping () + " == " + condVal); + conds[i] = val; + v += conds[i]; + } + // now compute the utility, apply weight, and accumulate to sum + if (weights.containsKey (k)) { // but only if weight is defined + score += weights.get (k) * u.f (v); + } + } + return score; + } + + /* + * (non-Javadoc) + * + * @see org.sa.rainbow.core.AbstractRainbowRunnable#runAction() + */ + @Override + protected void runAction () { + if (m_adaptEnabled) { + if (m_mode == Mode.SERIAL && m_pendingStrategies.size () > 0) + // Only go if there are no pending strategies + return; + Util.dataLogger ().info (IRainbowHealthProtocol.DATA_ADAPTATION_SELECTION_BEGIN); + AdaptationTree at = checkAdaptation (); + Util.dataLogger ().info (IRainbowHealthProtocol.DATA_ADAPTATION_SELECTION_END); + if (at != null) { + //log (">> do strategy: " + at); + m_pendingStrategies.add (at); + m_enqueuePort.offerAdaptation (at, null); + String logMessage = at.toString (); + strategyLog(logMessage); + } + } + } + + private void strategyLog (String logMessage) { + if (m_strategyLog != null) { + Date d = new Date (); + String log = MessageFormat.format ("{0,number,#},queuing,{1}\n", d.getTime (), + logMessage); + try { + m_strategyLog.write (java.nio.ByteBuffer.wrap (log.getBytes ())); + } catch (IOException e) { + reportingPort ().error (getComponentType (), "Failed to write " + log + " to log file"); + } + } + } + + /** + * For JUnit testing, used to set a stopwatch object used to time duration. + */ + StopWatch _stopWatchForTesting = null; + + /** + * For JUnit testing, allows fetching the strategy repertoire. NOT for public use! + * + * @return list of Stitch objects loaded at initialization from stitch file. + */ + List _retrieveRepertoireForTesting () { + return m_repertoire; + } + + /** + * For JUnit testing, allows fetching the utility objects. NOT for public use! + * + * @return map of utility identifiers to functions. + */ + Map _retrieveUtilityProfilesForTesting () { + return m_utilityModel.getUtilityFunctions (); + } + + /** + * For JUnit testing, allows re-invoking defineAttributes to artificially increase the number of quality dimensions + * in tactic attribute vectors. + */ + void _defineAttributesFromTester (Stitch stitch, Map> attrVectorMap) { + defineAttributes (stitch, attrVectorMap); + } + + private Strategy getStrategy(String name) { + Strategy strategy = null; + for (Stitch stitch : m_repertoire) { + if (!stitch.script.isApplicableForSystem (m_model)) { + m_reportingPort.trace (getComponentType (), "x. skipping " + stitch.script.getName ()); + continue; // skip checking this script + } + for (Strategy t : stitch.script.strategies) { + if (t.getName().equals(name)) { + strategy = t; + break; + } + } + } + + if (strategy == null) { + m_reportingPort.error(RainbowComponentT.ADAPTATION_MANAGER, + "Script for strategy ''" + name + "'' not found"); + } + return strategy; + } + + private AdaptationTree checkAdaptation () { + AdaptationTree at = null; + log ("Checking if adaptation is required."); + if (_stopWatchForTesting != null) { + _stopWatchForTesting.start (); + } + +// at = new AdaptationTree(getStrategy("RemoveServer")); + Vector tactics = new Vector(); + tactics.add("IncDimmer"); + tactics.add("RemoveServer"); + at = new AdaptationTree(AdaptationExecutionOperatorT.PARALLEL); + for (int t = 0; t < tactics.size(); t++) { + log(tactics.get(t)); + Strategy strategy = getStrategy(tactics.get(t));// Strategy has tactic name + at.addLeaf(strategy); + } + + if (_stopWatchForTesting != null) { + _stopWatchForTesting.stop (); + } + return at; + } + + /** + * Retrieves the adaptation repertoire; for each tactic, store the respective tactic attribute vectors. + */ + private void initAdaptationRepertoire () { + File stitchPath = Util.getRelativeToPath (Rainbow.instance ().getTargetPath (), + Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_SCRIPT_PATH)); + if (stitchPath == null) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, "The stitch path is not set!"); + } else if (stitchPath.exists () && stitchPath.isDirectory ()) { + FilenameFilter ff = new FilenameFilter () { // find only ".s" files + @Override + public boolean accept (File dir, String name) { + return name.endsWith (".s"); + } + }; + for (File f : stitchPath.listFiles (ff)) { + try { + + // don't load .t.s files: these are tactics imported from .s files + if (f.getName().endsWith(".t.s")) { + continue; + } + // don't duplicate loading of script files + Stitch stitch = Ohana.instance ().findStitch (f.getCanonicalPath ()); + if (stitch == null) { + DummyStitchProblemHandler stitchProblemHandler = new DummyStitchProblemHandler (); + stitch = Stitch.newInstance (f.getCanonicalPath (), stitchProblemHandler); + Ohana.instance ().parseFile (stitch); +// StitchTypechecker behavior = (StitchTypechecker )stitch.getBehavior (Stitch.TYPECHECKER_PASS); + + reportProblems (f, stitchProblemHandler); + + // apply attribute vectors to tactics, if available + defineAttributes (stitch, m_utilityModel.attributeVectors); + m_repertoire.add (stitch); + log ("Parsed script " + stitch.path); + } else { + log ("Previously known script " + stitch.path); + } + } catch (IOException e) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, + "Obtaining file canonical path failed! " + f.getName (), e); + } + } + } + } + + private void reportProblems (File f, DummyStitchProblemHandler sph) { + + Collection problem = sph.getProblems (); + if (!problem.isEmpty ()) { + log ("Errors exist in strategy: " + f.getName () + ", or one of its included files"); + } + for (IStitchProblem p : problem) { + StringBuilder out = new StringBuilder (); + switch (p.getSeverity ()) { + case StitchProblem.ERROR: + out.append ("ERROR: "); + break; + case StitchProblem.WARNING: + out.append ("WARNING: "); + break; + case StitchProblem.FATAL: + out.append ("FATAL ERROR: "); + break; + case StitchProblem.UNKNOWN: + out.append ("UNKNOWN PROBLEM: "); + break; + } + out.append ("Line: ").append (p.getLine ()); + out.append (", "); + out.append (" Column: ").append (p.getColumn ()); + out.append (": ").append (p.getMessage ()); + log (out.toString ()); + } + sph.clearProblems (); + } + + private void defineAttributes (Stitch stitch, Map> attrVectorMap) { + for (Tactic t : stitch.script.tactics) { + Map attributes = attrVectorMap.get (t.getName ()); + if (attributes != null) { + // found attribute def for tactic, save all key-value pairs + m_reportingPort.trace (getComponentType (), + "Found attributes for tactic " + t.getName () + ", saving pairs..."); + for (Map.Entry e : attributes.entrySet ()) { + t.putAttribute (e.getKey (), e.getValue ()); + m_reportingPort.trace (getComponentType (), " - (" + e.getKey () + ", " + e.getValue () + ")"); + } + } + } + } + + private static final int I_RUN = 0; + private static final int I_SUCCESS = 1; + private static final int I_FAIL = 2; + private static final int I_OTHER = 3; + private static final int CNT_I = 4; + + private void tallyStrategyOutcome (Strategy s) { + if (m_historyTrackUtilName == null) return; + + String name = s.getName (); + // mark timer of failure, if applicable + Beacon timer = m_failTimer.get (name); + if (timer == null) { + timer = new Beacon (); + m_failTimer.put (name, timer); + } + // get the stats array for this strategy + int[] stat = m_historyCnt.get (name); + if (stat == null) { + stat = new int[CNT_I]; + stat[I_RUN] = 0; + stat[I_SUCCESS] = 0; + stat[I_FAIL] = 0; + stat[I_OTHER] = 0; + m_historyCnt.put (name, stat); + } + // tally outcome counts + ++stat[I_RUN]; + switch (s.outcome ()) { + case SUCCESS: + ++stat[I_SUCCESS]; + break; + case FAILURE: + ++stat[I_FAIL]; + timer.mark (); + break; + default: + ++stat[I_OTHER]; + break; + } + String str = name + Arrays.toString (stat); + log ("History: " + str); + Util.dataLogger ().info (IRainbowHealthProtocol.DATA_ADAPTATION_STAT + str); + } + + + @Override + public void onEvent (ModelReference mr, IRainbowMessage message) { + // Because of the subscription, the model should be the model ref so no need to check + String typecheckSt = (String) message.getProperty (IModelChangeBusPort.PARAMETER_PROP + "0"); + Boolean typechecks = Boolean.valueOf (typecheckSt); + // Cause the thread to wake up if it is sleeping + if (!typechecks) { + activeThread ().interrupt (); + } + } + + @Override + public RainbowComponentT getComponentType () { + return RainbowComponentT.ADAPTATION_MANAGER; + } + + @Override + public void setEnabled (boolean enabled) { + m_reportingPort.info (getComponentType (), + MessageFormat.format ("Turning adaptation {0}.", (enabled ? "on" : "off"))); + if (!enabled && !m_pendingStrategies.isEmpty ()) { + m_reportingPort.info (getComponentType (), "There is an adaptation in progress. This will finish."); + } + m_adaptEnabled = enabled; + } + + private class StrategyAdaptationResultsVisitor extends DefaultAdaptationTreeWalker { + private final List m_strategiesExecuted; + + public StrategyAdaptationResultsVisitor (AdaptationTree strategy, + List strategiesExecuted) { + super (strategy); + m_strategiesExecuted = strategiesExecuted; + } + + @Override + protected void evaluate (Strategy adaptation) { + if (adaptation.outcome () != Strategy.Outcome.UNKNOWN) { + synchronized (m_strategiesExecuted) { + m_strategiesExecuted.add (adaptation); + } + } + } + + + } +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AddServerPlan.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AddServerPlan.java new file mode 100644 index 000000000..b1f10fe97 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/AddServerPlan.java @@ -0,0 +1,51 @@ +package org.sa.rainbow.swim.adaptation; + +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.swim.commands.AddServerWithTypeCmd; +import org.sa.rainbow.model.acme.swim.commands.SwimCommandFactory; + +public class AddServerPlan extends SwimExtendedPlan { + + private String m_server; + private boolean m_outcome; + private IModelsManagerPort m_modelsManager; + + //private SwimModelUpdateOperatorsImpl m_model; + private AcmeModelInstance m_reference; + + // server is either 1, 2, or 3 + public AddServerPlan (AcmeModelInstance m, String server) { + m_reference = m; + m_server = server; + } + + @Override + public Object evaluate(Object[] argsIn) { + IAdaptationExecutor executor = + Rainbow.instance().getRainbowMaster().strategyExecutor + (m_reference.getModelName() + ":" + m_reference.getModelType()); + SwimCommandFactory cf = (SwimCommandFactory) m_reference.getCommandFactory(); + AddServerWithTypeCmd cmd = cf.addServerWithTypeCmd(m_reference.getModelInstance().getComponent("LB0"), m_server); + System.out.println ("Changing Instructions inside AddServerPlan"); + if (executor == null) { + System.out.println("executor null"); return false; + } + else { + OperationResult result = executor.getOperationPublishingPort().publishOperation(cmd); + m_outcome = result.result == Result.SUCCESS; + System.out.println ("Done: " + m_outcome); + return m_outcome; } + } + + @Override + public boolean getOutcome() { + // TODO Auto-generated method stub + return m_outcome; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/DecDimmerPlan.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/DecDimmerPlan.java new file mode 100644 index 000000000..ecfced628 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/DecDimmerPlan.java @@ -0,0 +1,51 @@ +package org.sa.rainbow.swim.adaptation; + +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.swim.commands.DecDimmerCmd; +import org.sa.rainbow.model.acme.swim.commands.SwimCommandFactory; + +public class DecDimmerPlan extends SwimExtendedPlan { + + private boolean m_outcome; + private IModelsManagerPort m_modelsManager; + + //private SwimModelUpdateOperatorsImpl m_model; + private AcmeModelInstance m_reference; + + public DecDimmerPlan (AcmeModelInstance m) { + //m_instructionGraph = instructionGraph; + m_reference = m; + + } + + @Override + public Object evaluate(Object[] argsIn) { + IAdaptationExecutor executor = + Rainbow.instance().getRainbowMaster().strategyExecutor + (m_reference.getModelName() + ":" + m_reference.getModelType()); + SwimCommandFactory cf = (SwimCommandFactory) m_reference.getCommandFactory(); + DecDimmerCmd cmd = cf.decDimmerCmd(m_reference.getModelInstance().getComponent("LB0")); + System.out.println ("Changing Instructions"); + if (executor == null) { + System.out.println("executor null"); return false; + } + else { + OperationResult result = executor.getOperationPublishingPort().publishOperation(cmd); + m_outcome = result.result == Result.SUCCESS; + System.out.println ("Done: " + m_outcome); + return m_outcome; } + } + + @Override + public boolean getOutcome() { + // TODO Auto-generated method stub + return m_outcome; + } + +} + diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/DivertTrafficPlan.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/DivertTrafficPlan.java new file mode 100644 index 000000000..5004ddcc9 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/DivertTrafficPlan.java @@ -0,0 +1,51 @@ +package org.sa.rainbow.swim.adaptation; + +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.swim.commands.DivertTrafficCmd; +import org.sa.rainbow.model.acme.swim.commands.SwimCommandFactory; + +public class DivertTrafficPlan extends SwimExtendedPlan { + + private String m_divertCommand; + private boolean m_outcome; + private IModelsManagerPort m_modelsManager; + + //private SwimModelUpdateOperatorsImpl m_model; + private AcmeModelInstance m_reference; + + public DivertTrafficPlan (AcmeModelInstance m, String divertCommand) { + //m_instructionGraph = instructionGraph; + m_reference = m; + m_divertCommand = divertCommand; + } + + @Override + public Object evaluate(Object[] argsIn) { + IAdaptationExecutor executor = + Rainbow.instance().getRainbowMaster().strategyExecutor + (m_reference.getModelName() + ":" + m_reference.getModelType()); + SwimCommandFactory cf = (SwimCommandFactory) m_reference.getCommandFactory(); + DivertTrafficCmd cmd = cf.divertTrafficCmd(m_reference.getModelInstance().getComponent("LB0"), m_divertCommand); + System.out.println ("Changing Instructions"); + if (executor == null) { + System.out.println("executor null"); return false; + } + else { + OperationResult result = executor.getOperationPublishingPort().publishOperation(cmd); + m_outcome = result.result == Result.SUCCESS; + System.out.println ("Done: " + m_outcome); + return m_outcome; } + } + + @Override + public boolean getOutcome() { + // TODO Auto-generated method stub + return m_outcome; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/HPAdaptationManager.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/HPAdaptationManager.java new file mode 100644 index 000000000..5f1901661 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/HPAdaptationManager.java @@ -0,0 +1,1520 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.swim.adaptation; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.apache.commons.lang.time.StopWatch; +import org.sa.rainbow.core.AbstractRainbowRunnable; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.adaptation.AdaptationExecutionOperatorT; +import org.sa.rainbow.core.adaptation.AdaptationTree; +import org.sa.rainbow.core.adaptation.DefaultAdaptationTreeWalker; +import org.sa.rainbow.core.adaptation.IAdaptationManager; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.health.IRainbowHealthProtocol; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.UtilityFunction; +import org.sa.rainbow.core.models.UtilityPreferenceDescription; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IRainbowAdaptationEnqueuePort; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.AcmeRainbowOperationEvent.CommandEventT; +import org.sa.rainbow.model.acme.swim.SwimModelHelper; +import org.sa.rainbow.timeseriespredictor.model.TimeSeriesPredictorModel; +import org.sa.rainbow.timeseriespredictor.model.TimeSeriesPredictorModelInstance; +import org.sa.rainbow.util.Beacon; +import org.sa.rainbow.util.Util; + +import pladapt.AdaptationPlanner; +import pladapt.EnvironmentDTMCPartitioned; +import pladapt.PMCAdaptationManager; +import pladapt.PlanDB; +import pladapt.StringVector; + + +public final class HPAdaptationManager extends AbstractRainbowRunnable + implements IAdaptationManager, IRainbowModelChangeCallback { + + static { + System.loadLibrary("pladapt_wrap"); + } + + public static final String NAME = "Swim Extended Adaptation Manager"; + private static final String TSP_MODEL = "ArrivalRate"; + + // The thread "sleep" time. runAction will be called every 60 seconds in this case + public static final int SLEEP_TIME = 60000 /*ms*/; + + // Port to query with any models in models manager + private IModelsManagerPort m_modelsManagerPort; + private IModelChangeBusSubscriberPort m_modelChangePort; + private ModelReference m_modelRef; + private IRainbowAdaptationEnqueuePort m_adaptationEnqueuePort; + private boolean m_adaptationEnabled = true; + private boolean m_adaptationNeeded = false; + private boolean m_errorDetected = false; + private FileChannel m_strategyLog = null; + private boolean m_executingPlan = false; + + protected AcmeModelInstance m_model = null; + + protected boolean m_isInitialized = false; + + protected int m_horizon; + protected int m_currentTime; + private TimeSeriesPredictorModelInstance m_tspModel; + private PMCAdaptationManager m_adaptMgr; + private PlanDB m_planDB; + //private boolean startServerC; + //private AdaptationPlanner m_adaptPlanner; + + + private IRainbowChangeBusSubscription m_modelTypecheckingChanged = new IRainbowChangeBusSubscription () { + + @Override + public boolean matches (IRainbowMessage message) { + String type = (String) message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); + String modelName = (String) message.getProperty (IModelChangeBusPort.MODEL_NAME_PROP); + String modelType = (String) message.getProperty (IModelChangeBusPort.MODEL_TYPE_PROP); + try { + CommandEventT ct = CommandEventT.valueOf (type); + return (ct.isEnd () + && "setTypecheckResult".equals (message.getProperty (IModelChangeBusPort.COMMAND_PROP)) + && m_modelRef.equals (Util.genModelRef (modelName, modelType))); + } catch (Exception e) { + return false; + } + } + }; + + public HPAdaptationManager () { + super (NAME); + //startServerC = true; + String per = Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (per != null) { + setSleepTime (Long.parseLong (per)); + } + else { + setSleepTime (SLEEP_TIME); + } + } + + @Override + public void initialize (IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize(port); + initConnectors (); + } + + private void initConnectors () throws RainbowConnectionException { + // Create port to query models manager + m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort (); + m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort (); + m_modelChangePort.subscribe (m_modelTypecheckingChanged, this); + } + + @Override + public void setModelToManage(ModelReference modelRef) { + m_modelRef = modelRef; + try { + m_strategyLog = new FileOutputStream (new File (new File (Rainbow.instance ().getTargetPath (), "log"), + modelRef.getModelName () + "-adaptation.log")).getChannel (); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + m_model = (AcmeModelInstance) m_modelsManagerPort.getModelInstance (modelRef); + if (m_model == null) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, + MessageFormat.format ("Could not find reference to {0}", modelRef.toString ())); + } + m_adaptationEnqueuePort = RainbowPortFactory.createAdaptationEnqueuePort (modelRef); + SwimModelHelper swimModel = new SwimModelHelper(m_model); + if (!m_isInitialized) { + initializeAdaptationMgr(swimModel); + } + } + + //Debugging use only + String init_state_r = "const double addServer_LATENCY = 120;\n" + + "const int HORIZON = 5;\n" + + "const double PERIOD = 60;\n" + + "const int DIMMER_LEVELS = 3;\n" + + "const int ini_dimmer = 2;\n" + + "const int MAX_SERVERS_A = 1;\n" + + "const int MAX_SERVERS_B = 1;\n" + + "const int MAX_SERVERS_C = 1;\n" + + "const int ini_servers_A = 1;\n" + + "const int ini_servers_B = 1;\n" + + "const int ini_servers_C = 1;\n" + + "const int ini_addServerA_state = 0;\n" + + "const int ini_addServerB_state = 0;\n" + + "const int ini_addServerC_state = 0;\n" + + "const double SERVERA_COST_SEC = 1;\n" + + "const double SERVERB_COST_SEC = 0.7;\n" + + "const double SERVERC_COST_SEC = 0.5;\n" + + "const double MAX_ARRIVALA_CAPACITY = 200;\n" + + "const double MAX_ARRIVALA_CAPACITY_LOW = 400;\n" + + "const double MAX_ARRIVALB_CAPACITY = 140;\n" + + "const double MAX_ARRIVALB_CAPACITY_LOW = 280;\n" + + "const double MAX_ARRIVALC_CAPACITY = 100;\n" + + "const double MAX_ARRIVALC_CAPACITY_LOW = 200;\n" + + "const double penalty = -0.25;\n" + + "const int ini_traffic_A = 2;\n" + + "const int ini_traffic_B = 1;\n" + + "const int ini_traffic_C = 1;\n" + + "const double interArrivalScaleFactorForDecision = 1;"; + String env_mod_r = "formula stateValue = 0.00180519;"; + String init_state_d = "const double addServer_LATENCY = 120;\n" + + "const int HORIZON = 5;\n" + + "const double PERIOD = 60;\n" + + "const int DIMMER_LEVELS = 3;\n" + + "const int ini_dimmer = 1;\n" + + "const int MAX_SERVERS_A = 1;\n" + + "const int MAX_SERVERS_B = 1;\n" + + "const int MAX_SERVERS_C = 1;\n" + + "const int ini_servers_A = 1;\n" + + "const int ini_servers_B = 0;\n" + + "const int ini_servers_C = 0;\n" + + "const int ini_addServerA_state = 0;\n" + + "const int ini_addServerB_state = 0;\n" + + "const int ini_addServerC_state = 0;\n" + + "const double SERVERA_COST_SEC = 1;\n" + + "const double SERVERB_COST_SEC = 0.7;\n" + + "const double SERVERC_COST_SEC = 0.5;\n" + + "const double MAX_ARRIVALA_CAPACITY = 200;\n" + + "const double MAX_ARRIVALA_CAPACITY_LOW = 400;\n" + + "const double MAX_ARRIVALB_CAPACITY = 140;\n" + + "const double MAX_ARRIVALB_CAPACITY_LOW = 280;\n" + + "const double MAX_ARRIVALC_CAPACITY = 100;\n" + + "const double MAX_ARRIVALC_CAPACITY_LOW = 200;\n" + + "const double penalty = -0.25;\n" + + "const int ini_traffic_A = 4;\n" + + "const int ini_traffic_B = 0;\n" + + "const int ini_traffic_C = 0;\n" + + "const double interArrivalScaleFactorForDecision = 1;"; + String env_mod_d = "module environment\n" + + "s : [0..201] init 0;\n" + + "[tick] s = 0 -> \n" + + " 0.185 : (s' = 1)\n" + + " + 0.63 : (s' = 2)\n" + + " + 0.185 : (s' = 3);\n" + + "[tick] s = 3 -> \n" + + " 0.185 : (s' = 4)\n" + + " + 0.63 : (s' = 5)\n" + + " + 0.185 : (s' = 6);\n" + + "[tick] s = 6 -> \n" + + " 0.185 : (s' = 7)\n" + + " + 0.63 : (s' = 8)\n" + + " + 0.185 : (s' = 9);\n" + + "[tick] s = 9 -> \n" + + " 0.185 : (s' = 10)\n" + + " + 0.63 : (s' = 11)\n" + + " + 0.185 : (s' = 12);\n" + + "[tick] s = 12 -> \n" + + " 1 : (s' = 13);\n" + + "[tick] s = 11 -> \n" + + " 1 : (s' = 14);\n" + + "[tick] s = 10 -> \n" + + " 1 : (s' = 15);\n" + + "[tick] s = 8 -> \n" + + " 0.185 : (s' = 16)\n" + + " + 0.63 : (s' = 17)\n" + + " + 0.185 : (s' = 18);\n" + + "[tick] s = 18 -> \n" + + " 1 : (s' = 19);\n" + + "[tick] s = 17 -> \n" + + " 1 : (s' = 20);\n" + + "[tick] s = 16 -> \n" + + " 1 : (s' = 21);\n" + + "[tick] s = 7 -> \n" + + " 0.185 : (s' = 22)\n" + + " + 0.63 : (s' = 23)\n" + + " + 0.185 : (s' = 24);\n" + + "[tick] s = 24 -> \n" + + " 1 : (s' = 25);\n" + + "[tick] s = 23 -> \n" + + " 1 : (s' = 26);\n" + + "[tick] s = 22 -> \n" + + " 1 : (s' = 27);\n" + + "[tick] s = 5 -> \n" + + " 0.185 : (s' = 28)\n" + + " + 0.63 : (s' = 29)\n" + + " + 0.185 : (s' = 30);\n" + + "[tick] s = 30 -> \n" + + " 0.185 : (s' = 31)\n" + + " + 0.63 : (s' = 32)\n" + + " + 0.185 : (s' = 33);\n" + + "[tick] s = 33 -> \n" + + " 1 : (s' = 34);\n" + + "[tick] s = 32 -> \n" + + " 1 : (s' = 35);\n" + + "[tick] s = 31 -> \n" + + " 1 : (s' = 36);\n" + + "[tick] s = 29 -> \n" + + " 0.185 : (s' = 37)\n" + + " + 0.63 : (s' = 38)\n" + + " + 0.185 : (s' = 39);\n" + + "[tick] s = 39 -> \n" + + " 1 : (s' = 40);\n" + + "[tick] s = 38 -> \n" + + " 1 : (s' = 41);\n" + + "[tick] s = 37 -> \n" + + " 1 : (s' = 42);\n" + + "[tick] s = 28 -> \n" + + " 0.185 : (s' = 43)\n" + + " + 0.63 : (s' = 44)\n" + + " + 0.185 : (s' = 45);\n" + + "[tick] s = 45 -> \n" + + " 1 : (s' = 46);\n" + + "[tick] s = 44 -> \n" + + " 1 : (s' = 47);\n" + + "[tick] s = 43 -> \n" + + " 1 : (s' = 48);\n" + + "[tick] s = 4 -> \n" + + " 0.185 : (s' = 49)\n" + + " + 0.63 : (s' = 50)\n" + + " + 0.185 : (s' = 51);\n" + + "[tick] s = 51 -> \n" + + " 0.185 : (s' = 52)\n" + + " + 0.63 : (s' = 53)\n" + + " + 0.185 : (s' = 54);\n" + + "[tick] s = 54 -> \n" + + " 1 : (s' = 55);\n" + + "[tick] s = 53 -> \n" + + " 1 : (s' = 56);\n" + + "[tick] s = 52 -> \n" + + " 1 : (s' = 57);\n" + + "[tick] s = 50 -> \n" + + " 0.185 : (s' = 58)\n" + + " + 0.63 : (s' = 59)\n" + + " + 0.185 : (s' = 60);\n" + + "[tick] s = 60 -> \n" + + " 1 : (s' = 61);\n" + + "[tick] s = 59 -> \n" + + " 1 : (s' = 62);\n" + + "[tick] s = 58 -> \n" + + " 1 : (s' = 63);\n" + + "[tick] s = 49 -> \n" + + " 0.185 : (s' = 64)\n" + + " + 0.63 : (s' = 65)\n" + + " + 0.185 : (s' = 66);\n" + + "[tick] s = 66 -> \n" + + " 1 : (s' = 67);\n" + + "[tick] s = 65 -> \n" + + " 1 : (s' = 68);\n" + + "[tick] s = 64 -> \n" + + " 1 : (s' = 69);\n" + + "[tick] s = 2 -> \n" + + " 0.185 : (s' = 70)\n" + + " + 0.63 : (s' = 71)\n" + + " + 0.185 : (s' = 72);\n" + + "[tick] s = 72 -> \n" + + " 0.185 : (s' = 73)\n" + + " + 0.63 : (s' = 74)\n" + + " + 0.185 : (s' = 75);\n" + + "[tick] s = 75 -> \n" + + " 0.185 : (s' = 76)\n" + + " + 0.63 : (s' = 77)\n" + + " + 0.185 : (s' = 78);\n" + + "[tick] s = 78 -> \n" + + " 1 : (s' = 79);\n" + + "[tick] s = 77 -> \n" + + " 1 : (s' = 80);\n" + + "[tick] s = 76 -> \n" + + " 1 : (s' = 81);\n" + + "[tick] s = 74 -> \n" + + " 0.185 : (s' = 82)\n" + + " + 0.63 : (s' = 83)\n" + + " + 0.185 : (s' = 84);\n" + + "[tick] s = 84 -> \n" + + " 1 : (s' = 85);\n" + + "[tick] s = 83 -> \n" + + " 1 : (s' = 86);\n" + + "[tick] s = 82 -> \n" + + " 1 : (s' = 87);\n" + + "[tick] s = 73 -> \n" + + " 0.185 : (s' = 88)\n" + + " + 0.63 : (s' = 89)\n" + + " + 0.185 : (s' = 90);\n" + + "[tick] s = 90 -> \n" + + " 1 : (s' = 91);\n" + + "[tick] s = 89 -> \n" + + " 1 : (s' = 92);\n" + + "[tick] s = 88 -> \n" + + " 1 : (s' = 93);\n" + + "[tick] s = 71 -> \n" + + " 0.185 : (s' = 94)\n" + + " + 0.63 : (s' = 95)\n" + + " + 0.185 : (s' = 96);\n" + + "[tick] s = 96 -> \n" + + " 0.185 : (s' = 97)\n" + + " + 0.63 : (s' = 98)\n" + + " + 0.185 : (s' = 99);\n" + + "[tick] s = 99 -> \n" + + " 1 : (s' = 100);\n" + + "[tick] s = 98 -> \n" + + " 1 : (s' = 101);\n" + + "[tick] s = 97 -> \n" + + " 1 : (s' = 102);\n" + + "[tick] s = 95 -> \n" + + " 0.185 : (s' = 103)\n" + + " + 0.63 : (s' = 104)\n" + + " + 0.185 : (s' = 105);\n" + + "[tick] s = 105 -> \n" + + " 1 : (s' = 106);\n" + + "[tick] s = 104 -> \n" + + " 1 : (s' = 107);\n" + + "[tick] s = 103 -> \n" + + " 1 : (s' = 108);\n" + + "[tick] s = 94 -> \n" + + " 0.185 : (s' = 109)\n" + + " + 0.63 : (s' = 110)\n" + + " + 0.185 : (s' = 111);\n" + + "[tick] s = 111 -> \n" + + " 1 : (s' = 112);\n" + + "[tick] s = 110 -> \n" + + " 1 : (s' = 113);\n" + + "[tick] s = 109 -> \n" + + " 1 : (s' = 114);\n" + + "[tick] s = 70 -> \n" + + " 0.185 : (s' = 115)\n" + + " + 0.63 : (s' = 116)\n" + + " + 0.185 : (s' = 117);\n" + + "[tick] s = 117 -> \n" + + " 0.185 : (s' = 118)\n" + + " + 0.63 : (s' = 119)\n" + + " + 0.185 : (s' = 120);\n" + + "[tick] s = 120 -> \n" + + " 1 : (s' = 121);\n" + + "[tick] s = 119 -> \n" + + " 1 : (s' = 122);\n" + + "[tick] s = 118 -> \n" + + " 1 : (s' = 123);\n" + + "[tick] s = 116 -> \n" + + " 0.185 : (s' = 124)\n" + + " + 0.63 : (s' = 125)\n" + + " + 0.185 : (s' = 126);\n" + + "[tick] s = 126 -> \n" + + " 1 : (s' = 127);\n" + + "[tick] s = 125 -> \n" + + " 1 : (s' = 128);\n" + + "[tick] s = 124 -> \n" + + " 1 : (s' = 129);\n" + + "[tick] s = 115 -> \n" + + " 0.185 : (s' = 130)\n" + + " + 0.63 : (s' = 131)\n" + + " + 0.185 : (s' = 132);\n" + + "[tick] s = 132 -> \n" + + " 1 : (s' = 133);\n" + + "[tick] s = 131 -> \n" + + " 1 : (s' = 134);\n" + + "[tick] s = 130 -> \n" + + " 1 : (s' = 135);\n" + + "[tick] s = 1 -> \n" + + " 0.185 : (s' = 136)\n" + + " + 0.63 : (s' = 137)\n" + + " + 0.185 : (s' = 138);\n" + + "[tick] s = 138 -> \n" + + " 0.185 : (s' = 139)\n" + + " + 0.63 : (s' = 140)\n" + + " + 0.185 : (s' = 141);\n" + + "[tick] s = 141 -> \n" + + " 0.185 : (s' = 142)\n" + + " + 0.63 : (s' = 143)\n" + + " + 0.185 : (s' = 144);\n" + + "[tick] s = 144 -> \n" + + " 1 : (s' = 145);\n" + + "[tick] s = 143 -> \n" + + " 1 : (s' = 146);\n" + + "[tick] s = 142 -> \n" + + " 1 : (s' = 147);\n" + + "[tick] s = 140 -> \n" + + " 0.185 : (s' = 148)\n" + + " + 0.63 : (s' = 149)\n" + + " + 0.185 : (s' = 150);\n" + + "[tick] s = 150 -> \n" + + " 1 : (s' = 151);\n" + + "[tick] s = 149 -> \n" + + " 1 : (s' = 152);\n" + + "[tick] s = 148 -> \n" + + " 1 : (s' = 153);\n" + + "[tick] s = 139 -> \n" + + " 0.185 : (s' = 154)\n" + + " + 0.63 : (s' = 155)\n" + + " + 0.185 : (s' = 156);\n" + + "[tick] s = 156 -> \n" + + " 1 : (s' = 157);\n" + + "[tick] s = 155 -> \n" + + " 1 : (s' = 158);\n" + + "[tick] s = 154 -> \n" + + " 1 : (s' = 159);\n" + + "[tick] s = 137 -> \n" + + " 0.185 : (s' = 160)\n" + + " + 0.63 : (s' = 161)\n" + + " + 0.185 : (s' = 162);\n" + + "[tick] s = 162 -> \n" + + " 0.185 : (s' = 163)\n" + + " + 0.63 : (s' = 164)\n" + + " + 0.185 : (s' = 165);\n" + + "[tick] s = 165 -> \n" + + " 1 : (s' = 166);\n" + + "[tick] s = 164 -> \n" + + " 1 : (s' = 167);\n" + + "[tick] s = 163 -> \n" + + " 1 : (s' = 168);\n" + + "[tick] s = 161 -> \n" + + " 0.185 : (s' = 169)\n" + + " + 0.63 : (s' = 170)\n" + + " + 0.185 : (s' = 171);\n" + + "[tick] s = 171 -> \n" + + " 1 : (s' = 172);\n" + + "[tick] s = 170 -> \n" + + " 1 : (s' = 173);\n" + + "[tick] s = 169 -> \n" + + " 1 : (s' = 174);\n" + + "[tick] s = 160 -> \n" + + " 0.185 : (s' = 175)\n" + + " + 0.63 : (s' = 176)\n" + + " + 0.185 : (s' = 177);\n" + + "[tick] s = 177 -> \n" + + " 1 : (s' = 178);\n" + + "[tick] s = 176 -> \n" + + " 1 : (s' = 179);\n" + + "[tick] s = 175 -> \n" + + " 1 : (s' = 180);\n" + + "[tick] s = 136 -> \n" + + " 0.185 : (s' = 181)\n" + + " + 0.63 : (s' = 182)\n" + + " + 0.185 : (s' = 183);\n" + + "[tick] s = 183 -> \n" + + " 0.185 : (s' = 184)\n" + + " + 0.63 : (s' = 185)\n" + + " + 0.185 : (s' = 186);\n" + + "[tick] s = 186 -> \n" + + " 1 : (s' = 187);\n" + + "[tick] s = 185 -> \n" + + " 1 : (s' = 188);\n" + + "[tick] s = 184 -> \n" + + " 1 : (s' = 189);\n" + + "[tick] s = 182 -> \n" + + " 0.185 : (s' = 190)\n" + + " + 0.63 : (s' = 191)\n" + + " + 0.185 : (s' = 192);\n" + + "[tick] s = 192 -> \n" + + " 1 : (s' = 193);\n" + + "[tick] s = 191 -> \n" + + " 1 : (s' = 194);\n" + + "[tick] s = 190 -> \n" + + " 1 : (s' = 195);\n" + + "[tick] s = 181 -> \n" + + " 0.185 : (s' = 196)\n" + + " + 0.63 : (s' = 197)\n" + + " + 0.185 : (s' = 198);\n" + + "[tick] s = 198 -> \n" + + " 1 : (s' = 199);\n" + + "[tick] s = 197 -> \n" + + " 1 : (s' = 200);\n" + + "[tick] s = 196 -> \n" + + " 1 : (s' = 201);\n" + + "[tick] (s = 13 | s = 14 | s = 15 | s = 19 | s = 20 | s = 21 | s = 25 | s = 26 | s = 27 | s = 34 | s = 35 | s = 36 | s = 40 | s = 41 | s = 42 | s = 46 | s = 47 | s = 48 | s = 55 | s = 56 | s = 57 | s = 61 | s = 62 | s = 63 | s = 67 | s = 68 | s = 69 | s = 79 | s = 80 | s = 81 | s = 85 | s = 86 | s = 87 | s = 91 | s = 92 | s = 93 | s = 100 | s = 101 | s = 102 | s = 106 | s = 107 | s = 108 | s = 112 | s = 113 | s = 114 | s = 121 | s = 122 | s = 123 | s = 127 | s = 128 | s = 129 | s = 133 | s = 134 | s = 135 | s = 145 | s = 146 | s = 147 | s = 151 | s = 152 | s = 153 | s = 157 | s = 158 | s = 159 | s = 166 | s = 167 | s = 168 | s = 172 | s = 173 | s = 174 | s = 178 | s = 179 | s = 180 | s = 187 | s = 188 | s = 189 | s = 193 | s = 194 | s = 195 | s = 199 | s = 200 | s = 201) -> 1 : true;\n" + + "endmodule\n" + + "formula stateValue = (s = 0 ? 0.00542219 : 0) + \n" + + " (s = 3 ? 0.0058019 : 0) + \n" + + " (s = 6 ? 0.00613341 : 0) + \n" + + " (s = 9 ? 0.00647093 : 0) + \n" + + " (s = 12 ? 0.00683459 : 0) + \n" + + " (s = 13 ? 0.006665 : 0) + \n" + + " (s = 11 ? 0.00634498 : 0) + \n" + + " (s = 14 ? 0.00623415 : 0) + \n" + + " (s = 10 ? 0.00585538 : 0) + \n" + + " (s = 15 ? 0.00580329 : 0) + \n" + + " (s = 8 ? 0.00604796 : 0) + \n" + + " (s = 18 ? 0.00638176 : 0) + \n" + + " (s = 19 ? 0.00626651 : 0) + \n" + + " (s = 17 ? 0.00597277 : 0) + \n" + + " (s = 20 ? 0.0059066 : 0) + \n" + + " (s = 16 ? 0.00556378 : 0) + \n" + + " (s = 21 ? 0.00554669 : 0) + \n" + + " (s = 7 ? 0.00562499 : 0) + \n" + + " (s = 24 ? 0.00596396 : 0) + \n" + + " (s = 25 ? 0.00589885 : 0) + \n" + + " (s = 23 ? 0.00560055 : 0) + \n" + + " (s = 26 ? 0.00557905 : 0) + \n" + + " (s = 22 ? 0.00523714 : 0) + \n" + + " (s = 27 ? 0.00525925 : 0) + \n" + + " (s = 5 ? 0.00575623 : 0) + \n" + + " (s = 30 ? 0.00608888 : 0) + \n" + + " (s = 33 ? 0.00642429 : 0) + \n" + + " (s = 34 ? 0.00630394 : 0) + \n" + + " (s = 32 ? 0.00600878 : 0) + \n" + + " (s = 35 ? 0.00593829 : 0) + \n" + + " (s = 31 ? 0.00559326 : 0) + \n" + + " (s = 36 ? 0.00557263 : 0) + \n" + + " (s = 29 ? 0.00571605 : 0) + \n" + + " (s = 39 ? 0.00605014 : 0) + \n" + + " (s = 40 ? 0.00597469 : 0) + \n" + + " (s = 38 ? 0.00568068 : 0) + \n" + + " (s = 41 ? 0.00564956 : 0) + \n" + + " (s = 37 ? 0.00531122 : 0) + \n" + + " (s = 42 ? 0.00532444 : 0) + \n" + + " (s = 28 ? 0.00534321 : 0) + \n" + + " (s = 45 ? 0.00571214 : 0) + \n" + + " (s = 46 ? 0.00567724 : 0) + \n" + + " (s = 44 ? 0.00535259 : 0) + \n" + + " (s = 47 ? 0.00536084 : 0) + \n" + + " (s = 43 ? 0.00499304 : 0) + \n" + + " (s = 48 ? 0.00504444 : 0) + \n" + + " (s = 4 ? 0.00537906 : 0) + \n" + + " (s = 51 ? 0.0057429 : 0) + \n" + + " (s = 54 ? 0.00607598 : 0) + \n" + + " (s = 55 ? 0.00599742 : 0) + \n" + + " (s = 53 ? 0.00570431 : 0) + \n" + + " (s = 56 ? 0.00567036 : 0) + \n" + + " (s = 52 ? 0.00533264 : 0) + \n" + + " (s = 57 ? 0.00534329 : 0) + \n" + + " (s = 50 ? 0.00538413 : 0) + \n" + + " (s = 60 ? 0.00574728 : 0) + \n" + + " (s = 61 ? 0.00570817 : 0) + \n" + + " (s = 59 ? 0.0053886 : 0) + \n" + + " (s = 62 ? 0.00539253 : 0) + \n" + + " (s = 58 ? 0.00502991 : 0) + \n" + + " (s = 63 ? 0.00507688 : 0) + \n" + + " (s = 49 ? 0.00502537 : 0) + \n" + + " (s = 66 ? 0.00545493 : 0) + \n" + + " (s = 67 ? 0.0054509 : 0) + \n" + + " (s = 65 ? 0.00507288 : 0) + \n" + + " (s = 68 ? 0.0051147 : 0) + \n" + + " (s = 64 ? 0.00469084 : 0) + \n" + + " (s = 69 ? 0.0047785 : 0) + \n" + + " (s = 2 ? 0.00543652 : 0) + \n" + + " (s = 72 ? 0.00579298 : 0) + \n" + + " (s = 75 ? 0.00612467 : 0) + \n" + + " (s = 78 ? 0.00646176 : 0) + \n" + + " (s = 79 ? 0.00633691 : 0) + \n" + + " (s = 77 ? 0.00604027 : 0) + \n" + + " (s = 80 ? 0.005966 : 0) + \n" + + " (s = 76 ? 0.00561879 : 0) + \n" + + " (s = 81 ? 0.0055951 : 0) + \n" + + " (s = 74 ? 0.00574839 : 0) + \n" + + " (s = 84 ? 0.00608128 : 0) + \n" + + " (s = 85 ? 0.00600209 : 0) + \n" + + " (s = 83 ? 0.00570914 : 0) + \n" + + " (s = 86 ? 0.00567461 : 0) + \n" + + " (s = 82 ? 0.005337 : 0) + \n" + + " (s = 87 ? 0.00534712 : 0) + \n" + + " (s = 73 ? 0.0053721 : 0) + \n" + + " (s = 90 ? 0.0057369 : 0) + \n" + + " (s = 91 ? 0.00569903 : 0) + \n" + + " (s = 89 ? 0.00537801 : 0) + \n" + + " (s = 92 ? 0.00538321 : 0) + \n" + + " (s = 88 ? 0.00501912 : 0) + \n" + + " (s = 93 ? 0.00506739 : 0) + \n" + + " (s = 71 ? 0.0054347 : 0) + \n" + + " (s = 96 ? 0.00579138 : 0) + \n" + + " (s = 99 ? 0.00612311 : 0) + \n" + + " (s = 100 ? 0.00603889 : 0) + \n" + + " (s = 98 ? 0.00574698 : 0) + \n" + + " (s = 101 ? 0.0057079 : 0) + \n" + + " (s = 97 ? 0.00537085 : 0) + \n" + + " (s = 102 ? 0.00537691 : 0) + \n" + + " (s = 95 ? 0.00543309 : 0) + \n" + + " (s = 105 ? 0.00578997 : 0) + \n" + + " (s = 106 ? 0.00574574 : 0) + \n" + + " (s = 104 ? 0.00543168 : 0) + \n" + + " (s = 107 ? 0.00543044 : 0) + \n" + + " (s = 103 ? 0.0050734 : 0) + \n" + + " (s = 108 ? 0.00511515 : 0) + \n" + + " (s = 94 ? 0.00507481 : 0) + \n" + + " (s = 111 ? 0.0054932 : 0) + \n" + + " (s = 112 ? 0.00548458 : 0) + \n" + + " (s = 110 ? 0.00511639 : 0) + \n" + + " (s = 113 ? 0.00515299 : 0) + \n" + + " (s = 109 ? 0.00473959 : 0) + \n" + + " (s = 114 ? 0.0048214 : 0) + \n" + + " (s = 70 ? 0.00507641 : 0) + \n" + + " (s = 117 ? 0.00549445 : 0) + \n" + + " (s = 120 ? 0.00584445 : 0) + \n" + + " (s = 121 ? 0.00579368 : 0) + \n" + + " (s = 119 ? 0.00548568 : 0) + \n" + + " (s = 122 ? 0.00547796 : 0) + \n" + + " (s = 118 ? 0.0051269 : 0) + \n" + + " (s = 123 ? 0.00516224 : 0) + \n" + + " (s = 116 ? 0.0051178 : 0) + \n" + + " (s = 126 ? 0.00552697 : 0) + \n" + + " (s = 127 ? 0.0055143 : 0) + \n" + + " (s = 125 ? 0.00515423 : 0) + \n" + + " (s = 128 ? 0.00518628 : 0) + \n" + + " (s = 124 ? 0.00478148 : 0) + \n" + + " (s = 129 ? 0.00485827 : 0) + \n" + + " (s = 115 ? 0.00474116 : 0) + \n" + + " (s = 132 ? 0.00524549 : 0) + \n" + + " (s = 133 ? 0.00526659 : 0) + \n" + + " (s = 131 ? 0.00482278 : 0) + \n" + + " (s = 134 ? 0.00489461 : 0) + \n" + + " (s = 130 ? 0.00440007 : 0) + \n" + + " (s = 135 ? 0.00452262 : 0) + \n" + + " (s = 1 ? 0.00507114 : 0) + \n" + + " (s = 138 ? 0.00549034 : 0) + \n" + + " (s = 141 ? 0.00584076 : 0) + \n" + + " (s = 144 ? 0.00617171 : 0) + \n" + + " (s = 145 ? 0.00608167 : 0) + \n" + + " (s = 143 ? 0.00579043 : 0) + \n" + + " (s = 146 ? 0.00574614 : 0) + \n" + + " (s = 142 ? 0.00540915 : 0) + \n" + + " (s = 147 ? 0.00541062 : 0) + \n" + + " (s = 140 ? 0.00548206 : 0) + \n" + + " (s = 150 ? 0.00583336 : 0) + \n" + + " (s = 151 ? 0.00578392 : 0) + \n" + + " (s = 149 ? 0.00547477 : 0) + \n" + + " (s = 152 ? 0.00546836 : 0) + \n" + + " (s = 148 ? 0.00511618 : 0) + \n" + + " (s = 153 ? 0.0051528 : 0) + \n" + + " (s = 139 ? 0.00512335 : 0) + \n" + + " (s = 156 ? 0.00553137 : 0) + \n" + + " (s = 157 ? 0.00551816 : 0) + \n" + + " (s = 155 ? 0.00515911 : 0) + \n" + + " (s = 158 ? 0.00519058 : 0) + \n" + + " (s = 154 ? 0.00478685 : 0) + \n" + + " (s = 159 ? 0.00486299 : 0) + \n" + + " (s = 137 ? 0.00511316 : 0) + \n" + + " (s = 162 ? 0.0055233 : 0) + \n" + + " (s = 165 ? 0.00587045 : 0) + \n" + + " (s = 166 ? 0.00581656 : 0) + \n" + + " (s = 164 ? 0.00551107 : 0) + \n" + + " (s = 167 ? 0.0055003 : 0) + \n" + + " (s = 163 ? 0.00515169 : 0) + \n" + + " (s = 168 ? 0.00518405 : 0) + \n" + + " (s = 161 ? 0.00515014 : 0) + \n" + + " (s = 171 ? 0.00555269 : 0) + \n" + + " (s = 172 ? 0.00553693 : 0) + \n" + + " (s = 170 ? 0.00518269 : 0) + \n" + + " (s = 173 ? 0.00521133 : 0) + \n" + + " (s = 169 ? 0.00481268 : 0) + \n" + + " (s = 174 ? 0.00488572 : 0) + \n" + + " (s = 160 ? 0.00477698 : 0) + \n" + + " (s = 177 ? 0.005271 : 0) + \n" + + " (s = 178 ? 0.00528904 : 0) + \n" + + " (s = 176 ? 0.00485431 : 0) + \n" + + " (s = 179 ? 0.00492235 : 0) + \n" + + " (s = 175 ? 0.00443761 : 0) + \n" + + " (s = 180 ? 0.00455566 : 0) + \n" + + " (s = 136 ? 0.00473599 : 0) + \n" + + " (s = 183 ? 0.00524183 : 0) + \n" + + " (s = 186 ? 0.00562712 : 0) + \n" + + " (s = 187 ? 0.00560243 : 0) + \n" + + " (s = 185 ? 0.00526337 : 0) + \n" + + " (s = 188 ? 0.00528233 : 0) + \n" + + " (s = 184 ? 0.00489962 : 0) + \n" + + " (s = 189 ? 0.00496223 : 0) + \n" + + " (s = 182 ? 0.00481823 : 0) + \n" + + " (s = 192 ? 0.00530066 : 0) + \n" + + " (s = 193 ? 0.00531514 : 0) + \n" + + " (s = 191 ? 0.0048906 : 0) + \n" + + " (s = 194 ? 0.00495429 : 0) + \n" + + " (s = 190 ? 0.00448054 : 0) + \n" + + " (s = 195 ? 0.00459344 : 0) + \n" + + " (s = 181 ? 0.00439463 : 0) + \n" + + " (s = 198 ? 0.00500909 : 0) + \n" + + " (s = 199 ? 0.00505856 : 0) + \n" + + " (s = 197 ? 0.00451784 : 0) + \n" + + " (s = 200 ? 0.00462626 : 0) + \n" + + " (s = 196 ? 0.00402658 : 0) + \n" + + " (s = 201 ? 0.00419396 : 0);"; + + protected void initializeAdaptationMgr(SwimModelHelper swimModel) { + log("Starting SWIMEXT HP Adaptation Manager initialization"); + computeDecisionHorizon(swimModel); + m_currentTime = 0; + m_adaptMgr = new PMCAdaptationManager(); + m_planDB = PlanDB.get_instance(); + + + log("begin testing..."); + //StringVector sv = new StringVector(); + //m_tspModel.getModelInstance().observe(0.00727339); + //m_tspModel.getModelInstance().observe(0.00688481); + //m_tspModel.getModelInstance().observe(0.00626385); + //m_tspModel.getModelInstance().observe(0.00603236); + //m_tspModel.getModelInstance().observe(0.00655949); + //log("after observations"); + //generateEnvironmentModel(); generateEnvironmentModel(); + //log("after generations"); + //AdaptationPlanner m_adaptPlanner = new AdaptationPlanner(); + //m_adaptPlanner.setModelTemplatePath("/home/frank/Sandbox/plasasim/templates/final_ibl.prism"); + //sv = m_adaptPlanner.plan("foooo", "barrrr", "/home/frank/PrismDump", true); + //sv = m_adaptPlanner.plan(env_mod_r, init_state_r, "/home/frank/PrismDump", true); + //log("size: " + sv.size()); + //for(int i = 0; i < sv.size(); ++i) { + // log("R" + i + ": " + sv.get(i)); + //} + // sv.clear(); + //sv = m_adaptPlanner.plan(env_mod_d, init_state_d, "/home/frank/PrismDump", false); + //log("size: " + sv.size()); + //for(int i = 0; i < sv.size(); ++i) { + // log("D" + i + ": " + sv.get(i)); + //} + //m_planDB.update_val(5, m_currentTime, 1, 0, 0, 1, 4, 0, 0, 0, 60, 60, 0, 0.03); + //log("updated"); + //String path = m_adaptPlanner.getPlanned_path(); + //log("path is: " + path); + //if(m_planDB.populate_db(path)) { + // log("success!"); + //} else { + // log("fail!"); + //} + //m_planDB.get_plan(); + //sv = m_planDB.getActions(); + //log("size: " + sv.size()); + //for(int i = 0; i < sv.size(); ++i) { + // log("D" + i + ": " + sv.get(i)); + //} + + m_isInitialized = true; + log("m_isInitialized set to true, finished initialization"); + } + + private void computeDecisionHorizon(SwimModelHelper swimModel) { + + log("max servers: " + swimModel.getMaxServers()); + log("latency: " + swimModel.getAddServerLatencyPeriods()); + m_horizon = (int) Math.max(5.0, + swimModel.getAddServerLatencyPeriods() * (swimModel.getMaxServers() - 1) + 1); + + // set value in tsp model + ModelReference modelRef = new ModelReference(TSP_MODEL, TimeSeriesPredictorModelInstance.MODEL_TYPE); + m_tspModel = (TimeSeriesPredictorModelInstance) m_modelsManagerPort.getModelInstance (modelRef); + try { + m_tspModel.getModelInstance().setHorizon(m_horizon); + } catch (RainbowException e) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, e.toString()); + } + } + + private EnvironmentDTMCPartitioned generateEnvironmentModel() { + return m_tspModel.getModelInstance().generateEnvironmentDTMC(4, m_horizon); + } + + private String get_initial_state_str (SwimModelHelper swimModel, boolean fastPlanning) { + String res = ""; + res += "const double addServer_LATENCY = "; + res += swimModel.getAddServerLatencySec(); + res += ";\n"; + + res += "const int HORIZON = "; + res += m_horizon; + res += ";\n"; + + res += "const double PERIOD = "; + res += SLEEP_TIME / 1000; //evaluation period, in sec(?) + res += ";\n"; + + res += "const int DIMMER_LEVELS = "; + res += swimModel.getDimmerLevels(); + res += ";\n"; + + res += "const int ini_dimmer = "; + // int discretizedBrownoutFactor = 1 + (hpModel.numberOfBrownoutLevels - 1) * (int)(hpModel.brownoutFactor); + int discretizedBrownoutFactor = 1 + (swimModel.getDimmerLevels() - 1) * (int)(swimModel.getCurrentDimmer()); + res += discretizedBrownoutFactor; + res += ";\n"; + + res += "const int MAX_SERVERS_A = "; + res += 1; //hardcoded + res += ";\n"; + + res += "const int MAX_SERVERS_B = "; + res += 1; //hardcoded + res += ";\n"; + + res += "const int MAX_SERVERS_C = "; + res += 1; //hardcoded + res += ";\n"; + + res += "const int ini_servers_A = "; + res += getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isActive")) ? 1 : 0; + res += ";\n"; + + int temp = getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isActive")) ? 1 : 0; + //log("**************** const int ini_servers_A = " + temp + " FastPlanning = " + fastPlanning); + + res += "const int ini_servers_B = "; + res += getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isActive")) ? 1 : 0; + res += ";\n"; + + temp = getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isActive")) ? 1 : 0; + //log("**************** const int ini_servers_B = " + temp + " FastPlanning = " + fastPlanning); + + res += "const int ini_servers_C = "; + res += getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isActive")) ? 1 : 0; + res += ";\n"; + + temp = getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isActive")) ? 1 : 0; + //log("**************** const int ini_servers_C = " + temp + " FastPlanning = " + fastPlanning); + + int addServerAState = 0; + int addServerBState = 0; + int addServerCState = 0; + int bootType = getBootType(); + + if (bootType != 0) { + int addServerState = swimModel.getAddServerTacticProgress(); + + if(bootType == 1) + addServerAState = addServerState; + else if(bootType == 2) + addServerBState = addServerState; + else if(bootType == 3) + addServerCState = addServerState; + } + + res += "const int ini_addServerA_state = "; + res += addServerAState; + res += ";\n"; + + //log("**************** const int ini_addServerA_state = " + addServerAState + " FastPlanning = " + fastPlanning); + + res += "const int ini_addServerB_state = "; + res += addServerBState; + res += ";\n"; + + //log("**************** const int ini_addServerB_state = " + addServerBState + " FastPlanning = " + fastPlanning); + + res += "const int ini_addServerC_state = "; + res += addServerCState; + res += ";\n"; + + //log("**************** const int ini_addServerC_state = " + addServerCState + " FastPlanning = " + fastPlanning); + + res += "const double SERVERA_COST_SEC = "; + res += getDoubleVal(m_model.getModelInstance().getComponent("server1").getProperty("cost")); + res += ";\n"; + + res += "const double SERVERB_COST_SEC = "; + res += getDoubleVal(m_model.getModelInstance().getComponent("server2").getProperty("cost")); + res += ";\n"; + + res += "const double SERVERC_COST_SEC = "; + res += getDoubleVal(m_model.getModelInstance().getComponent("server3").getProperty("cost")); + res += ";\n"; + + res += "const double MAX_ARRIVALA_CAPACITY = "; + res += getIntVal(m_model.getModelInstance().getComponent("server1").getProperty("max_arrival_capacity")); + res += ";\n"; + + res += "const double MAX_ARRIVALA_CAPACITY_LOW = "; + res += getIntVal(m_model.getModelInstance().getComponent("server1").getProperty("max_arrival_capacity_low")); + res += ";\n"; + + res += "const double MAX_ARRIVALB_CAPACITY = "; + res += getIntVal(m_model.getModelInstance().getComponent("server2").getProperty("max_arrival_capacity")); + res += ";\n"; + + res += "const double MAX_ARRIVALB_CAPACITY_LOW = "; + res += getIntVal(m_model.getModelInstance().getComponent("server2").getProperty("max_arrival_capacity_low")); + res += ";\n"; + + res += "const double MAX_ARRIVALC_CAPACITY = "; + res += getIntVal(m_model.getModelInstance().getComponent("server3").getProperty("max_arrival_capacity")); + res += ";\n"; + + res += "const double MAX_ARRIVALC_CAPACITY_LOW = "; + res += getIntVal(m_model.getModelInstance().getComponent("server3").getProperty("max_arrival_capacity_low")); + res += ";\n"; + + res += "const double penalty = "; + res += -0.25; //TODO: hardcoded from swimExtention.ini + res += ";\n"; + + res += "const int ini_traffic_A = "; + res += (int) getDoubleVal(m_model.getModelInstance().getComponent("server1").getProperty("traffic")); + res += ";\n"; + + res += "const int ini_traffic_B = "; + res += (int) getDoubleVal(m_model.getModelInstance().getComponent("server2").getProperty("traffic")); + res += ";\n"; + + res += "const int ini_traffic_C = "; + res += (int) getDoubleVal(m_model.getModelInstance().getComponent("server3").getProperty("traffic")); + res += ";\n"; + + res += "const double interArrivalScaleFactorForDecision = 1;\n"; + + + return res; + } + + protected SwimExtendedPlan parsePlan (String plan) { + SwimExtendedPlan res = null; + if(plan.equals("addServerA_start")) + res = new AddServerPlan(m_model, "1"); + else if(plan.equals("addServerB_start")) + res = new AddServerPlan(m_model, "2"); + else if(plan.equals("addServerC_start")) + res = new AddServerPlan(m_model, "3"); + else if(plan.equals("removeServerA_start")) + res = new RemoveServerPlan(m_model, "1"); + else if(plan.equals("removeServerB_start")) + res = new RemoveServerPlan(m_model, "2"); + else if(plan.equals("removeServerC_start")) + res = new RemoveServerPlan(m_model, "3"); + else if(plan.equals("increaseDimmer_start")) + res = new IncDimmerPlan(m_model); + else if(plan.equals("decreaseDimmer_start")) + res = new DecDimmerPlan(m_model); + else if(plan.equals("divert_100_0_0")) + res = new DivertTrafficPlan(m_model, "divert_100_0_0"); + else if(plan.equals("divert_75_25_0")) + res = new DivertTrafficPlan(m_model, "divert_75_25_0"); + else if(plan.equals("divert_75_0_25")) + res = new DivertTrafficPlan(m_model, "divert_75_0_25"); + else if(plan.equals("divert_50_50_0")) + res = new DivertTrafficPlan(m_model, "divert_50_50_0"); + else if(plan.equals("divert_50_0_50")) + res = new DivertTrafficPlan(m_model, "divert_50_0_50"); + else if(plan.equals("divert_50_25_25")) + res = new DivertTrafficPlan(m_model, "divert_50_25_25"); + else if(plan.equals("divert_25_75_0")) + res = new DivertTrafficPlan(m_model, "divert_25_75_0"); + else if(plan.equals("divert_25_0_75")) + res = new DivertTrafficPlan(m_model, "divert_25_0_75"); + else if(plan.equals("divert_25_50_25")) + res = new DivertTrafficPlan(m_model, "divert_25_50_25"); + else if(plan.equals("divert_25_25_50")) + res = new DivertTrafficPlan(m_model, "divert_25_25_50"); + else if(plan.equals("divert_0_100_0")) + res = new DivertTrafficPlan(m_model, "divert_0_100_0"); + else if(plan.equals("divert_0_0_100")) + res = new DivertTrafficPlan(m_model, "divert_0_0_100"); + else if(plan.equals("divert_0_75_25")) + res = new DivertTrafficPlan(m_model, "divert_0_75_25"); + else if(plan.equals("divert_0_25_75")) + res = new DivertTrafficPlan(m_model, "divert_0_25_75"); + else if(plan.equals("divert_0_50_50")) + res = new DivertTrafficPlan(m_model, "divert_0_50_50"); + else if(plan.startsWith("progress") || plan.equals("addServerA_complete") + || plan.equals("addServerB_complete") || plan.equals("addServerC_complete")) { + log("Ignoring #" + ": " + plan); + } else { + assert(false); // unknown tactic + } + + return res; + } + + protected AdaptationTree parseActions (StringVector actions){ + AdaptationTree at = new AdaptationTree<>(AdaptationExecutionOperatorT.PARALLEL); + + //log("actions to take: " + actions.size()); + + for(int i = 0; i < actions.size(); ++i) { + if (actions.get(i).startsWith("progress") + || actions.get(i).equals("addServerA_complete") + || actions.get(i).equals("addServerB_complete") + || actions.get(i).equals("addServerC_complete")) { + log("Ignoring #" + i + ": " + actions.get(i)); + } else { + at.addLeaf(parsePlan(actions.get(i))); + log("#" + i + ": " + actions.get(i)); + } + } + + return at; + } + + + @Override + public void dispose() { + if (m_adaptationEnqueuePort != null) { + m_adaptationEnqueuePort.dispose (); + } + if (m_modelChangePort != null) { + m_modelChangePort.dispose (); + } + + // null-out data members + m_model = null; + } + + @Override + protected void log(String txt) { + m_reportingPort.info (RainbowComponentT.ADAPTATION_MANAGER, txt); + } + + protected void error (String txt) { + m_reportingPort.error (RainbowComponentT.ADAPTATION_MANAGER, txt); + } + + public void setAdaptationEnabled (boolean b) { + m_adaptationEnabled = b; + } + + public boolean adaptationInProgress () { + return m_adaptationNeeded; + } + + + @Override + public void markStrategyExecuted(AdaptationTree plan) { + AdaptationResultsVisitor v = new AdaptationResultsVisitor (plan); + plan.visit(v); + + if (v.m_allOk) { + log("Finished adapting the system"); + } else { + log("Something in the adaptation plan failed to execute."); + } + + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + m_executingPlan = false; + } + + + @Override + public void onEvent(ModelReference reference, IRainbowMessage message) { + // Because of the subscription, the model should be the model ref so no need to check + String typecheckSt = (String) message.getProperty (IModelChangeBusPort.PARAMETER_PROP + "0"); + Boolean typechecks = Boolean.valueOf (typecheckSt); + // Cause the thread to wake up if it is sleeping + if (!typechecks) { + activeThread ().interrupt (); + } + } + + + + + + @Override + public void setEnabled(boolean enabled) { + m_reportingPort.info (getComponentType (), + MessageFormat.format ("Turning adaptation {0}.", (enabled ? "on" : "off"))); + // if (!enabled && !m_pendingStrategies.isEmpty ()) { + // m_reportingPort.info (getComponentType (), "There is an adaptation in progress. This will finish."); + // } + // m_adaptEnabled = enabled; + } + + + @Override + public boolean isEnabled() { + return true; + } + + protected AdaptationTree checkAdaptation () { + boolean decide = true; + AdaptationTree at = null; + SwimModelHelper swimModel = new SwimModelHelper(m_model); + if (!m_isInitialized) { + initializeAdaptationMgr(swimModel); + } + + /*boolean enabled = getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isArchEnabled")); + int temp = getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isActive")) ? 1 : 0; + log("**************** const int ini_servers_A = " + temp + " Enabled = " + enabled); + + enabled = getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isArchEnabled")); + temp = getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isActive")) ? 1 : 0; + log("**************** const int ini_servers_B = " + temp + " Enabled = " + enabled); + + enabled = getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isArchEnabled")); + temp = getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isActive")) ? 1 : 0; + log("**************** const int ini_servers_C = " + temp + " Enabled = " + enabled);*/ + + EnvironmentDTMCPartitioned env = generateEnvironmentModel(); + + if (env == null) { + log("No environment observations available. Can't make adaptation decision"); + decide = false; + } + + if (decide) { + at = checkAdaptationImpl (swimModel, env); + log("Adaptation decision time DONE"); + } + + log ("About to return at"); + return at; + } + + protected int getIntVal (IAcmeProperty val) { + return (int) PropertyHelper.toJavaVal(val.getValue()); + } + protected double getDoubleVal (IAcmeProperty val) { + return (double) PropertyHelper.toJavaVal(val.getValue()); + } + protected boolean getBoolVal (IAcmeProperty val) { + return (boolean) PropertyHelper.toJavaVal(val.getValue()); + } + + protected int getBootType () { + //getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isArchEnabled")); + //getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isActive")); + /*log("isArchEnabled = " + + getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isArchEnabled")) + + " isActive = " + + getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isActive"))); + + log("isArchEnabled = " + + getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isArchEnabled")) + + " isActive = " + + getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isActive"))); + + log("isArchEnabled = " + + getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isArchEnabled")) + + " isActive = " + + getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isActive")));*/ + + if(getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isActive")) + != getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isArchEnabled"))) + return 1; + else if (getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isActive")) + != getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isArchEnabled"))) + return 2; + else if (getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isActive")) + != getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isArchEnabled"))) + return 3; + else + return 0; + } + + //class that defines fast planning procedure + public class Reactive extends Thread { + public SwimModelHelper swimModel; + public boolean usePredictor; + public String initialState; + public String environmentModel; + public StringVector actions; + public String ret_path; + + Reactive(SwimModelHelper swimModel, boolean usePredictor){ + this.swimModel = swimModel; + this.usePredictor = usePredictor; + } + + @Override + public void run() { + // TODO Auto-generated method stub + /*if (startServerC) { + log("fast planning returning addServerC_start"); + actions. + actions.add("addServerC_start"); + startServerC = false; + return; + }*/ + initialState = get_initial_state_str(swimModel, true); + + if(usePredictor) { + environmentModel = "formula stateValue = " + ";\n"; + } else { + environmentModel = "formula stateValue = " + swimModel.getArrivalRate() + ";\n"; + } + + log("fast planning triggered"); + AdaptationPlanner m_adaptPlanner = new AdaptationPlanner(); + String sysEnvStr = System.getenv("RAINBOW"); + m_adaptPlanner.setModelTemplatePath(sysEnvStr + "/pladapt/templates/final_ibl.prism"); + actions = m_adaptPlanner.plan(environmentModel, initialState, "", true); + String ret_path = m_adaptPlanner.getPlanned_path(); + log("fast plan over, path = " + ret_path); + } + } + + //class that defines slow planning procedure + public class Deliberative extends Thread { + public SwimModelHelper swimModel; + public boolean usePredictor; + public String initialState; + public String environmentModel; + public String ret_path; + + Deliberative(SwimModelHelper swimModel, boolean usePredictor){ + this.swimModel = swimModel; + this.usePredictor = usePredictor; + } + + @Override + public void run() { + // TODO Auto-generated method stub + initialState = get_initial_state_str(swimModel, false); + m_currentTime = 0; //reset current time for new plan + if(usePredictor) { + environmentModel = PMCAdaptationManager.generateEnvironmentDTMC(generateEnvironmentModel()); + } else { + environmentModel = PMCAdaptationManager.generateEnvironmentDTMC(generateEnvironmentModel()); + } + + environmentModel = "module environment\n" + environmentModel; + + log("slow planning triggered"); + AdaptationPlanner m_adaptPlanner = new AdaptationPlanner(); + String sysEnvStr = System.getenv("RAINBOW"); + m_adaptPlanner.setModelTemplatePath(sysEnvStr + "/pladapt/templates/final_ibl.prism"); + m_adaptPlanner.plan(environmentModel, initialState, "", false); + String ret_path = m_adaptPlanner.getPlanned_path(); + log("slow plan over, path = " + ret_path); + m_planDB.clean_db(); + m_planDB.populate_db(ret_path); + log("slow plan populate db over"); + } + } + + protected AdaptationTree checkAdaptationImpl(SwimModelHelper swimModel, + EnvironmentDTMCPartitioned env){ + //first we update planDB + m_planDB.update_val + (m_horizon, + m_currentTime, + getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isActive")) ? 1 : 0, + getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isActive")) ? 1 : 0, + getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isActive")) ? 1 : 0, + swimModel.getCurrentDimmerLevel(), + (int) getDoubleVal(m_model.getModelInstance().getComponent("server1").getProperty("traffic")), + (int) getDoubleVal(m_model.getModelInstance().getComponent("server2").getProperty("traffic")), + (int) getDoubleVal(m_model.getModelInstance().getComponent("server3").getProperty("traffic")), + swimModel.getAddServerTacticProgress(), + swimModel.getAddServerLatencySec(), + SLEEP_TIME / 1000, //evaluation period, in sec(?) + getBootType(), + swimModel.getArrivalRate() //should be mean arrival rate, need fix + ); + + //then we try to get plan + StringVector actions = new StringVector(); + if(!m_planDB.get_plan()) { + if(m_horizon > m_currentTime) { + log("Plan Failed"); + } else { + log("Plan Over"); + } + + boolean usePredictor = false; + + //Generate a new plan + boolean trigger_fast_planning = false; + //check if fast planning needed against threshold + if(swimModel.getAverageResponseTime() >= 0) { + trigger_fast_planning = true; + } + + //trigger slow planning + Deliberative runD = new Deliberative(swimModel, usePredictor); + runD.start(); + + if(trigger_fast_planning) { + //spawn a new reactive thread, trigger fast planning + Reactive runR = new Reactive(swimModel, usePredictor); + runR.start(); + try { + runR.join(); + actions = runR.actions; + log("Executing reactive plan."); + /*if (startServerC) { + log("Adding fast planning action addServerC_start"); + + actions.add("addServerC_start"); + startServerC = false; + }*/ + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //actions = runR.actions; + } + } else { + log("State Found in Deliberative Plan"); + actions = m_planDB.getActions(); + } + + //parse actions + AdaptationTree at = parseActions(actions); + + /*log("actions to take: " + actions.size()); + for(int i = 0; i < actions.size(); ++i) { + if (!actions.get(i).startsWith("progressC")) { + log("#" + i + ": " + actions.get(i)); + } else { + log("Ignoring #" + i + ": " + actions.get(i)); + } + }*/ + + return at; + } + + + + @Override + protected void runAction() { + //log("inside runAction"); + // double arrivalRate = getDoubleVal(m_model.getModelInstance().getComponent("LB0").getProperty("arrivalRate")); + // m_tspModel.getModelInstance().observe(arrivalRate); + m_currentTime++; + if (m_adaptationEnabled && !m_executingPlan) { + AdaptationTree at = checkAdaptation (); + if (at != null) { + //log (">> do strategy: " + at); + m_adaptationEnqueuePort.offerAdaptation (at, new Object[0]); + String logMessage = at.toString (); + //log("New plan generated. Enqueueing..."); + log(logMessage); + m_executingPlan = true; + } + } else { + log("occupied"); + } + + //testing code + /*String logInfo = ""; + logInfo += "Load Balancer:"; + logInfo += "\ndimmer: " + getDoubleVal(m_model.getModelInstance().getComponent("LB0").getProperty("dimmer")); + logInfo += "\narrivalRate: " + getDoubleVal(m_model.getModelInstance().getComponent("LB0").getProperty("arrivalRate")); + logInfo += "\naverageResponseTime: " + getDoubleVal(m_model.getModelInstance().getComponent("LB0").getProperty("averageResponseTime")); + logInfo += "\nServer 1:"; + logInfo += "\ntraffic: " + getDoubleVal(m_model.getModelInstance().getComponent("server1").getProperty("traffic")); + logInfo += "\nisArchEnabled: " + getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isArchEnabled")); + logInfo += "\nmax_arrival_capacity: " + getIntVal(m_model.getModelInstance().getComponent("server1").getProperty("max_arrival_capacity")); + logInfo += "\nmax_arrival_capacity_low: " + getIntVal(m_model.getModelInstance().getComponent("server1").getProperty("max_arrival_capacity_low")); + logInfo += "\nindex: " + getIntVal(m_model.getModelInstance().getComponent("server1").getProperty("index")); + logInfo += "\nisActive: " + getBoolVal(m_model.getModelInstance().getComponent("server1").getProperty("isActive")); + logInfo += "\nexpectedActivationTime: " + getIntVal(m_model.getModelInstance().getComponent("server1").getProperty("expectedActivationTime")); + logInfo += "\nreqServiceRate: " + getDoubleVal(m_model.getModelInstance().getComponent("server1").getProperty("reqServiceRate")); + logInfo += "\nbyteServiceRate: " + getDoubleVal(m_model.getModelInstance().getComponent("server1").getProperty("byteServiceRate")); + logInfo += "\ncost: " + getDoubleVal(m_model.getModelInstance().getComponent("server1").getProperty("cost")); + logInfo += "\nServer 2:"; + logInfo += "\ntraffic: " + getDoubleVal(m_model.getModelInstance().getComponent("server2").getProperty("traffic")); + logInfo += "\nisArchEnabled: " + getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isArchEnabled")); + logInfo += "\nmax_arrival_capacity: " + getIntVal(m_model.getModelInstance().getComponent("server2").getProperty("max_arrival_capacity")); + logInfo += "\nmax_arrival_capacity_low: " + getIntVal(m_model.getModelInstance().getComponent("server2").getProperty("max_arrival_capacity_low")); + logInfo += "\nindex: " + getIntVal(m_model.getModelInstance().getComponent("server2").getProperty("index")); + logInfo += "\nisActive: " + getBoolVal(m_model.getModelInstance().getComponent("server2").getProperty("isActive")); + logInfo += "\nexpectedActivationTime: " + getIntVal(m_model.getModelInstance().getComponent("server2").getProperty("expectedActivationTime")); + logInfo += "\nreqServiceRate: " + getDoubleVal(m_model.getModelInstance().getComponent("server2").getProperty("reqServiceRate")); + logInfo += "\nbyteServiceRate: " + getDoubleVal(m_model.getModelInstance().getComponent("server2").getProperty("byteServiceRate")); + logInfo += "\ncost: " + getDoubleVal(m_model.getModelInstance().getComponent("server2").getProperty("cost")); + logInfo += "\nServer 3:"; + logInfo += "\ntraffic: " + getDoubleVal(m_model.getModelInstance().getComponent("server3").getProperty("traffic")); + logInfo += "\nisArchEnabled: " + getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isArchEnabled")); + logInfo += "\nmax_arrival_capacity: " + getIntVal(m_model.getModelInstance().getComponent("server3").getProperty("max_arrival_capacity")); + logInfo += "\nmax_arrival_capacity_low: " + getIntVal(m_model.getModelInstance().getComponent("server3").getProperty("max_arrival_capacity_low")); + logInfo += "\nindex: " + getIntVal(m_model.getModelInstance().getComponent("server3").getProperty("index")); + logInfo += "\nisActive: " + getBoolVal(m_model.getModelInstance().getComponent("server3").getProperty("isActive")); + logInfo += "\nexpectedActivationTime: " + getIntVal(m_model.getModelInstance().getComponent("server3").getProperty("expectedActivationTime")); + logInfo += "\nreqServiceRate: " + getDoubleVal(m_model.getModelInstance().getComponent("server3").getProperty("reqServiceRate")); + logInfo += "\nbyteServiceRate: " + getDoubleVal(m_model.getModelInstance().getComponent("server3").getProperty("byteServiceRate")); + logInfo += "\ncost: " + getDoubleVal(m_model.getModelInstance().getComponent("server3").getProperty("cost")); + log(logInfo);*/ + + //testing 2 + SwimModelHelper swimModel = new SwimModelHelper(m_model); + if (!m_isInitialized) { + initializeAdaptationMgr(swimModel); + } + String environmentModel = PMCAdaptationManager.generateEnvironmentDTMC(generateEnvironmentModel()); + //log(get_initial_state_str(swimModel, true)); + //log(environmentModel); + } + + private void strategyLog (String logMessage) { + if (m_strategyLog != null) { + Date d = new Date (); + String log = MessageFormat.format ("{0,number,#},queuing,{1}\n", d.getTime (), + logMessage); + try { + m_strategyLog.write (java.nio.ByteBuffer.wrap (log.getBytes ())); + } catch (IOException e) { + reportingPort ().error (getComponentType (), "Failed to write " + log + " to log file"); + } + } + } + + @Override + public RainbowComponentT getComponentType() { + return RainbowComponentT.ADAPTATION_MANAGER; + } + + + private class AdaptationResultsVisitor extends DefaultAdaptationTreeWalker { + + public AdaptationResultsVisitor (AdaptationTree adt) { + super (adt); + } + + boolean m_allOk = true; + + @Override + protected void evaluate (SwimExtendedPlan adaptation) { + m_allOk &= adaptation.getOutcome (); + } + + } + + +} + + + + + + + + + + diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/IncDimmerPlan.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/IncDimmerPlan.java new file mode 100644 index 000000000..2d3302538 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/IncDimmerPlan.java @@ -0,0 +1,52 @@ +package org.sa.rainbow.swim.adaptation; + +import org.acmestudio.acme.element.IAcmeComponent; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.swim.Swim; +import org.sa.rainbow.model.acme.swim.SwimModelUpdateOperatorsImpl; +import org.sa.rainbow.model.acme.swim.commands.IncDimmerCmd; +import org.sa.rainbow.model.acme.swim.commands.SwimCommandFactory; + +public class IncDimmerPlan extends SwimExtendedPlan { + + private boolean m_outcome; + private IModelsManagerPort m_modelsManager; + + //private SwimModelUpdateOperatorsImpl m_model; + private AcmeModelInstance m_reference; + + public IncDimmerPlan (AcmeModelInstance m) { + //m_instructionGraph = instructionGraph; + m_reference = m; + + } + + @Override + public Object evaluate(Object[] argsIn) { + IAdaptationExecutor executor = + Rainbow.instance().getRainbowMaster().strategyExecutor + (m_reference.getModelName() + ":" + m_reference.getModelType()); + SwimCommandFactory cf = (SwimCommandFactory) m_reference.getCommandFactory(); + IncDimmerCmd cmd = cf.incDimmerCmd(m_reference.getModelInstance().getComponent("LB0")); + System.out.println ("Changing Instructions"); + if (executor == null) { + System.out.println("executor null"); return false; + } + OperationResult result = executor.getOperationPublishingPort().publishOperation(cmd); + m_outcome = result.result == Result.SUCCESS; + System.out.println ("Done"); + return m_outcome; + } + + @Override + public boolean getOutcome() { + // TODO Auto-generated method stub + return m_outcome; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/OperaWrapper.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/OperaWrapper.java new file mode 100644 index 000000000..5b1c9f0e8 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/OperaWrapper.java @@ -0,0 +1,267 @@ +package org.sa.rainbow.swim.adaptation; + +import java.io.File; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map.Entry; + +import opera.OperaModel; +import opera.KalmanFilter.EstimationResults; +import opera.KalmanFilter.KalmanConfiguration; +import opera.KalmanFilter.KalmanEstimator; +import Application.Configuration.ConfigurationManager; +import Application.Configuration.MetricMappingsConfigurationSection; +import Framework.Diagnostics.Trace; +import Framework.Monitoring.Data.MetricValues; + + +public class OperaWrapper { + + private static final String BALANCER = "[Balancer]"; + private static final String WEB_CLUSTER = "WebCluster"; + /** + * Data for the builder. + */ + private File m_buildSModelFile = null; + private File m_buildSFilterFile = null; + + OperaModel theModel = null; + KalmanEstimator theEstimator = null; + + // contains metrics that need to be inserted into the model from the monitoring component + HashMap mapMetricsToModel; + + HashMap mapMetricsToFilter; + + public OperaWrapper() { + System.out.println("OperaWrapper()"); + } + + public boolean configure(File configFile) + { + System.out.println("configure(" + configFile + ")"); + try { + Trace.WriteLine("trying trace"); + } catch (Exception e) { + e.printStackTrace(); + } + System.out.println("after Trace"); + ConfigurationManager.Configure(configFile.getPath()); + m_buildSModelFile = new File(configFile.getParentFile(), ConfigurationManager.GetSetting("OperaModel")); + m_buildSFilterFile = new File(configFile.getParentFile(), ConfigurationManager.GetSetting("FilterConfig")); + System.out.println("OperaModel=" + m_buildSModelFile + " FilterConfig=" + m_buildSFilterFile); + + if (false == this.Validate()) + { + System.out.println("HognaEngine doesn't have all the components it needs. " + + "Make sure that the model " + + "is corectly specified and the files exist and are accesible."); + return false; + } + System.out.println("OperaWrapper configured"); + return true; + } + + public void updateModel(int numServers, double avgCpuUtilization, + double arrivalRate, double responseTime, double throughput, + double lowArrivalRate, double lowResponseTime, double lowThroughput) { + MetricValues metricValues = new MetricValues(); + + theModel.SetNodeMultiplicity("WebHost", numServers); +/* + * + + + + + + + + + + + + + */ + metricValues.AddMetricValue(WEB_CLUSTER, BALANCER, "Users normal", arrivalRate); + metricValues.AddMetricValue(WEB_CLUSTER, BALANCER, "Users low", lowArrivalRate); + + metricValues.AddMetricValue(WEB_CLUSTER, "fakeSingle", "CPUUtilization", avgCpuUtilization); + metricValues.AddMetricValue(WEB_CLUSTER, BALANCER, "Response Time normal", responseTime); + metricValues.AddMetricValue(WEB_CLUSTER, BALANCER, "Response Time low", lowResponseTime); + metricValues.AddMetricValue(WEB_CLUSTER, BALANCER, "Throughput normal", throughput); + metricValues.AddMetricValue(WEB_CLUSTER, BALANCER, "Throughput low", lowThroughput); + + UpdateModel(metricValues); + } + + public double[] getParamEstimates() { + double[] results = new double[2]; + results[0] = theModel.GetCpuDemand("normal", "WebServer"); + results[1] = theModel.GetCpuDemand("low", "WebServer"); + return results; + } + + /** + * Solves the performance model and returns the average response time + * + * @param servers + * @param arrivalRate + * @param brownoutFactor + * @return average response time + */ + public double solveModel(int servers, double arrivalRate, double brownoutFactor) { + if (arrivalRate == 0) { + return 0.0; + } + + // clone model + StringWriter modelString = new StringWriter(); + theModel.SaveModel(modelString); + + OperaModel tempModel = new OperaModel(); + tempModel.setModelFromString(modelString.toString()); + + + tempModel.SetNodeMultiplicity("WebHost", servers); + tempModel.SetXPathModelNodesValue("/Model/Workloads/WorkloadMixes/Mix[@scenario='normal']/@load", + String.valueOf(arrivalRate * (1 - brownoutFactor))); + tempModel.SetXPathModelNodesValue("/Model/Workloads/WorkloadMixes/Mix[@scenario='low']/@load", + String.valueOf(arrivalRate * brownoutFactor)); + + double avgResponseTime = Double.MAX_VALUE; + try { + tempModel.solve(); + double throughputLow = tempModel.GetThroughput("low"); + double throughputNormal = tempModel.GetThroughput("normal"); + double responseTimeLow = tempModel.GetResponseTimeScenario("low"); + double responseTimeNormal = tempModel.GetResponseTimeScenario("normal"); + + avgResponseTime = (throughputLow * responseTimeLow + throughputNormal * responseTimeNormal) + / (throughputLow + throughputNormal); + } + catch (Exception e) + { + System.out.println("OperaWrapper.solve(): " + e.toString()); + } + + return avgResponseTime; + } + + void UpdateModel(MetricValues theMetrics) + { + // put the extracted workload into the model + for (Entry entry : this.mapMetricsToModel.entrySet()) + { + String[] strMetric = entry.getKey().split("/"); + double value = 0; + if (strMetric[2].equals("Average")) + { + value = theMetrics.GetMetricValueAverage(strMetric[1], strMetric[3]); + } + else + { + value = theMetrics.GetMetricValue(strMetric[1], strMetric[2], strMetric[3]); + } + + this.theModel.SetXPathModelNodesValue(entry.getValue(), String.valueOf(value)); + } + + + // put the extracted performance metrics into kalman + double[] trackedMetricValues = new double[this.mapMetricsToFilter.size()]; + for (Entry entry : this.mapMetricsToFilter.entrySet()) + { + String[] strMetric = entry.getKey().split("/"); + double value = 0; + if (strMetric[2].equals("Average")) + { + value = theMetrics.GetMetricValueAverage(strMetric[1], strMetric[3]); + } + else + { + value = theMetrics.GetMetricValue(strMetric[1], strMetric[2], strMetric[3]); + } + + trackedMetricValues[entry.getValue()] = value; + } + + + // run kalman filter to fix the model + try + { + EstimationResults results = this.theEstimator.EstimateModelParameters(trackedMetricValues); + System.out.println(results.toString()); + } + catch (Exception e) + { + System.out.println("Singular matrix -- cannot calibrate the model (most likely this means there is a problem with the metrics)."); + System.out.println(e.toString()); + e.printStackTrace(); + } + + // out: a model that is properly calibrated + +// long start = System.currentTimeMillis(); +// theModel.solve(); +// long end = System.currentTimeMillis(); +// System.out.println("solve took " + Long.toString(end - start) + "ms"); + +// System.out.println("saving models"); +// theModel.SaveModelToXmlFile("operamodel.xml"); +// theModel.SaveResultsToXmlFile("operaresults.xml"); +// System.out.println("saved models"); + } + + private void ValidateModel() + { + theModel = new OperaModel(); + theModel.setModel(m_buildSModelFile.getPath()); + } + + private void ValidateFilter() + { + KalmanConfiguration kalmanConfig = new KalmanConfiguration(); + kalmanConfig.withConfigFile(m_buildSFilterFile.getPath()) + .withModel(theModel) + .withSetting(KalmanConfiguration.ITERATIONS_MAX, "20"); + theEstimator = new KalmanEstimator(kalmanConfig); + } + + private void ValidateMetricsMappings() + { + MetricMappingsConfigurationSection secMetricMappings = (MetricMappingsConfigurationSection)ConfigurationManager.GetSection("metricMappings"); + + if (secMetricMappings != null) + { + this.mapMetricsToModel = secMetricMappings.GetMetricsToModelMappings(); + this.mapMetricsToFilter = secMetricMappings.GetMetricsToFilterMappings(); + } + } + + private boolean Validate() + { + // validate the model + try + { + this.ValidateModel(); + this.ValidateFilter(); + this.ValidateMetricsMappings(); + } + catch (Exception ex) + { + // reset the object to un-usable state + System.out.println("OperaWrapper.Validate():" + ex.toString()); + ex.printStackTrace(); + this.theModel = null; + this.theEstimator = null; + throw ex; + } + finally + { + } + + return true; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/RemoveServerPlan.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/RemoveServerPlan.java new file mode 100644 index 000000000..d9caa152b --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/RemoveServerPlan.java @@ -0,0 +1,49 @@ +package org.sa.rainbow.swim.adaptation; + +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.OperationResult; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort.Result; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.swim.commands.RemoveServerWithTypeCmd; +import org.sa.rainbow.model.acme.swim.commands.SwimCommandFactory; + +public class RemoveServerPlan extends SwimExtendedPlan { + + private String m_server; + private boolean m_outcome; + private IModelsManagerPort m_modelsManager; + + //private SwimModelUpdateOperatorsImpl m_model; + private AcmeModelInstance m_reference; + + // server is either 1, 2, or 3 + public RemoveServerPlan (AcmeModelInstance m, String server) { + m_reference = m; + m_server = server; + } + + @Override + public Object evaluate(Object[] argsIn) { + IAdaptationExecutor executor = + Rainbow.instance().getRainbowMaster().strategyExecutor + (m_reference.getModelName() + ":" + m_reference.getModelType()); + if (executor == null) { + System.out.println("executor null"); return false; + } + SwimCommandFactory cf = (SwimCommandFactory) m_reference.getCommandFactory(); + RemoveServerWithTypeCmd cmd = cf.removeServerWithTypeCmd(m_reference.getModelInstance().getComponent("LB0"), m_server); + System.out.println ("Changing Instructions"); + OperationResult result = executor.getOperationPublishingPort().publishOperation(cmd); + m_outcome = result.result == Result.SUCCESS; + System.out.println ("Done: " + m_outcome); + return m_outcome; + } + + @Override + public boolean getOutcome() { + // TODO Auto-generated method stub + return m_outcome; + } +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/SwimExtendedExecutor.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/SwimExtendedExecutor.java new file mode 100644 index 000000000..75a9eb83a --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/SwimExtendedExecutor.java @@ -0,0 +1,132 @@ +package org.sa.rainbow.swim.adaptation; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.sa.rainbow.core.AbstractRainbowRunnable; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowMaster; +import org.sa.rainbow.core.adaptation.AdaptationTree; +import org.sa.rainbow.core.adaptation.DefaultAdaptationExecutorVisitor; +import org.sa.rainbow.core.adaptation.IAdaptationExecutor; +import org.sa.rainbow.core.adaptation.IAdaptationManager; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.gauges.IGauge; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.IModelDSBusPublisherPort; +import org.sa.rainbow.core.ports.IRainbowAdaptationDequeuePort; +import org.sa.rainbow.core.ports.IRainbowReportingPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; + +public class SwimExtendedExecutor extends AbstractRainbowRunnable + implements IAdaptationExecutor { + + private final class SWIMEXTExecutionVisitor extends DefaultAdaptationExecutorVisitor { + private IRainbowReportingPort m_reporter; + + public SWIMEXTExecutionVisitor(AdaptationTree adt, ThreadGroup tg, String threadName, + CountDownLatch done, IRainbowReportingPort reporter) { + super(adt, tg, threadName, done, reporter); + m_reporter = reporter; + } + + @Override + protected boolean evaluate(SwimExtendedPlan adaptation) { + Object evaluate = adaptation.evaluate (new Object[0]); + if (evaluate instanceof Boolean) return ((Boolean )evaluate); + return false; + } + + @Override + protected DefaultAdaptationExecutorVisitor spawnNewExecutorForTree( + AdaptationTree adt, ThreadGroup g, CountDownLatch doneSignal) { + return new SWIMEXTExecutionVisitor (adt, g, "SWIMEXT", doneSignal, m_reporter); + } + } + + + public static final String NAME = "Swim Extended Plan Executor"; + private ModelReference m_modelRef; + private IRainbowAdaptationDequeuePort m_adaptationDQPort; + private IModelDSBusPublisherPort m_modelDSPort; + private java.lang.ThreadGroup m_executionThreadGroup; + /** + * Default Constructor with name for the thread. + */ + public SwimExtendedExecutor () { + super (NAME); + } + + @Override + public void initialize (IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize (port); + + // Create the model DS port where operations go (and effectors listen) + m_modelDSPort = RainbowPortFactory.createModelDSPublishPort (this); + } + + + @Override + public void dispose() { + if (m_adaptationDQPort != null) { + m_adaptationDQPort.dispose (); + } + m_modelDSPort.dispose (); + m_reportingPort.dispose (); + } + + @Override + public void setModelToManage(ModelReference modelRef) { + m_modelRef = modelRef; + m_adaptationDQPort = RainbowPortFactory.createAdaptationDequeuePort (m_modelRef); + m_executionThreadGroup = new ThreadGroup (m_modelRef.toString () + " ThreadGroup"); + + } + @Override + public IModelDSBusPublisherPort getOperationPublishingPort() { + return m_modelDSPort; + } + @Override + public IRainbowReportingPort getReportingPort() { + return m_reportingPort; + } + @Override + protected void log(String txt) { + m_reportingPort.info (RainbowComponentT.EXECUTOR, txt); + } + @Override + protected void runAction() { + if (m_adaptationDQPort != null && !m_adaptationDQPort.isEmpty ()) { + AdaptationTree at = m_adaptationDQPort.dequeue (); + log ("Got a new plan -- executing"); + CountDownLatch latch = new CountDownLatch (1); + SWIMEXTExecutionVisitor executor = new SWIMEXTExecutionVisitor + (at, m_executionThreadGroup, "SWIMEXT Execution", latch, m_reportingPort); + executor.start(); + try { + latch.await (20, TimeUnit.SECONDS); + } + catch (InterruptedException e) { + e.printStackTrace (); + } + + if (!Rainbow.instance ().shouldTerminate ()) { + final IAdaptationManager adaptationManager = Rainbow.instance ().getRainbowMaster () + .adaptationManagerForModel (this.m_modelRef.toString ()); + if (adaptationManager != null) { + adaptationManager.markStrategyExecuted (at); + } else { + log("AM null"); + } + } + } + } + @Override + public RainbowComponentT getComponentType() { + return RainbowComponentT.EXECUTOR; + } + + + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/SwimExtendedPlan.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/SwimExtendedPlan.java new file mode 100644 index 000000000..34e7cce03 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/SwimExtendedPlan.java @@ -0,0 +1,19 @@ +package org.sa.rainbow.swim.adaptation; + +import org.sa.rainbow.core.adaptation.IEvaluable; + +public abstract class SwimExtendedPlan implements IEvaluable { + + // Evaluates (executes) the plan, returning a result + @Override + public abstract Object evaluate(Object[] argsIn); + + // This is deprecated (?) + @Override + public long estimateAvgTimeCost() { + // TODO Auto-generated method stub + return 0; + } + + public abstract boolean getOutcome(); +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/SwimUtilityFunction.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/SwimUtilityFunction.java new file mode 100644 index 000000000..3de922ca1 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/swim/adaptation/SwimUtilityFunction.java @@ -0,0 +1,92 @@ +package org.sa.rainbow.swim.adaptation; + +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.swim.SwimModelHelper; + +import pladapt.GenericConfiguration; +import pladapt.GenericEnvironment; +import pladapt.GenericUtilityFunction; + +public class SwimUtilityFunction extends GenericUtilityFunction { + + private SwimModelHelper m_modelHelper = null; + + SwimUtilityFunction(AcmeModelInstance model, SwimModelHelper swimModel) { + m_modelHelper = swimModel; + } + + //***************************************************************** + // Queuing model G/G/c LPS with round-robin allocation to servers + //***************************************************************** + private double responseTime(int servers, int threads, double arrivalRateMean, double arrivalRateVariance, + double brownoutFactor, double lowServiceTimeMean, double lowServiceTimeVariance, double serviceTimeMean, + double serviceTimeVariance) { + if (arrivalRateMean == 0) { + return 0; + } + double lambda = arrivalRateMean / servers; + double beta = brownoutFactor * lowServiceTimeMean + (1-brownoutFactor) * serviceTimeMean; + double rho = lambda * beta; + double ca2 = servers / (arrivalRateVariance * Math.pow(servers / arrivalRateMean, 2)); + double cs2 = (brownoutFactor * lowServiceTimeVariance + (1 - brownoutFactor) * serviceTimeVariance) + / Math.pow(beta, 2); + double dp = Math.pow(rho, threads * (1+cs2)/(ca2 + cs2)); + double rb = ((ca2 + cs2) / 2) * dp * beta / (1 - rho); + double rz = ((ca2 + cs2) / (1 + cs2)) * (1 - dp) * beta / (1 - rho); + double rt= (rho > 1 ? Double.MAX_VALUE : (rb + rz)); + + return rt; + } + + public double getGenAdditiveUtility(GenericConfiguration config, GenericEnvironment env, int time) { + double predictedResponseTime = responseTime( + m_modelHelper.getNumActiveServers(config), + m_modelHelper.getNumThreadsPerServer(), + env.getDouble(SwimModelHelper.ENV_ARRIVAL_RATE_MEAN), + env.getDouble(SwimModelHelper.ENV_ARRIVAL_RATE_VARIANCE), + (1 - m_modelHelper.getDimmer(config)), + m_modelHelper.getEstimatedBasicServiceTime(), + m_modelHelper.getEstimatedBasicServiceTimeVariance(), + m_modelHelper.getEstimatedOptServiceTime(), + m_modelHelper.getEstimatedOptServiceTimeVariance()); + +// System.out.println("getGenAdditiveUtility(" + config + ", " + env + ") -> rt=" + predictedResponseTime); + return getUtility(config, env, predictedResponseTime); + } + + + /** + * returns utility per unit of time; + * + * This function is used to drive decisions, so it may give results that force decisions in certain + * way, but are not actual utility accrued (e.g., penalizing not adding servers when the system is overloaded) + */ + private double getUtility(GenericConfiguration config, GenericEnvironment env, double avgResponseTime) + { + int numServers = m_modelHelper.getNumServers(config); + double cost = numServers; + double brownoutRevenue = 1; + double normalRevenue = 1.5; + double spacing = m_modelHelper.getMaxServers() + 1; // to spread apart utility values to rank by number of servers + double maxThroughput = m_modelHelper.getMaxServers() * m_modelHelper.getMaximumCapacity(); + double latePenalty = maxThroughput * normalRevenue * spacing; + + // TODO this is arrival rate, not really throughput + // Using arrival rate is just an approximation. Fixing it would require computing the throughput with a perf model + double arrivalRateMean = env.asDouble(); + double throughput = arrivalRateMean; + + double brownoutFactor = 1 - m_modelHelper.getDimmer(config); + + double positiveUtility = Math.round((throughput * (brownoutFactor * brownoutRevenue + (1 - brownoutFactor) * normalRevenue))) + * spacing; + + double utility = ((avgResponseTime > m_modelHelper.getRTThreshold() || avgResponseTime < 0) ? Math.min(0.0, throughput * normalRevenue * spacing - latePenalty) : positiveUtility) - cost; + if (avgResponseTime == Double.MAX_VALUE || avgResponseTime < 0) { + utility = (-latePenalty - 2 * spacing + numServers + brownoutFactor); + } + + return utility; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/ObserveCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/ObserveCmd.java new file mode 100644 index 000000000..e24a8bed2 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/ObserveCmd.java @@ -0,0 +1,49 @@ +package org.sa.rainbow.timeseriespredictor.model; + +import java.util.List; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class ObserveCmd extends AbstractRainbowModelOperation { + + private Double m_value; + + public ObserveCmd (TimeSeriesPredictorModelInstance model, String bogusTarget, String value) { + super ("observe", model, bogusTarget, value); + m_value = Double.valueOf (value); + } + + @Override + public Object getResult () throws IllegalStateException { + return null; + } + + @Override + protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { + return generateEvents (messageFactory, "TimeSeriesPredictorModelOperation"); + } + + @Override + protected void subExecute () throws RainbowException { + m_modelContext.getModelInstance ().observe (m_value); + } + + @Override + protected void subRedo () throws RainbowException { + m_modelContext.getModelInstance ().observe (m_value); + } + + @Override + protected void subUndo () throws RainbowException { + throw new RainbowException("Undo not supported for " + super.getName()); + } + + @Override + protected boolean checkModelValidForCommand (TimeSeriesPredictorModel model) { + return true; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/SetHorizonCmd.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/SetHorizonCmd.java new file mode 100644 index 000000000..aaa7184b5 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/SetHorizonCmd.java @@ -0,0 +1,49 @@ +package org.sa.rainbow.timeseriespredictor.model; + +import java.util.List; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class SetHorizonCmd extends AbstractRainbowModelOperation { + + private Integer m_value; + + public SetHorizonCmd (TimeSeriesPredictorModelInstance model, String bogusTarget, String value) { + super ("setHorizon", model, bogusTarget, value); + m_value = Integer.valueOf (value); + } + + @Override + public Object getResult () throws IllegalStateException { + return null; + } + + @Override + protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { + return generateEvents (messageFactory, "TimeSeriesPredictorModelOperation"); + } + + @Override + protected void subExecute () throws RainbowException { + m_modelContext.getModelInstance ().setHorizon (m_value); + } + + @Override + protected void subRedo () throws RainbowException { + m_modelContext.getModelInstance ().setHorizon (m_value); + } + + @Override + protected void subUndo () throws RainbowException { + throw new RainbowException("Undo not supported for " + super.getName()); + } + + @Override + protected boolean checkModelValidForCommand (TimeSeriesPredictorModel model) { + return true; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModel.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModel.java new file mode 100644 index 000000000..63a583930 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModel.java @@ -0,0 +1,110 @@ +package org.sa.rainbow.timeseriespredictor.model; +import java.util.Vector; + +import org.sa.rainbow.core.error.RainbowException; + +import pladapt.EnvironmentDTMCPartitioned; +import pladapt.TimeSeriesPredictor; + +public class TimeSeriesPredictorModel implements Cloneable { + + private enum ObservationFeeder { AVERAGE, LAST }; + private ObservationFeeder ObservationFeederMode = ObservationFeeder.LAST; + + TimeSeriesPredictor m_predictor; + String m_modelArgs; + long m_trainingLength; + int m_horizon = -1; + + /** + * Since it is hard to synchronize observations from gauges with + * the evaluation period, the observations are stored here + * until it is time to generate the environment DTMC. At that point, + * the average of the observations is fed as a single observation + * to the predictor. That way, we get one observation per evaluation + * period. + */ + Vector m_observations = new Vector(); + + /** + * load PLADAPT wrapper + */ + static { + System.loadLibrary("pladapt_wrap"); + } + + public TimeSeriesPredictorModel (String modelArgs, long trainingLength) { + m_modelArgs = modelArgs; + m_trainingLength = trainingLength; + } + + public void observe(double value) { + m_observations.add(Double.valueOf(value)); + } + + protected void feedObservations() { + if (!m_observations.isEmpty()) { + double observation = 0; + if (ObservationFeederMode == ObservationFeeder.AVERAGE) { + double sum = 0; + for (Double o : m_observations) { + sum += o.doubleValue(); + } + + observation = sum / m_observations.size(); + } else { + observation = m_observations.lastElement(); + } + + if (m_predictor == null) { + m_predictor = TimeSeriesPredictor.getInstance(m_modelArgs, m_trainingLength, m_horizon); + } + + m_predictor.observe(observation); + m_observations.clear(); + } + } + + public void setHorizon(int value) throws RainbowException { + if (m_predictor != null) { + throw new RainbowException("TimeSeriesPredictorModel: attempt to set horizon after first observation"); + } + m_horizon = value; + } + + /** + * Generates environment DTMC + * + * @param branchingDepth + * @param depth + * @return null if no observation has been made + */ + public EnvironmentDTMCPartitioned generateEnvironmentDTMC(int branchingDepth, int depth) { + EnvironmentDTMCPartitioned envDTMC = null; + feedObservations(); + if (m_predictor != null) { + envDTMC = m_predictor.generateEnvironmentDTMC(branchingDepth, depth); + } + return envDTMC; + } + + /** + * Returns a one step ahead prediction + * + * @return prediction, or null if no prediction can be made (no observations yet) + */ + public Double getSimplePrediction() { + feedObservations(); + if (m_predictor == null) { + return null; // no observations yet + } + double[] predictions = new double[1]; + m_predictor.predict(0, Double.MAX_VALUE, 1, predictions); + return Double.valueOf(predictions[0]); + } + + @Override + public Object clone () throws CloneNotSupportedException { + throw new CloneNotSupportedException("TimeSeriesPredictorModel"); + } +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelCommandFactory.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelCommandFactory.java new file mode 100644 index 000000000..e4b40b6a7 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelCommandFactory.java @@ -0,0 +1,45 @@ +package org.sa.rainbow.timeseriespredictor.model; + +import java.io.InputStream; + +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class TimeSeriesPredictorModelCommandFactory extends ModelCommandFactory { + + public static TimeSeriesPredictorModelLoadModelCommand loadCommand (ModelsManager mm, + String modelName, + InputStream stream, + String source) { + return new TimeSeriesPredictorModelLoadModelCommand (mm, modelName, stream, source); + } + + public TimeSeriesPredictorModelCommandFactory (TimeSeriesPredictorModelInstance model) { + super (model.getClass (), model); + + } + + @Override + protected void fillInCommandMap () { + m_commandMap.put("Observe".toLowerCase (), ObserveCmd.class); + m_commandMap.put("SetHorizon".toLowerCase (), SetHorizonCmd.class); + } + + @Override + public AbstractSaveModelCmd saveCommand (String location) throws RainbowModelException { + // TODO Auto-generated method stub + return null; + } + + public ObserveCmd observeCmd (double value) { + return new ObserveCmd ((TimeSeriesPredictorModelInstance) m_modelInstance, "", Double.toString (value)); + } + + public SetHorizonCmd setHorizonCmd (int value) { + return new SetHorizonCmd ((TimeSeriesPredictorModelInstance) m_modelInstance, "", Integer.toString (value)); + } + + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelInstance.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelInstance.java new file mode 100644 index 000000000..aeee9b938 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelInstance.java @@ -0,0 +1,78 @@ +package org.sa.rainbow.timeseriespredictor.model; + +import org.sa.rainbow.core.error.RainbowCopyException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class TimeSeriesPredictorModelInstance implements IModelInstance { + + public static final String MODEL_TYPE = "TSP"; + private TimeSeriesPredictorModel m_model; + private String m_attachedToModel; + private String m_source; + private TimeSeriesPredictorModelCommandFactory m_commandFactory; + + public TimeSeriesPredictorModelInstance (TimeSeriesPredictorModel pModel, String attachedToModel, String source) { + setModelInstance (pModel); + setOriginalSource (source); + m_attachedToModel = attachedToModel; + } + + @Override + public TimeSeriesPredictorModel getModelInstance () { + return m_model; + } + + @Override + public void setModelInstance (TimeSeriesPredictorModel model) { + m_model = model; + } + + @Override + public IModelInstance copyModelInstance (String newName) throws RainbowCopyException { + try { + return new TimeSeriesPredictorModelInstance ((TimeSeriesPredictorModel )m_model.clone (), m_attachedToModel, + getOriginalSource ()); + } + catch (CloneNotSupportedException e) { + return null; + } + } + + @Override + public String getModelType () { + return MODEL_TYPE; + } + + @Override + public String getModelName () { + return m_attachedToModel; + } + + @Override + public ModelCommandFactory getCommandFactory () { + if (m_commandFactory == null) { + m_commandFactory = new TimeSeriesPredictorModelCommandFactory (this); + } + return m_commandFactory; + } + + @Override + public void setOriginalSource (String source) { + m_source = source; + } + + @Override + public String getOriginalSource () { + return m_source; + } + + @Override + public void dispose () throws RainbowException { + m_source = null; + m_model = null; + m_attachedToModel = null; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelLoadModelCommand.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelLoadModelCommand.java new file mode 100644 index 000000000..32cff22b5 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelLoadModelCommand.java @@ -0,0 +1,59 @@ +package org.sa.rainbow.timeseriespredictor.model; + +import java.io.InputStream; + +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; + +public class TimeSeriesPredictorModelLoadModelCommand extends AbstractLoadModelCmd { + + private static final String PROP_ARGS = "customize.model.timeseriespredictor.args"; + public static final String PROP_TRAININGLENGTH = "customize.model.timeseriespredictor.traininglength"; + private String m_name; + private TimeSeriesPredictorModelInstance m_result; + + public TimeSeriesPredictorModelLoadModelCommand (IModelsManager mm, String modelName, InputStream is, String source) { + super ("loadTimeSeriesPredictorModel", mm, modelName, is, source); + m_name = modelName; + } + + @Override + public IModelInstance getResult () throws IllegalStateException { + return m_result; + } + + @Override + public ModelReference getModelReference () { + return new ModelReference (m_name, TimeSeriesPredictorModelInstance.MODEL_TYPE); + } + + @Override + protected void subExecute () throws RainbowException { + String modelArgs = Rainbow.instance ().getProperty (PROP_ARGS); + int trainingLength = Integer.parseInt(Rainbow.instance ().getProperty (PROP_TRAININGLENGTH)); + + TimeSeriesPredictorModel pm = new TimeSeriesPredictorModel (modelArgs, trainingLength); + m_result = new TimeSeriesPredictorModelInstance(pm, getModelReference().getModelName(), ""); + doPostExecute (); + } + + @Override + protected void subRedo () throws RainbowException { + doPostExecute (); + } + + @Override + protected void subUndo () throws RainbowException { + doPostUndo (); + } + + @Override + protected boolean checkModelValidForCommand (Object model) { + return true; + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java new file mode 100644 index 000000000..d9fd7a098 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java @@ -0,0 +1,96 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.swim.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Gauge for marking servers as active or not + * + * @author gmoreno + */ +public class ServerActiveGauge extends RegularPatternGauge { + + public static final String NAME = "G - ServerActive"; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "serverActivated" + }; + private static final String DEFAULT = "DEFAULT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public ServerActiveGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile (".*")); + } + + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + //System.out.println(" Inside ServerActiveGauge::doMatch"); + + if (matchName == DEFAULT) { + int numServers = Integer.parseInt(m.group(0)); + int thisServer = (int) m_configParams.get("serverNum").getValue(); + + //boolean serverActive = numServers >= thisServer; + boolean serverActive = (numServers == 1) ? true : false; + //System.out.println("Server " + thisServer + ": Updating server active to " + serverActive); + + m_reportingPort.trace (getComponentType (), "Updating server active condition to " + serverActive); + if (m_commands.containsKey (valueNames[0])) { + IRainbowOperation cmd = getCommand (valueNames[0]); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], (serverActive) ? "true" : "false"); + issueCommand (cmd, parameterMap); + } + } + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java new file mode 100644 index 000000000..28fbf485f --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java @@ -0,0 +1,95 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.swim.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Gauge for marking servers as enabled or not + * + * @author gmoreno + */ +public class ServerEnabledGauge extends RegularPatternGauge { + + public static final String NAME = "G - ServerEnabled"; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "serverEnabled" + }; + private static final String DEFAULT = "DEFAULT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public ServerEnabledGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile (".*")); + } + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + //System.out.println(" Inside ServerEnabledGauge::doMatch"); + + if (matchName == DEFAULT) { + int numServers = Integer.parseInt(m.group(0)); + int thisServer = (int) m_configParams.get("serverNum").getValue(); + + //boolean serverEnabled = numServers >= thisServer; + boolean serverEnabled = (numServers == 1) ? true : false; + + //System.out.println("Server " + thisServer + ": Updating server enablement to " + serverEnabled); + m_reportingPort.trace (getComponentType (), "Updating server enablement to " + serverEnabled); + if (m_commands.containsKey (valueNames[0])) { + IRainbowOperation cmd = getCommand (valueNames[0]); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], (serverEnabled) ? "true" : "false"); + issueCommand (cmd, parameterMap); + } + } + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java new file mode 100644 index 000000000..284439232 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java @@ -0,0 +1,84 @@ +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.swim.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Simple gauge: complete probe output passed as arg to command + * + * @author gmoreno + */ +public class SimpleGauge extends RegularPatternGauge { + + public static final String NAME = "G - SimpleGauge"; + + private static final String DEFAULT = "DEFAULT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public SimpleGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile (".*")); + } + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + String value = m.group(0); + String commandName = m_commands.keySet().iterator().next(); + m_reportingPort.trace (getComponentType (), + "Updating component prop using command " + + commandName + " and value = " + value); + IRainbowOperation cmd = getCommand (commandName); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], value); + issueCommand (cmd, parameterMap); + } + } + +} diff --git a/deployments/rainbow-swim-hybrid/src/test/resources/acme/imports.acme b/deployments/rainbow-swim-hybrid/src/test/resources/acme/imports.acme new file mode 100644 index 000000000..9050035ed --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/test/resources/acme/imports.acme @@ -0,0 +1,4 @@ +import "families/f1.acme"; +system s : f1 = new f1 extended with { + component c : CT = new CT; +} \ No newline at end of file diff --git a/deployments/rainbow-swim-hybrid/src/test/resources/acme/inbuilt-system.acme b/deployments/rainbow-swim-hybrid/src/test/resources/acme/inbuilt-system.acme new file mode 100644 index 000000000..addb5fe5b --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/test/resources/acme/inbuilt-system.acme @@ -0,0 +1,9 @@ +family f1 = { + + component type CT = { + property p : int; + } +} +system s : f1 = new f1 extended with { + component c : CT = new CT; +} \ No newline at end of file diff --git a/deployments/rainbow-swim-hybrid/src/test/resources/acme/self-contained.acme b/deployments/rainbow-swim-hybrid/src/test/resources/acme/self-contained.acme new file mode 100644 index 000000000..a019b82c9 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/test/resources/acme/self-contained.acme @@ -0,0 +1,3 @@ +system s = { + component c; +} \ No newline at end of file diff --git a/deployments/rainbow-swim-hybrid/src/test/resources/acme/znn.acme b/deployments/rainbow-swim-hybrid/src/test/resources/acme/znn.acme new file mode 100644 index 000000000..5da216500 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/test/resources/acme/znn.acme @@ -0,0 +1,270 @@ +Family ZNewsFam = { + + Port Type HttpPortT = { + + } + Role Type RequestorRoleT = { + + } + Component Type ProxyT = { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Port Type ProxyForwardPortT = { + + } + Component Type ServerT = { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + Property reqServiceRate : float << default : float = 0.0; >> ; + + Property byteServiceRate : float << default : float = 0.0; >> ; + + Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; + + Property cost : float << default : float = 1.0; >> ; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + Role Type ReceiverRoleT = { + + } + Connector Type ProxyConnT = { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Component Type ClientT = { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property experRespTime : float << default : float = 0.0; >> ; + + Property reqRate : float << default : float = 0.0; >> ; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + Port Type HttpReqPortT = { + + } + Connector Type HttpConnT = { + + Property bandwidth : float << default : float = 0.0; >> ; + + Property latency : float << default : float = 0.0; >> ; + + Property numReqsSuccess : int << default : int = 0; >> ; + + Property numReqsRedirect : int << default : int = 0; >> ; + + Property numReqsClientError : int << default : int = 0; >> ; + + Property numReqsServerError : int << default : int = 0; >> ; + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + + Property MIN_RESPTIME : float; + + Property MAX_RESPTIME : float; + + Property TOLERABLE_PERCENT_UNHAPPY : float; + + Property UNHAPPY_GRADIENT_1 : float; + + Property UNHAPPY_GRADIENT_2 : float; + + Property UNHAPPY_GRADIENT_3 : float; + + Property FRACTION_GRADIENT_1 : float; + + Property FRACTION_GRADIENT_2 : float; + + Property FRACTION_GRADIENT_3 : float; + + Property MIN_UTIL : float; + + Property MAX_UTIL : float; + + Property MAX_FIDELITY_LEVEL : int; + + Property THRESHOLD_FIDELITY : int; + + Property THRESHOLD_COST : float; +} + +System ZNewsSys : ZNewsFam = { + + + Property MIN_RESPTIME : float = 100; + + Property MAX_RESPTIME : float = 2000; + + Property UNHAPPY_GRADIENT_1 : float = 0.1; + + Property UNHAPPY_GRADIENT_2 : float = 0.2; + + Property UNHAPPY_GRADIENT_3 : float = 0.5; + + Property FRACTION_GRADIENT_1 : float = 0.2; + + Property FRACTION_GRADIENT_2 : float = 0.4; + + Property FRACTION_GRADIENT_3 : float = 1.0; + + Property TOLERABLE_PERCENT_UNHAPPY : float = 0.25; + + Property MIN_UTIL : float = 0.1; + + Property MAX_UTIL : float = 0.75; + + Property MAX_FIDELITY_LEVEL : int = 5; + + Property THRESHOLD_FIDELITY : int = 2; + + Property THRESHOLD_COST : float = 6.0; + Component s1 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.2"; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component lbproxy : ProxyT = new ProxyT extended with { + + Property deploymentLocation = "127.0.0.1"; + Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port http0 : HttpPortT = new HttpPortT extended with { + + } + Port http1 : HttpPortT = new HttpPortT extended with { + + } + Port http2 : HttpPortT = new HttpPortT extended with { + + } + + } + Component s2 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.3"; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component s3 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.4"; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component s0 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property cost = 1.0; + + Property fidelity = 5; + + Property load = 0.0; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component c0 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50.0; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + } + + } + Component c1 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + } + + } + Component c2 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + } + + } + Connector conn0 : HttpConnT = new HttpConnT extended with { + + } + Connector proxyconn0 : ProxyConnT = new ProxyConnT extended with { + + } + Connector proxyconn1 : ProxyConnT = new ProxyConnT extended with { + + } + Connector proxyconn3 : ProxyConnT = new ProxyConnT extended with { + + } + Connector proxyconn2 : ProxyConnT = new ProxyConnT extended with { + + } + Connector conn : HttpConnT = new HttpConnT extended with { + + } + Connector conn1 : HttpConnT = new HttpConnT extended with { + + } + Attachment lbproxy.fwd0 to proxyconn0.req; + Attachment s2.http0 to proxyconn2.rec; + Attachment lbproxy.fwd1 to proxyconn1.req; + Attachment s1.http0 to proxyconn1.rec; + Attachment s0.http0 to proxyconn0.rec; + Attachment c0.p0 to conn0.req; + Attachment lbproxy.http0 to conn0.rec; + Attachment s3.http0 to proxyconn3.rec; + Attachment lbproxy.fwd3 to proxyconn3.req; + Attachment c1.p0 to conn.req; + Attachment c2.p0 to conn1.req; + Attachment lbproxy.http2 to conn1.rec; + Attachment lbproxy.http1 to conn.rec; +} + diff --git a/deployments/rainbow-swim-hybrid/src/test/resources/log4j.properties b/deployments/rainbow-swim-hybrid/src/test/resources/log4j.properties new file mode 100644 index 000000000..4c0d3a502 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/test/resources/log4j.properties @@ -0,0 +1,4 @@ +log4j.rootLogger=INFO,CONSOLE +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%-5p $c{1} - %m%n diff --git a/deployments/rainbow-swim-hybrid/src/test/resources/log4j.xml b/deployments/rainbow-swim-hybrid/src/test/resources/log4j.xml new file mode 100644 index 000000000..829891348 --- /dev/null +++ b/deployments/rainbow-swim-hybrid/src/test/resources/log4j.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/deployments/rainbow-swim-hybrid/src/test/resources/testdata-project.properties b/deployments/rainbow-swim-hybrid/src/test/resources/testdata-project.properties new file mode 100644 index 000000000..e69de29bb diff --git a/deployments/rainbow-swim/.project b/deployments/rainbow-swim/.project index 69469b608..2ff49bf70 100644 --- a/deployments/rainbow-swim/.project +++ b/deployments/rainbow-swim/.project @@ -1,24 +1,24 @@ - - - rainbow-swim - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - org.eclipse.jdt.core.javanature - org.eclipse.linuxtools.tmf.project.nature - - + + + rainbow-swim + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + org.eclipse.linuxtools.tmf.project.nature + + diff --git a/deployments/rainbow-swim/.settings/org.eclipse.core.resources.prefs b/deployments/rainbow-swim/.settings/org.eclipse.core.resources.prefs index 5213b31e5..ff0ac6e33 100644 --- a/deployments/rainbow-swim/.settings/org.eclipse.core.resources.prefs +++ b/deployments/rainbow-swim/.settings/org.eclipse.core.resources.prefs @@ -1,4 +1,4 @@ -eclipse.preferences.version=1 -encoding//src/main/java=utf-8 -encoding//src/test/resources=utf-8 -encoding/=utf-8 +eclipse.preferences.version=1 +encoding//src/main/java=utf-8 +encoding//src/test/resources=utf-8 +encoding/=utf-8 diff --git a/deployments/rainbow-swim/.settings/org.eclipse.jdt.core.prefs b/deployments/rainbow-swim/.settings/org.eclipse.jdt.core.prefs index f4217b01d..62492222a 100644 --- a/deployments/rainbow-swim/.settings/org.eclipse.jdt.core.prefs +++ b/deployments/rainbow-swim/.settings/org.eclipse.jdt.core.prefs @@ -1,12 +1,12 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.7 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.7 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/deployments/rainbow-swim/.settings/org.eclipse.m2e.core.prefs b/deployments/rainbow-swim/.settings/org.eclipse.m2e.core.prefs index 14b697b7b..f897a7f1c 100644 --- a/deployments/rainbow-swim/.settings/org.eclipse.m2e.core.prefs +++ b/deployments/rainbow-swim/.settings/org.eclipse.m2e.core.prefs @@ -1,4 +1,4 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/deployments/rainbow-swim/Dockerfile-swim b/deployments/rainbow-swim/Dockerfile-swim index c5604d62c..33f06be02 100644 --- a/deployments/rainbow-swim/Dockerfile-swim +++ b/deployments/rainbow-swim/Dockerfile-swim @@ -64,14 +64,10 @@ RUN apt update && DEBIAN_FRONTEND=noninteractive apt-get -y install software-pro RUN sed -i "s/allowed_users=console/allowed_users=anybody/;$ a needs_root_rights=yes" /etc/X11/Xwrapper.config RUN \ - echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && \ - add-apt-repository -y ppa:webupd8team/java && \ + add-apt-repository -y ppa:openjdk-r/ppa && \ apt-get update && \ - apt-get install -y oracle-java8-installer --allow-unauthenticated && \ - rm -rf /var/lib/apt/lists/* && \ - rm -rf /var/cache/oracle-jdk8-installer + apt-get -y install openjdk-8-jdk -ENV JAVA_HOME /usr/lib/jvm/java-8-oracle RUN mkdir /rainbow WORKDIR /rainbow COPY --from=builder /root/pladapt ./pladapt diff --git a/deployments/rainbow-swim/pom.xml b/deployments/rainbow-swim/pom.xml index 57eec1eab..8ea5d8a7a 100644 --- a/deployments/rainbow-swim/pom.xml +++ b/deployments/rainbow-swim/pom.xml @@ -1,4 +1,5 @@ - 4.0.0 rainbow @@ -90,7 +91,7 @@ svn://acme.able.cs.cmu.edu/rainbow/v2/trunk - + @@ -196,7 +197,7 @@ - + maven-dependency-plugin @@ -210,38 +211,111 @@ ${project.build.directory}/lib + + copy + install + + copy + + + + + pladapt + libpladapt_wrap + 1.0.1 + so + x86_64 + ${project.build.directory}/lib + libpladapt_wrap.so + + + + + + + + + org.eclipse.xtext + xtext-maven-plugin + 2.19.0 + + + + generate + + + + 1.8 + 1.8 + + + org.sa.rainbow.configuration.ConfigModelStandaloneSetup + + + src-gen/main/java/ + + + tgt-gen + true + true + true + + + + + + src/main/resources/rbw + + + + + org.sa.rainbow.configuration + org.sa.rainbow.configuration + 1.0.0-SNAPSHOT + + + org.eclipse.emf + org.eclipse.emf.mwe2.launch + 2.11.0 + + + org.eclipse.xtext + org.eclipse.xtext.common.types + 2.19.0 + + + org.eclipse.xtext + org.eclipse.xtext.xtext.generator + 2.19.0 + + + org.eclipse.xtext + org.eclipse.xtext.xbase + 2.19.0 + + + org.eclipse.xtext + xtext-antlr-generator + 2.1.1 + + + + io.typefox.xtext + jflex-fragment + 0.2.1 + + + org.eclipse.xtext + org.eclipse.xtext.xbase.lib + 2.18.0 + + - - org.apache.maven.plugins - maven-dependency-plugin - - - copy - install - - copy - - - - - pladapt - libpladapt_wrap - 1.0.1 - so - x86_64 - ${project.build.directory}/lib - libpladapt_wrap.so - - - - - - - - @@ -254,6 +328,17 @@ dav:http://acme.able.cs.cmu.edu/maven-repository + + codehaus-snapshots + disable dead 'Codehaus Snapshots' repository, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=481478 + http://nexus.codehaus.org/snapshots/ + + false + + + false + + + rainbow rainbow-acme-model - 3.0 + 3.1.0 rainbow rainbow-stitch - 3.0 + 3.1.0 rainbow rainbow-utility-model - 3.0 + 3.1.0 rainbow rainbow-gui - 3.0 + 3.1.0 - rainbow - rainbow-znn - 2.1-SNAPSHOT - - - org.jyaml - jyaml - 1.3 - - - org.apache - xerces - 2.9.0 - ---> - - opera - hogna - 1.0 - - - opera - opera - 1.0 - - - xerces - xercesImpl - 2.12.0 - - - pladapt - pladapt_wrap - 1.0.1 - - - pladapt - libpladapt_wrap - 1.0.1 - runtime - so - x86_64 + rainbow-mem-comms + 3.1.0 + diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/gui/RainbowControl.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/gui/RainbowControl.java index 9d777e507..0c6baa7ad 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/gui/RainbowControl.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/gui/RainbowControl.java @@ -1,56 +1,56 @@ -package org.sa.rainbow.gui; - -import java.text.MessageFormat; -import java.util.EnumSet; - -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.globals.ExitState; -import org.sa.rainbow.core.ports.IMasterCommandPort; -import org.sa.rainbow.core.ports.IMasterConnectionPort.ReportType; -import org.sa.rainbow.core.ports.IRainbowReportingSubscriberPort; -import org.sa.rainbow.core.ports.IRainbowReportingSubscriberPort.IRainbowReportingSubscriberCallback; -import org.sa.rainbow.core.ports.RainbowPortFactory; - -public class RainbowControl { - - private static void usage() { - String usage = MessageFormat.format( - "Usage: {0} command\n\tcommand='{startprobes|killprobes|terminate}'", RainbowControl.class.getSimpleName()); - System.out.println(usage); - } - - public static void main (String[] args) throws RainbowConnectionException { - if (args.length != 1) { - usage(); - return; - } - - IMasterCommandPort master = RainbowPortFactory.createMasterCommandPort (); - IRainbowReportingSubscriberPort reportingSubscriberPort = RainbowPortFactory - .createReportingSubscriberPort (new IRainbowReportingSubscriberCallback () { - - @Override - public void report (RainbowComponentT component, ReportType type, String message) { - if (type == ReportType.ERROR || type == ReportType.FATAL || type == ReportType.WARNING) { - System.out.println (type.name () + ": " + message); - } - if (component == RainbowComponentT.GAUGE) { - System.out.println ("Gauge: " + message); - } - } - }); - reportingSubscriberPort.subscribe (EnumSet.allOf (RainbowComponentT.class), EnumSet.allOf (ReportType.class)); - - if (args[0].equals("startprobes")) { - master.startProbes (); - } else if (args[0].equals("killprobes")) { - master.killProbes(); - } else if (args[0].equals("terminate")) { - master.terminate (ExitState.DESTRUCT); - } else { - usage(); - } - System.exit (1); - } -} +package org.sa.rainbow.gui; + +import java.text.MessageFormat; +import java.util.EnumSet; + +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.globals.ExitState; +import org.sa.rainbow.core.ports.IMasterCommandPort; +import org.sa.rainbow.core.ports.IMasterConnectionPort.ReportType; +import org.sa.rainbow.core.ports.IRainbowReportingSubscriberPort; +import org.sa.rainbow.core.ports.IRainbowReportingSubscriberPort.IRainbowReportingSubscriberCallback; +import org.sa.rainbow.core.ports.RainbowPortFactory; + +public class RainbowControl { + + private static void usage() { + String usage = MessageFormat.format( + "Usage: {0} command\n\tcommand='{startprobes|killprobes|terminate}'", RainbowControl.class.getSimpleName()); + System.out.println(usage); + } + + public static void main (String[] args) throws RainbowConnectionException { + if (args.length != 1) { + usage(); + return; + } + + IMasterCommandPort master = RainbowPortFactory.createMasterCommandPort (); + IRainbowReportingSubscriberPort reportingSubscriberPort = RainbowPortFactory + .createReportingSubscriberPort (new IRainbowReportingSubscriberCallback () { + + @Override + public void report (RainbowComponentT component, ReportType type, String message) { + if (type == ReportType.ERROR || type == ReportType.FATAL || type == ReportType.WARNING) { + System.out.println (type.name () + ": " + message); + } + if (component == RainbowComponentT.GAUGE) { + System.out.println ("Gauge: " + message); + } + } + }); + reportingSubscriberPort.subscribe (EnumSet.allOf (RainbowComponentT.class), EnumSet.allOf (ReportType.class)); + + if (args[0].equals("startprobes")) { + master.startProbes (); + } else if (args[0].equals("killprobes")) { + master.killProbes(); + } else if (args[0].equals("terminate")) { + master.terminate (ExitState.DESTRUCT); + } else { + usage(); + } + System.exit (1); + } +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java index 6fc7aabcb..c6d4870e2 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/Swim.java @@ -1,114 +1,114 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim; - -import java.util.HashSet; -import java.util.Set; -import java.util.Stack; - -import org.acmestudio.acme.core.resource.RegionManager; -import org.acmestudio.acme.element.IAcmeElementInstance; -import org.acmestudio.acme.element.IAcmeElementType; -import org.acmestudio.acme.environment.error.AcmeError; -import org.acmestudio.acme.rule.AcmeSet; -import org.acmestudio.acme.rule.node.IExpressionNode; -import org.acmestudio.acme.type.verification.NodeScopeLookup; -import org.acmestudio.acme.type.verification.RuleTypeChecker; -import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; - -/** - * This class provides SWIM-specific operators that can be referred to in strategies and tactics. This class can be - * imported into Stitch and the static members called from there. - * - * @author Bradley Schmerl: schmerl - * @author gmoreno - */ -public class Swim { - // Acme expressions for evaluating the methods - private static final String FIND_SERVICES_EXPR = "/self/components:T[!isArchEnabled]"; - private static final String AVAILABLE_SERVICES_EXPR = "size (" + FIND_SERVICES_EXPR + ")"; - // Holder objects for caching parsed Acme expressions - private static IExpressionNode s_availableServicesExpr = null; - private static IExpressionNode s_findServicesExpression; - - /** - * Returns the number services of a particular type that are available. Availability here means that they are not - * yet marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type - * - * @param model - * The model to find availabile services in - * @param elemType - * The type of service to find - * @return the number of services that are available. - * @throws Exception - */ - public static int availableServices (SwimModelUpdateOperatorsImpl model, IAcmeElementType elemType) - throws Exception { - if (s_availableServicesExpr == null) { - s_availableServicesExpr = StandaloneLanguagePackHelper.defaultLanguageHelper () - .designRuleExpressionFromString ( - AVAILABLE_SERVICES_EXPR, new RegionManager ()); - } - - // Add "T" as a name in scope, referring to the type that we are looking for - NodeScopeLookup nameLookup = new NodeScopeLookup (); - nameLookup.put ("T", elemType); - return RuleTypeChecker.evaluateAsInt (model.getModelInstance (), null, s_availableServicesExpr, - new Stack (), - nameLookup); - } - - /** - * Returns the services of a particular type that are available. Availability here means that they are not yet - * marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type - * - * @param model - * The model to find availabile services in - * @param type - * The type of service to find - * @return the number of services that are available. - * @throws Exception - */ - public static Set> findServices (SwimModelUpdateOperatorsImpl model, - IAcmeElementType type) - throws Exception { - if (s_findServicesExpression == null) { - s_findServicesExpression = StandaloneLanguagePackHelper.defaultLanguageHelper () - .designRuleExpressionFromString (FIND_SERVICES_EXPR, new RegionManager ()); - } - NodeScopeLookup nameLookup = new NodeScopeLookup (); - nameLookup.put ("T", type); - AcmeSet set = RuleTypeChecker.evaluateAsSet (model.getModelInstance (), null, s_findServicesExpression, - new Stack (), - nameLookup); - - Set> retSet = new HashSet<> (); - for (Object o : set.getValues ()) { - if (o instanceof IAcmeElementInstance) { - retSet.add ((IAcmeElementInstance )o); - } - } - return retSet; - } -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim; + +import java.util.HashSet; +import java.util.Set; +import java.util.Stack; + +import org.acmestudio.acme.core.resource.RegionManager; +import org.acmestudio.acme.element.IAcmeElementInstance; +import org.acmestudio.acme.element.IAcmeElementType; +import org.acmestudio.acme.environment.error.AcmeError; +import org.acmestudio.acme.rule.AcmeSet; +import org.acmestudio.acme.rule.node.IExpressionNode; +import org.acmestudio.acme.type.verification.NodeScopeLookup; +import org.acmestudio.acme.type.verification.RuleTypeChecker; +import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; + +/** + * This class provides SWIM-specific operators that can be referred to in strategies and tactics. This class can be + * imported into Stitch and the static members called from there. + * + * @author Bradley Schmerl: schmerl + * @author gmoreno + */ +public class Swim { + // Acme expressions for evaluating the methods + private static final String FIND_SERVICES_EXPR = "/self/components:T[!isArchEnabled]"; + private static final String AVAILABLE_SERVICES_EXPR = "size (" + FIND_SERVICES_EXPR + ")"; + // Holder objects for caching parsed Acme expressions + private static IExpressionNode s_availableServicesExpr = null; + private static IExpressionNode s_findServicesExpression; + + /** + * Returns the number services of a particular type that are available. Availability here means that they are not + * yet marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type + * + * @param model + * The model to find availabile services in + * @param elemType + * The type of service to find + * @return the number of services that are available. + * @throws Exception + */ + public static int availableServices (SwimModelUpdateOperatorsImpl model, IAcmeElementType elemType) + throws Exception { + if (s_availableServicesExpr == null) { + s_availableServicesExpr = StandaloneLanguagePackHelper.defaultLanguageHelper () + .designRuleExpressionFromString ( + AVAILABLE_SERVICES_EXPR, new RegionManager ()); + } + + // Add "T" as a name in scope, referring to the type that we are looking for + NodeScopeLookup nameLookup = new NodeScopeLookup (); + nameLookup.put ("T", elemType); + return RuleTypeChecker.evaluateAsInt (model.getModelInstance (), null, s_availableServicesExpr, + new Stack (), + nameLookup); + } + + /** + * Returns the services of a particular type that are available. Availability here means that they are not yet + * marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type + * + * @param model + * The model to find availabile services in + * @param type + * The type of service to find + * @return the number of services that are available. + * @throws Exception + */ + public static Set> findServices (SwimModelUpdateOperatorsImpl model, + IAcmeElementType type) + throws Exception { + if (s_findServicesExpression == null) { + s_findServicesExpression = StandaloneLanguagePackHelper.defaultLanguageHelper () + .designRuleExpressionFromString (FIND_SERVICES_EXPR, new RegionManager ()); + } + NodeScopeLookup nameLookup = new NodeScopeLookup (); + nameLookup.put ("T", type); + AcmeSet set = RuleTypeChecker.evaluateAsSet (model.getModelInstance (), null, s_findServicesExpression, + new Stack (), + nameLookup); + + Set> retSet = new HashSet<> (); + for (Object o : set.getValues ()) { + if (o instanceof IAcmeElementInstance) { + retSet.add ((IAcmeElementInstance )o); + } + } + return retSet; + } +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java index 767fc4091..b97491151 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/ActivateServerCmd.java @@ -1,103 +1,103 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -/** - * A class representing the Acme command to activate a server in SWIM. - * This is represented using the property isActive - * - * @author Bradley Schmerl: schmerl - * @author gmoreno - * - */ -public class ActivateServerCmd extends SwimAcmeModelCommand { - - private static final String PROPERTY = "isActive"; - - - // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" - public ActivateServerCmd (AcmeModelInstance model, String target, String enable) { - super ("activateServer", model, target, enable); - } - - /** - * Constructs the list of commands for activating the server by setting the isActive property - * - * @return the list of commands - * @throws RainbowModelException - * when the server cannot be found, is of the incorrect type, or the argument is malformed. - */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - List> cmds = new LinkedList<> (); - IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", getTarget ())); - IAcmeProperty property = server.getProperty (PROPERTY); - if (property == null) { - throw new RainbowModelException(MessageFormat.format( - "The server ''{0}'' is not of the right type. It does not have a property ''" + PROPERTY + "''", - getTarget())); - } - try { - IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Boolean.valueOf (getParameters ()[0])); - if (propertyValueChanging (property, acmeVal)) { - m_command = property.getCommandFactory ().propertyValueSetCommand (property, - acmeVal); - cmds.add (m_command); - } - } - catch (IllegalArgumentException e) { - throw new RainbowModelException (e.getMessage (), e); - } - return cmds; - - } - - - /** - * - * @return the property after the command has been executed - * @throws IllegalStateException - */ - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * A class representing the Acme command to activate a server in SWIM. + * This is represented using the property isActive + * + * @author Bradley Schmerl: schmerl + * @author gmoreno + * + */ +public class ActivateServerCmd extends SwimAcmeModelCommand { + + private static final String PROPERTY = "isActive"; + + + // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" + public ActivateServerCmd (String c, AcmeModelInstance model, String target, String enable) { + super (c, model, target, enable); + } + + /** + * Constructs the list of commands for activating the server by setting the isActive property + * + * @return the list of commands + * @throws RainbowModelException + * when the server cannot be found, is of the incorrect type, or the argument is malformed. + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + IAcmeProperty property = server.getProperty (PROPERTY); + if (property == null) { + throw new RainbowModelException(MessageFormat.format( + "The server ''{0}'' is not of the right type. It does not have a property ''" + PROPERTY + "''", + getTarget())); + } + try { + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Boolean.valueOf (getParameters ()[0])); + if (propertyValueChanging (property, acmeVal)) { + m_command = property.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + } + catch (IllegalArgumentException e) { + throw new RainbowModelException (e.getMessage (), e); + } + return cmds; + + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java index d78b964e6..be60e5574 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/AddServerCmd.java @@ -1,120 +1,120 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -/** - * A class representing the Acme command to add a server to SWIM - * - * @author gmoreno - */ -public class AddServerCmd extends SwimAcmeModelCommand { - - private static final String PROPERTY = "expectedActivationTime"; - - private String m_server; - - - /** - * Target is the server add - * - * Note that since in SWIM we just add a server (not add a particular server) - * the target must be the server not currently enabled with the lowest index. - * - * This command does not mark the server as enabled. It only sets its expected - * activation time. Enablement happens through the gauge when is reported by the - * probe. - * - * The target is the load balancer, and the server is the server to be added - */ - public AddServerCmd (AcmeModelInstance model, String target, String server) { - super ("addServer", model, target, server); - m_server = server; - } - - /** - * Constructs the list of commands for setting the expectedActivationTime property - * - * @return the list of commands - * @throws RainbowModelException - * when the server cannot be found, is of the incorrect type, or the argument is malformed. - */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - List> cmds = new LinkedList<> (); - IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", m_server)); - IAcmeProperty property = server.getProperty (PROPERTY); - if (property == null) { - throw new RainbowModelException(MessageFormat.format( - "The server ''{0}'' is not of the right type. It does not have a property ''{1}''", - m_server, PROPERTY)); - } - - IAcmeProperty prop = getModelContext().getModelInstance().getProperty("ADD_SERVER_LATENCY_SEC"); - int addServerLatency = ((Integer) PropertyHelper.toJavaVal(prop.getValue())).intValue(); - int expectedActivationTime = (int)(System.currentTimeMillis() / 1000) + addServerLatency; - - try { - IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Integer.valueOf(expectedActivationTime)); - if (propertyValueChanging (property, acmeVal)) { - m_command = property.getCommandFactory ().propertyValueSetCommand (property, - acmeVal); - cmds.add (m_command); - } - } - catch (IllegalArgumentException e) { - throw new RainbowModelException (e.getMessage (), e); - } - - return cmds; - - } - - - /** - * - * @return the property after the command has been executed - * @throws IllegalStateException - */ - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * A class representing the Acme command to add a server to SWIM + * + * @author gmoreno + */ +public class AddServerCmd extends SwimAcmeModelCommand { + + private static final String PROPERTY = "expectedActivationTime"; + + private String m_server; + + + /** + * Target is the server add + * + * Note that since in SWIM we just add a server (not add a particular server) + * the target must be the server not currently enabled with the lowest index. + * + * This command does not mark the server as enabled. It only sets its expected + * activation time. Enablement happens through the gauge when is reported by the + * probe. + * + * The target is the load balancer, and the server is the server to be added + */ + public AddServerCmd (String c, AcmeModelInstance model, String target, String server) { + super (c, model, target, server); + m_server = server; + } + + /** + * Constructs the list of commands for setting the expectedActivationTime property + * + * @return the list of commands + * @throws RainbowModelException + * when the server cannot be found, is of the incorrect type, or the argument is malformed. + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", m_server)); + IAcmeProperty property = server.getProperty (PROPERTY); + if (property == null) { + throw new RainbowModelException(MessageFormat.format( + "The server ''{0}'' is not of the right type. It does not have a property ''{1}''", + m_server, PROPERTY)); + } + + IAcmeProperty prop = getModelContext().getModelInstance().getProperty("ADD_SERVER_LATENCY_SEC"); + int addServerLatency = ((Integer) PropertyHelper.toJavaVal(prop.getValue())).intValue(); + int expectedActivationTime = (int)(System.currentTimeMillis() / 1000) + addServerLatency; + + try { + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Integer.valueOf(expectedActivationTime)); + if (propertyValueChanging (property, acmeVal)) { + m_command = property.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + } + catch (IllegalArgumentException e) { + throw new RainbowModelException (e.getMessage (), e); + } + + return cmds; + + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java index d4c28a719..4f20ddad5 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/EnableServerCmd.java @@ -1,107 +1,107 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -/** - * A class representing the Acme command to enable a server in Znn. Currently, this is modeled by setting the property - * "isArchEnabled" on the model. - * - * @author Bradley Schmerl: schmerl - * - */ -public class EnableServerCmd extends SwimAcmeModelCommand { - - // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" - public EnableServerCmd (AcmeModelInstance model, String target, String enable) { - super ("enableServer", model, target, enable); - } - - /** - * Constructs the list of commands for enabling the server by setting the isArchEnabled property - * - * @return the list of commands - * @throws RainbowModelException - * when the server cannot be found, is of the incorrect type, or the argument is malformed. - */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - List> cmds = new LinkedList<> (); - IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", getTarget ())); - if (!server.declaresType ("ArchElementT")) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' is not of the right type. It does not have a property ''isArchEnabled''", - getTarget ())); - IAcmeProperty property = server.getProperty ("isArchEnabled"); - try { - boolean enabled = Boolean.valueOf (getParameters ()[0]); - IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (enabled); - if (propertyValueChanging (property, acmeVal)) { - m_command = property.getCommandFactory ().propertyValueSetCommand (property, - acmeVal); - cmds.add (m_command); - } - if (!enabled) { - - // set the load to 0, so that it does not affect the average - IAcmeProperty loadProperty = server.getProperty ("load"); - IAcmeCommand newCommand = loadProperty.getCommandFactory ().propertyValueSetCommand (loadProperty, - PropertyHelper.toAcmeVal(0.0)); - cmds.add(newCommand); - } - } - catch (IllegalArgumentException e) { - throw new RainbowModelException (e.getMessage (), e); - } - return cmds; - - } - - - /** - * - * @return the property after the command has been executed - * @throws IllegalStateException - */ - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * A class representing the Acme command to enable a server in Znn. Currently, this is modeled by setting the property + * "isArchEnabled" on the model. + * + * @author Bradley Schmerl: schmerl + * + */ +public class EnableServerCmd extends SwimAcmeModelCommand { + + // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" + public EnableServerCmd (String c, AcmeModelInstance model, String target, String enable) { + super (c, model, target, enable); + } + + /** + * Constructs the list of commands for enabling the server by setting the isArchEnabled property + * + * @return the list of commands + * @throws RainbowModelException + * when the server cannot be found, is of the incorrect type, or the argument is malformed. + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + if (!server.declaresType ("ArchElementT")) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''isArchEnabled''", + getTarget ())); + IAcmeProperty property = server.getProperty ("isArchEnabled"); + try { + boolean enabled = Boolean.valueOf (getParameters ()[0]); + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (enabled); + if (propertyValueChanging (property, acmeVal)) { + m_command = property.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + if (!enabled) { + + // set the load to 0, so that it does not affect the average + IAcmeProperty loadProperty = server.getProperty ("load"); + IAcmeCommand newCommand = loadProperty.getCommandFactory ().propertyValueSetCommand (loadProperty, + PropertyHelper.toAcmeVal(0.0)); + cmds.add(newCommand); + } + } + catch (IllegalArgumentException e) { + throw new RainbowModelException (e.getMessage (), e); + } + return cmds; + + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java index b2f549565..c934e4624 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/RemoveServerCmd.java @@ -1,79 +1,79 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import java.util.LinkedList; -import java.util.List; - -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -/** - * A class representing the Acme command to remove a server from SWIM - * - * @author gmoreno - */ -public class RemoveServerCmd extends SwimAcmeModelCommand { - - /** - * Target is the server add - * - * Note that since in SWIM we just remove a server (not a particular server) - * the target must be the server currently enabled with the highest index. - * - * This command does not mark the server as not enabled. That happens - * through the gauge when is reported by the probe. - * - * The target is the load balancer, and the server is the server to be removed - */ - public RemoveServerCmd (AcmeModelInstance model, String target, String server) { - super ("removeServer", model, target, server); - } - - /** - * Nothing is changed in the model, so the command is empty - * - * @return the list of commands - */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - List> cmds = new LinkedList<> (); - return cmds; - } - - - /** - * - * @return the property after the command has been executed - * @throws IllegalStateException - */ - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.LinkedList; +import java.util.List; + +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +/** + * A class representing the Acme command to remove a server from SWIM + * + * @author gmoreno + */ +public class RemoveServerCmd extends SwimAcmeModelCommand { + + /** + * Target is the server add + * + * Note that since in SWIM we just remove a server (not a particular server) + * the target must be the server currently enabled with the highest index. + * + * This command does not mark the server as not enabled. That happens + * through the gauge when is reported by the probe. + * + * The target is the load balancer, and the server is the server to be removed + */ + public RemoveServerCmd (String c, AcmeModelInstance model, String target, String server) { + super (c, model, target, server); + } + + /** + * Nothing is changed in the model, so the command is empty + * + * @return the list of commands + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + return cmds; + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java index 9911980f5..88bfe716c 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetArrivalRateCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetArrivalRateCmd extends SetDoubleCmd { - private final static String COMMAND = "setArrivalRate"; - private final static String PROPERTY = "arrivalRate"; - - public SetArrivalRateCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetArrivalRateCmd extends SetDoubleCmd { + private final static String PROPERTY = "arrivalRate"; + + public SetArrivalRateCmd(String c, AcmeModelInstance model, String component, String value) { + super(c, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicResponseTimeCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicResponseTimeCmd.java index 0a0bdddce..b56ce2f5d 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicResponseTimeCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicResponseTimeCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetBasicResponseTimeCmd extends SetDoubleCmd { - private final static String COMMAND = "setBasicResponseTime"; - private final static String PROPERTY = "basicResponseTime"; - - public SetBasicResponseTimeCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetBasicResponseTimeCmd extends SetDoubleCmd { + private final static String PROPERTY = "basicResponseTime"; + + public SetBasicResponseTimeCmd(String c, AcmeModelInstance model, String component, String value) { + super(c, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java index eb9947e06..6b1dceb9f 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetBasicThroughputCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetBasicThroughputCmd extends SetDoubleCmd { - private final static String COMMAND = "setBasicThroughput"; - private final static String PROPERTY = "basicThroughput"; - - public SetBasicThroughputCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetBasicThroughputCmd extends SetDoubleCmd { + private final static String PROPERTY = "basicThroughput"; + + public SetBasicThroughputCmd(String c, AcmeModelInstance model, String component, String value) { + super(c, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java index 9b7403224..8275db8ea 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDimmerCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetDimmerCmd extends SetDoubleCmd { - private final static String COMMAND = "setDimmer"; - private final static String PROPERTY = "dimmer"; - - public SetDimmerCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetDimmerCmd extends SetDoubleCmd { + private final static String PROPERTY = "dimmer"; + + public SetDimmerCmd(String c, AcmeModelInstance model, String component, String value) { + super(c, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java index 28ea340e5..cce8c3e5c 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetDoubleCmd.java @@ -1,98 +1,98 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -public abstract class SetDoubleCmd extends SwimAcmeModelCommand { - - protected String m_property; - - private String m_component; - private double m_value; - - public SetDoubleCmd (String command, String property, AcmeModelInstance model, String component, String value) { - super (command, model, component, value); - m_component = component; - m_value = Double.valueOf (value); - m_property = property; - } - - /** - * This method can be overriden by derived classes to process the value - * before it is set in the model. - * - * @param value - * @return processed value to be set in the model - */ - public double processValue(double value) { - return value; - } - - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent server = getModelContext ().resolveInModel (m_component, IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", getTarget ())); - IAcmeProperty property = server.getProperty (m_property); - if (property == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' is not of the right type. It does not have a property ''{1}''", - getTarget (), m_property)); - - try { - IAcmeFloatingPointValue acmeVal = PropertyHelper.toAcmeVal (m_value); - List> cmds = new LinkedList<> (); - if (propertyValueChanging (property, acmeVal)) { - m_command = server.getCommandFactory ().propertyValueSetCommand (property, acmeVal); - cmds.add (m_command); - } - return cmds; - } - catch (Exception e) { - throw new RainbowModelException (MessageFormat.format ("Error setting ACME model property ''{0}.{1}: {3}", - getTarget(), m_property, e.getMessage())); - } - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +public abstract class SetDoubleCmd extends SwimAcmeModelCommand { + + protected String m_property; + + private String m_component; + private double m_value; + + public SetDoubleCmd (String command, String property, AcmeModelInstance model, String component, String value) { + super (command, model, component, value); + m_component = component; + m_value = Double.valueOf (value); + m_property = property; + } + + /** + * This method can be overriden by derived classes to process the value + * before it is set in the model. + * + * @param value + * @return processed value to be set in the model + */ + public double processValue(double value) { + return value; + } + + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent server = getModelContext ().resolveInModel (m_component, IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + IAcmeProperty property = server.getProperty (m_property); + if (property == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''{1}''", + getTarget (), m_property)); + + try { + IAcmeFloatingPointValue acmeVal = PropertyHelper.toAcmeVal (m_value); + List> cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = server.getCommandFactory ().propertyValueSetCommand (property, acmeVal); + cmds.add (m_command); + } + return cmds; + } + catch (Exception e) { + throw new RainbowModelException (MessageFormat.format ("Error setting ACME model property ''{0}.{1}: {3}", + getTarget(), m_property, e.getMessage())); + } + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetLoadCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetLoadCmd.java index 6751cad0d..3993ceedd 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetLoadCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetLoadCmd.java @@ -27,11 +27,10 @@ public class SetLoadCmd extends SetDoubleCmd { - private final static String COMMAND = "setLoad"; private final static String PROPERTY = "load"; - public SetLoadCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); + public SetLoadCmd(String c, AcmeModelInstance model, String component, String value) { + super(c, PROPERTY, model, component, value); } public double processValue(double value) { diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java index 541ac8428..ba1eb6b3a 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptResponseTimeCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetOptResponseTimeCmd extends SetDoubleCmd { - private final static String COMMAND = "setOptResponseTime"; - private final static String PROPERTY = "optResponseTime"; - - public SetOptResponseTimeCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetOptResponseTimeCmd extends SetDoubleCmd { + private final static String PROPERTY = "optResponseTime"; + + public SetOptResponseTimeCmd(String c, AcmeModelInstance model, String component, String value) { + super(c, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java index 896dc6082..04437539e 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SetOptThroughputCmd.java @@ -1,36 +1,35 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class SetOptThroughputCmd extends SetDoubleCmd { - private final static String COMMAND = "setOptThroughput"; - private final static String PROPERTY = "optThroughput"; - - public SetOptThroughputCmd(AcmeModelInstance model, String component, String value) { - super(COMMAND, PROPERTY, model, component, value); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class SetOptThroughputCmd extends SetDoubleCmd { + private final static String PROPERTY = "optThroughput"; + + public SetOptThroughputCmd(String c, AcmeModelInstance model, String component, String value) { + super(c, PROPERTY, model, component, value); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java index 4f838958d..2e78bfc0e 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimAcmeModelCommand.java @@ -1,43 +1,43 @@ -/* - * The MIT License - * - * Copyright 2014 CMU Aimport org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.model.acme.AcmeModelInstance; -import org.sa.rainbow.model.acme.AcmeModelOperation; - "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.model.acme.AcmeModelOperation; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public abstract class SwimAcmeModelCommand extends AcmeModelOperation { - - public SwimAcmeModelCommand (String commandName, AcmeModelInstance model, String target, - String... parameters) { - super (commandName, model, target, parameters); - } - - - @Override - protected boolean checkModelValidForCommand (IAcmeSystem model) { - return model.declaresType ("SwimFam"); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU Aimport org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.AcmeModelOperation; + "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelOperation; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public abstract class SwimAcmeModelCommand extends AcmeModelOperation { + + public SwimAcmeModelCommand (String commandName, AcmeModelInstance model, String target, + String... parameters) { + super (commandName, model, target, parameters); + } + + + @Override + protected boolean checkModelValidForCommand (IAcmeSystem model) { + return model.declaresType ("SwimFam"); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimCommandFactory.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimCommandFactory.java index 72239b8b5..5c046c05a 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimCommandFactory.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimCommandFactory.java @@ -1,169 +1,177 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import java.io.InputStream; - -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.model.acme.AcmeModelCommandFactory; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import incubator.pval.Ensure; - -public class SwimCommandFactory extends AcmeModelCommandFactory { - - - public static SwimLoadModelCommand loadCommand (ModelsManager modelsManager, - String modelName, - InputStream stream, - String source) { - return new SwimLoadModelCommand (modelName, modelsManager, stream, source); - } - - public SwimCommandFactory (AcmeModelInstance modelInstance) { - super (modelInstance); - } - - @Override - protected void fillInCommandMap () { - super.fillInCommandMap (); - m_commandMap.put("SetDimmer".toLowerCase (), SetDimmerCmd.class); - m_commandMap.put("SetLoad".toLowerCase (), SetLoadCmd.class); - m_commandMap.put("SetArrivalRate".toLowerCase (), SetArrivalRateCmd.class); - m_commandMap.put("SetBasicResponseTime".toLowerCase (), SetBasicResponseTimeCmd.class); - m_commandMap.put("SetOptResponseTime".toLowerCase (), SetOptResponseTimeCmd.class); - m_commandMap.put("SetBasicThroughput".toLowerCase (), SetBasicThroughputCmd.class); - m_commandMap.put("SetOptThroughput".toLowerCase (), SetOptThroughputCmd.class); - m_commandMap.put("SetOptThroughput".toLowerCase (), SetOptThroughputCmd.class); - m_commandMap.put("EnableServer".toLowerCase (), EnableServerCmd.class); - m_commandMap.put("ActivateServer".toLowerCase (), ActivateServerCmd.class); - m_commandMap.put("AddServer".toLowerCase (), AddServerCmd.class); - m_commandMap.put("RemoveServer".toLowerCase (), RemoveServerCmd.class); - } - - - public SetDimmerCmd setDimmerCmd (IAcmeComponent loadBalancer, double dimmer) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetDimmerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (dimmer)); - } - - public SetLoadCmd setLoadCmd (IAcmeComponent server, double value) { - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetLoadCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - Double.toString (value)); - } - - public SetArrivalRateCmd setArrivalRateCmd (IAcmeComponent loadBalancer, double value) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetArrivalRateCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (value)); - } - - public SetBasicResponseTimeCmd setBasicResponseTimeCmd (IAcmeComponent loadBalancer, double value) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetBasicResponseTimeCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (value)); - } - - public SetOptResponseTimeCmd setOptResponseTimeCmd (IAcmeComponent loadBalancer, double value) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetOptResponseTimeCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (value)); - } - - public SetBasicThroughputCmd setBasicThroughputCmd (IAcmeComponent loadBalancer, double value) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetBasicThroughputCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (value)); - } - - public SetOptThroughputCmd setOptThroughputCmd (IAcmeComponent loadBalancer, double value) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetOptThroughputCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - Double.toString (value)); - } - - public EnableServerCmd enableServerCmd (IAcmeComponent server, boolean enabled) { - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new EnableServerCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - Boolean.toString (enabled)); - } - - public ActivateServerCmd activateServerCmd (IAcmeComponent server, boolean enabled) { - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new ActivateServerCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - Boolean.toString (enabled)); - } - - public AddServerCmd addServerCmd (IAcmeComponent loadBalancer, IAcmeComponent server) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new AddServerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - server.getQualifiedName()); - } - - public RemoveServerCmd removeServerCmd (IAcmeComponent loadBalancer, IAcmeComponent server) { - Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new RemoveServerCmd ((AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), - server.getQualifiedName()); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import java.io.InputStream; + +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.model.acme.AcmeModelCommandFactory; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import incubator.pval.Ensure; + +public class SwimCommandFactory extends AcmeModelCommandFactory { + + + private static final String REMOVE_SERVER_CMD = "RemoveServer"; + private static final String ADD_SERVER_CMD = "AddServer"; + private static final String ACTIVATE_SERVER_CMD = "ActivateServer"; + private static final String ENABLE_SERVER_CMD = "EnableServer"; + private static final String SET_OPT_THROUGHPUT_CMD = "SetOptThroughput"; + private static final String SET_BASIC_THROUGHPUT_CMD = "SetBasicThroughput"; + private static final String SET_OPT_RESPONSE_TIME_CMD = "SetOptResponseTime"; + private static final String SET_BASIC_RESPONSE_TIME_CMD = "SetBasicResponseTime"; + private static final String SET_ARRIVAL_RATE_CMD = "SetArrivalRate"; + private static final String SET_LOAD_CMD = "SetLoad"; + private static final String SET_DIMMER_CMD = "SetDimmer"; + + @LoadOperation + public static SwimLoadModelCommand loadCommand (ModelsManager modelsManager, + String modelName, + InputStream stream, + String source) { + return new SwimLoadModelCommand (modelName, modelsManager, stream, source); + } + + public SwimCommandFactory (AcmeModelInstance modelInstance) throws RainbowException { + super (modelInstance); + } + + @Operation(name=SET_DIMMER_CMD) + public SetDimmerCmd setDimmerCmd (IAcmeComponent loadBalancer, double dimmer) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetDimmerCmd (SET_DIMMER_CMD, + (AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (dimmer)); + } + + @Operation(name=SET_LOAD_CMD) + public SetLoadCmd setLoadCmd (IAcmeComponent server, double value) { + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetLoadCmd (SET_LOAD_CMD, (AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + Double.toString (value)); + } + + @Operation(name=SET_ARRIVAL_RATE_CMD) + public SetArrivalRateCmd setArrivalRateCmd (IAcmeComponent loadBalancer, double value) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetArrivalRateCmd (SET_ARRIVAL_RATE_CMD, (AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (value)); + } + + @Operation(name=SET_BASIC_RESPONSE_TIME_CMD) + public SetBasicResponseTimeCmd setBasicResponseTimeCmd (IAcmeComponent loadBalancer, double value) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetBasicResponseTimeCmd (SET_BASIC_RESPONSE_TIME_CMD, (AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (value)); + } + + @Operation(name=SET_OPT_RESPONSE_TIME_CMD) + public SetOptResponseTimeCmd setOptResponseTimeCmd (IAcmeComponent loadBalancer, double value) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetOptResponseTimeCmd (SET_OPT_RESPONSE_TIME_CMD, (AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (value)); + } + + @Operation(name=SET_BASIC_THROUGHPUT_CMD) + public SetBasicThroughputCmd setBasicThroughputCmd (IAcmeComponent loadBalancer, double value) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetBasicThroughputCmd (SET_BASIC_THROUGHPUT_CMD, (AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (value)); + } + + @Operation(name=SET_OPT_THROUGHPUT_CMD) + public SetOptThroughputCmd setOptThroughputCmd (IAcmeComponent loadBalancer, double value) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetOptThroughputCmd (SET_OPT_THROUGHPUT_CMD, (AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + Double.toString (value)); + } + + @Operation(name=ENABLE_SERVER_CMD) + public EnableServerCmd enableServerCmd (IAcmeComponent server, boolean enabled) { + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new EnableServerCmd (ENABLE_SERVER_CMD, (AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + Boolean.toString (enabled)); + } + + @Operation(name=ACTIVATE_SERVER_CMD) + public ActivateServerCmd activateServerCmd (IAcmeComponent server, boolean enabled) { + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new ActivateServerCmd (ACTIVATE_SERVER_CMD, (AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + Boolean.toString (enabled)); + } + + @Operation(name=ADD_SERVER_CMD) + public AddServerCmd addServerCmd (IAcmeComponent loadBalancer, IAcmeComponent server) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new AddServerCmd (ADD_SERVER_CMD, (AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + server.getQualifiedName()); + } + + @Operation(name=REMOVE_SERVER_CMD) + public RemoveServerCmd removeServerCmd (IAcmeComponent loadBalancer, IAcmeComponent server) { + Ensure.is_true (loadBalancer.declaresType ("LoadBalancerT")); + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (loadBalancer) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new RemoveServerCmd (REMOVE_SERVER_CMD, (AcmeModelInstance) m_modelInstance, loadBalancer.getQualifiedName (), + server.getQualifiedName()); + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java index b4d118920..b9634435a 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimConstants.java @@ -1,19 +1,19 @@ -package org.sa.rainbow.model.acme.swim.commands; - -import java.util.Collections; -import java.util.List; - -/** - * Created by schmerl on 2/4/2016. - */ -public class SwimConstants { - public static final String SERVER_T_NAME = "ServerT"; - public static final String PROXY_CONN_T_NAME = "ProxyConnT"; - public static final String PROXY_FORWARD_PORT_T_NAME = "ProxyForwardPortT"; - public static final String HTTP_PORT_T_NAME = "HttpPortT"; - - static final List SERVER_TYPE = Collections.singletonList (SERVER_T_NAME); - static final List HTTP_CONN_T = Collections.singletonList (PROXY_CONN_T_NAME); - static final List PROXY_FORWARD_PORT = Collections.singletonList (PROXY_FORWARD_PORT_T_NAME); - static final List HTTP_PORT = Collections.singletonList (HTTP_PORT_T_NAME); -} +package org.sa.rainbow.model.acme.swim.commands; + +import java.util.Collections; +import java.util.List; + +/** + * Created by schmerl on 2/4/2016. + */ +public class SwimConstants { + public static final String SERVER_T_NAME = "ServerT"; + public static final String PROXY_CONN_T_NAME = "ProxyConnT"; + public static final String PROXY_FORWARD_PORT_T_NAME = "ProxyForwardPortT"; + public static final String HTTP_PORT_T_NAME = "HttpPortT"; + + static final List SERVER_TYPE = Collections.singletonList (SERVER_T_NAME); + static final List HTTP_CONN_T = Collections.singletonList (PROXY_CONN_T_NAME); + static final List PROXY_FORWARD_PORT = Collections.singletonList (PROXY_FORWARD_PORT_T_NAME); + static final List HTTP_PORT = Collections.singletonList (HTTP_PORT_T_NAME); +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimLoadModelCommand.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimLoadModelCommand.java index 72e8707cf..e022f9735 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimLoadModelCommand.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/model/acme/swim/commands/SwimLoadModelCommand.java @@ -1,146 +1,146 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.swim.commands; - -import org.acmestudio.acme.core.exception.AcmeException; -import org.acmestudio.acme.core.exception.AcmeVisitorException; -import org.acmestudio.acme.core.resource.IAcmeResource; -import org.acmestudio.acme.core.resource.ParsingFailureException; -import org.acmestudio.acme.core.type.IAcmeStringValue; -import org.acmestudio.acme.element.AbstractAcmeElementVisitor; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.acmestudio.acme.model.util.core.UMStringValue; -import org.acmestudio.standalone.resource.StandaloneResourceProvider; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; -import org.sa.rainbow.model.acme.swim.SwimModelUpdateOperatorsImpl; -import org.sa.rainbow.util.Util; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.LinkedList; -import java.util.List; - -public class SwimLoadModelCommand extends AbstractLoadModelCmd { - - public class AcmePropertySubstitutionVisitor extends AbstractAcmeElementVisitor { - - protected List> m_commands = new LinkedList<> (); - - public IAcmeCommand getCommand () { - if (m_commands.isEmpty ()) return null; - if (m_commands.size () == 1) return m_commands.get (0); - return m_commands.get (0).getCommandFactory ().compoundCommand (m_commands); - } - - @Override - public Object visitIAcmeProperty (IAcmeProperty property, Object data) throws AcmeVisitorException { - if (property.getValue () instanceof IAcmeStringValue) { - IAcmeStringValue val = (IAcmeStringValue )property.getValue (); - String origVal = val.getValue (); - String newVal = Util.evalTokens (origVal); - if (!newVal.equals (origVal)) { - IAcmePropertyCommand cmd = property.getCommandFactory ().propertyValueSetCommand (property, - new UMStringValue (newVal)); - m_commands.add (cmd); - } - } - return data; - } - } - - private String m_systemName; - private SwimModelUpdateOperatorsImpl m_result; - - public SwimLoadModelCommand (String systemName, IModelsManager mm, InputStream is, String source) { - super ("loadSwimModel", mm, systemName, is, source); - m_systemName = systemName; - } - - @Override - public ModelReference getModelReference () { - return new ModelReference (m_systemName, "Acme"); - } - - - @Override - protected void subExecute () throws RainbowException { - try { - IAcmeResource resource = StandaloneResourceProvider.instance () - .acmeResourceForObject ( - new File (getOriginalSource ())); - m_result = new SwimModelUpdateOperatorsImpl (resource.getModel ().getSystem (m_systemName), - getOriginalSource ()); - - // Do property substitution - try { - AcmePropertySubstitutionVisitor visitor = new AcmePropertySubstitutionVisitor (); - m_result.getModelInstance ().visit (visitor, null); - IAcmeCommand cmd = visitor.getCommand (); - cmd.execute (); - } - catch (IllegalStateException | AcmeException e) { - e.printStackTrace (); - } - - doPostExecute (); - } - catch (ParsingFailureException | IOException e) { - throw new RainbowException (e); - } - } - - @Override - protected void subRedo () throws RainbowException { - doPostExecute (); - } - - @Override - protected void subUndo () throws RainbowException { - doPostUndo (); - } - - @Override - public IModelInstance getResult () { - return m_result; - } - - @Override - public String getName () { - return "LoadSwimModel"; - } - - @Override - protected boolean checkModelValidForCommand (Object model) { - return true; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.swim.commands; + +import org.acmestudio.acme.core.exception.AcmeException; +import org.acmestudio.acme.core.exception.AcmeVisitorException; +import org.acmestudio.acme.core.resource.IAcmeResource; +import org.acmestudio.acme.core.resource.ParsingFailureException; +import org.acmestudio.acme.core.type.IAcmeStringValue; +import org.acmestudio.acme.element.AbstractAcmeElementVisitor; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.acmestudio.acme.model.util.core.UMStringValue; +import org.acmestudio.standalone.resource.StandaloneResourceProvider; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; +import org.sa.rainbow.model.acme.swim.SwimModelUpdateOperatorsImpl; +import org.sa.rainbow.util.Util; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedList; +import java.util.List; + +public class SwimLoadModelCommand extends AbstractLoadModelCmd { + + public class AcmePropertySubstitutionVisitor extends AbstractAcmeElementVisitor { + + protected List> m_commands = new LinkedList<> (); + + public IAcmeCommand getCommand () { + if (m_commands.isEmpty ()) return null; + if (m_commands.size () == 1) return m_commands.get (0); + return m_commands.get (0).getCommandFactory ().compoundCommand (m_commands); + } + + @Override + public Object visitIAcmeProperty (IAcmeProperty property, Object data) throws AcmeVisitorException { + if (property.getValue () instanceof IAcmeStringValue) { + IAcmeStringValue val = (IAcmeStringValue )property.getValue (); + String origVal = val.getValue (); + String newVal = Util.evalTokens (origVal); + if (!newVal.equals (origVal)) { + IAcmePropertyCommand cmd = property.getCommandFactory ().propertyValueSetCommand (property, + new UMStringValue (newVal)); + m_commands.add (cmd); + } + } + return data; + } + } + + private String m_systemName; + private SwimModelUpdateOperatorsImpl m_result; + + public SwimLoadModelCommand (String systemName, IModelsManager mm, InputStream is, String source) { + super ("loadSwimModel", mm, systemName, is, source); + m_systemName = systemName; + } + + @Override + public ModelReference getModelReference () { + return new ModelReference (m_systemName, "Acme"); + } + + + @Override + protected void subExecute () throws RainbowException { + try { + IAcmeResource resource = StandaloneResourceProvider.instance () + .acmeResourceForObject ( + new File (getOriginalSource ())); + m_result = new SwimModelUpdateOperatorsImpl (resource.getModel ().getSystem (m_systemName), + getOriginalSource ()); + + // Do property substitution + try { + AcmePropertySubstitutionVisitor visitor = new AcmePropertySubstitutionVisitor (); + m_result.getModelInstance ().visit (visitor, null); + IAcmeCommand cmd = visitor.getCommand (); + cmd.execute (); + } + catch (IllegalStateException | AcmeException e) { + e.printStackTrace (); + } + + doPostExecute (); + } + catch (ParsingFailureException | IOException e) { + throw new RainbowException (e); + } + } + + @Override + protected void subRedo () throws RainbowException { + doPostExecute (); + } + + @Override + protected void subUndo () throws RainbowException { + doPostUndo (); + } + + @Override + public IModelInstance getResult () { + return m_result; + } + + @Override + public String getName () { + return "LoadSwimModel"; + } + + @Override + protected boolean checkModelValidForCommand (Object model) { + return true; + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/ObserveCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/ObserveCmd.java index 80a67496b..e24a8bed2 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/ObserveCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/ObserveCmd.java @@ -1,49 +1,49 @@ -package org.sa.rainbow.timeseriespredictor.model; - -import java.util.List; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public class ObserveCmd extends AbstractRainbowModelOperation { - - private Double m_value; - - public ObserveCmd (TimeSeriesPredictorModelInstance model, String bogusTarget, String value) { - super ("observe", model, bogusTarget, value); - m_value = Double.valueOf (value); - } - - @Override - public Object getResult () throws IllegalStateException { - return null; - } - - @Override - protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "TimeSeriesPredictorModelOperation"); - } - - @Override - protected void subExecute () throws RainbowException { - m_modelContext.getModelInstance ().observe (m_value); - } - - @Override - protected void subRedo () throws RainbowException { - m_modelContext.getModelInstance ().observe (m_value); - } - - @Override - protected void subUndo () throws RainbowException { - throw new RainbowException("Undo not supported for " + super.getName()); - } - - @Override - protected boolean checkModelValidForCommand (TimeSeriesPredictorModel model) { - return true; - } - -} +package org.sa.rainbow.timeseriespredictor.model; + +import java.util.List; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class ObserveCmd extends AbstractRainbowModelOperation { + + private Double m_value; + + public ObserveCmd (TimeSeriesPredictorModelInstance model, String bogusTarget, String value) { + super ("observe", model, bogusTarget, value); + m_value = Double.valueOf (value); + } + + @Override + public Object getResult () throws IllegalStateException { + return null; + } + + @Override + protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { + return generateEvents (messageFactory, "TimeSeriesPredictorModelOperation"); + } + + @Override + protected void subExecute () throws RainbowException { + m_modelContext.getModelInstance ().observe (m_value); + } + + @Override + protected void subRedo () throws RainbowException { + m_modelContext.getModelInstance ().observe (m_value); + } + + @Override + protected void subUndo () throws RainbowException { + throw new RainbowException("Undo not supported for " + super.getName()); + } + + @Override + protected boolean checkModelValidForCommand (TimeSeriesPredictorModel model) { + return true; + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/SetHorizonCmd.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/SetHorizonCmd.java index a5abe13d2..aaa7184b5 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/SetHorizonCmd.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/SetHorizonCmd.java @@ -1,49 +1,49 @@ -package org.sa.rainbow.timeseriespredictor.model; - -import java.util.List; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; - -public class SetHorizonCmd extends AbstractRainbowModelOperation { - - private Integer m_value; - - public SetHorizonCmd (TimeSeriesPredictorModelInstance model, String bogusTarget, String value) { - super ("setHorizon", model, bogusTarget, value); - m_value = Integer.valueOf (value); - } - - @Override - public Object getResult () throws IllegalStateException { - return null; - } - - @Override - protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { - return generateEvents (messageFactory, "TimeSeriesPredictorModelOperation"); - } - - @Override - protected void subExecute () throws RainbowException { - m_modelContext.getModelInstance ().setHorizon (m_value); - } - - @Override - protected void subRedo () throws RainbowException { - m_modelContext.getModelInstance ().setHorizon (m_value); - } - - @Override - protected void subUndo () throws RainbowException { - throw new RainbowException("Undo not supported for " + super.getName()); - } - - @Override - protected boolean checkModelValidForCommand (TimeSeriesPredictorModel model) { - return true; - } - -} +package org.sa.rainbow.timeseriespredictor.model; + +import java.util.List; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; + +public class SetHorizonCmd extends AbstractRainbowModelOperation { + + private Integer m_value; + + public SetHorizonCmd (TimeSeriesPredictorModelInstance model, String bogusTarget, String value) { + super ("setHorizon", model, bogusTarget, value); + m_value = Integer.valueOf (value); + } + + @Override + public Object getResult () throws IllegalStateException { + return null; + } + + @Override + protected List getGeneratedEvents (IRainbowMessageFactory messageFactory) { + return generateEvents (messageFactory, "TimeSeriesPredictorModelOperation"); + } + + @Override + protected void subExecute () throws RainbowException { + m_modelContext.getModelInstance ().setHorizon (m_value); + } + + @Override + protected void subRedo () throws RainbowException { + m_modelContext.getModelInstance ().setHorizon (m_value); + } + + @Override + protected void subUndo () throws RainbowException { + throw new RainbowException("Undo not supported for " + super.getName()); + } + + @Override + protected boolean checkModelValidForCommand (TimeSeriesPredictorModel model) { + return true; + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModel.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModel.java index 29fd0a005..63a583930 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModel.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModel.java @@ -1,110 +1,110 @@ -package org.sa.rainbow.timeseriespredictor.model; -import java.util.Vector; - -import org.sa.rainbow.core.error.RainbowException; - -import pladapt.EnvironmentDTMCPartitioned; -import pladapt.TimeSeriesPredictor; - -public class TimeSeriesPredictorModel implements Cloneable { - - private enum ObservationFeeder { AVERAGE, LAST }; - private ObservationFeeder ObservationFeederMode = ObservationFeeder.LAST; - - TimeSeriesPredictor m_predictor; - String m_modelArgs; - long m_trainingLength; - int m_horizon = -1; - - /** - * Since it is hard to synchronize observations from gauges with - * the evaluation period, the observations are stored here - * until it is time to generate the environment DTMC. At that point, - * the average of the observations is fed as a single observation - * to the predictor. That way, we get one observation per evaluation - * period. - */ - Vector m_observations = new Vector(); - - /** - * load PLADAPT wrapper - */ - static { - System.loadLibrary("pladapt_wrap"); - } - - public TimeSeriesPredictorModel (String modelArgs, long trainingLength) { - m_modelArgs = modelArgs; - m_trainingLength = trainingLength; - } - - public void observe(double value) { - m_observations.add(Double.valueOf(value)); - } - - protected void feedObservations() { - if (!m_observations.isEmpty()) { - double observation = 0; - if (ObservationFeederMode == ObservationFeeder.AVERAGE) { - double sum = 0; - for (Double o : m_observations) { - sum += o.doubleValue(); - } - - observation = sum / m_observations.size(); - } else { - observation = m_observations.lastElement(); - } - - if (m_predictor == null) { - m_predictor = TimeSeriesPredictor.getInstance(m_modelArgs, m_trainingLength, m_horizon); - } - - m_predictor.observe(observation); - m_observations.clear(); - } - } - - public void setHorizon(int value) throws RainbowException { - if (m_predictor != null) { - throw new RainbowException("TimeSeriesPredictorModel: attempt to set horizon after first observation"); - } - m_horizon = value; - } - - /** - * Generates environment DTMC - * - * @param branchingDepth - * @param depth - * @return null if no observation has been made - */ - public EnvironmentDTMCPartitioned generateEnvironmentDTMC(int branchingDepth, int depth) { - EnvironmentDTMCPartitioned envDTMC = null; - feedObservations(); - if (m_predictor != null) { - envDTMC = m_predictor.generateEnvironmentDTMC(branchingDepth, depth); - } - return envDTMC; - } - - /** - * Returns a one step ahead prediction - * - * @return prediction, or null if no prediction can be made (no observations yet) - */ - public Double getSimplePrediction() { - feedObservations(); - if (m_predictor == null) { - return null; // no observations yet - } - double[] predictions = new double[1]; - m_predictor.predict(0, Double.MAX_VALUE, 1, predictions); - return Double.valueOf(predictions[0]); - } - - @Override - public Object clone () throws CloneNotSupportedException { - throw new CloneNotSupportedException("TimeSeriesPredictorModel"); - } -} +package org.sa.rainbow.timeseriespredictor.model; +import java.util.Vector; + +import org.sa.rainbow.core.error.RainbowException; + +import pladapt.EnvironmentDTMCPartitioned; +import pladapt.TimeSeriesPredictor; + +public class TimeSeriesPredictorModel implements Cloneable { + + private enum ObservationFeeder { AVERAGE, LAST }; + private ObservationFeeder ObservationFeederMode = ObservationFeeder.LAST; + + TimeSeriesPredictor m_predictor; + String m_modelArgs; + long m_trainingLength; + int m_horizon = -1; + + /** + * Since it is hard to synchronize observations from gauges with + * the evaluation period, the observations are stored here + * until it is time to generate the environment DTMC. At that point, + * the average of the observations is fed as a single observation + * to the predictor. That way, we get one observation per evaluation + * period. + */ + Vector m_observations = new Vector(); + + /** + * load PLADAPT wrapper + */ + static { + System.loadLibrary("pladapt_wrap"); + } + + public TimeSeriesPredictorModel (String modelArgs, long trainingLength) { + m_modelArgs = modelArgs; + m_trainingLength = trainingLength; + } + + public void observe(double value) { + m_observations.add(Double.valueOf(value)); + } + + protected void feedObservations() { + if (!m_observations.isEmpty()) { + double observation = 0; + if (ObservationFeederMode == ObservationFeeder.AVERAGE) { + double sum = 0; + for (Double o : m_observations) { + sum += o.doubleValue(); + } + + observation = sum / m_observations.size(); + } else { + observation = m_observations.lastElement(); + } + + if (m_predictor == null) { + m_predictor = TimeSeriesPredictor.getInstance(m_modelArgs, m_trainingLength, m_horizon); + } + + m_predictor.observe(observation); + m_observations.clear(); + } + } + + public void setHorizon(int value) throws RainbowException { + if (m_predictor != null) { + throw new RainbowException("TimeSeriesPredictorModel: attempt to set horizon after first observation"); + } + m_horizon = value; + } + + /** + * Generates environment DTMC + * + * @param branchingDepth + * @param depth + * @return null if no observation has been made + */ + public EnvironmentDTMCPartitioned generateEnvironmentDTMC(int branchingDepth, int depth) { + EnvironmentDTMCPartitioned envDTMC = null; + feedObservations(); + if (m_predictor != null) { + envDTMC = m_predictor.generateEnvironmentDTMC(branchingDepth, depth); + } + return envDTMC; + } + + /** + * Returns a one step ahead prediction + * + * @return prediction, or null if no prediction can be made (no observations yet) + */ + public Double getSimplePrediction() { + feedObservations(); + if (m_predictor == null) { + return null; // no observations yet + } + double[] predictions = new double[1]; + m_predictor.predict(0, Double.MAX_VALUE, 1, predictions); + return Double.valueOf(predictions[0]); + } + + @Override + public Object clone () throws CloneNotSupportedException { + throw new CloneNotSupportedException("TimeSeriesPredictorModel"); + } +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelCommandFactory.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelCommandFactory.java index ded00e33d..e4b40b6a7 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelCommandFactory.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelCommandFactory.java @@ -1,45 +1,45 @@ -package org.sa.rainbow.timeseriespredictor.model; - -import java.io.InputStream; - -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class TimeSeriesPredictorModelCommandFactory extends ModelCommandFactory { - - public static TimeSeriesPredictorModelLoadModelCommand loadCommand (ModelsManager mm, - String modelName, - InputStream stream, - String source) { - return new TimeSeriesPredictorModelLoadModelCommand (mm, modelName, stream, source); - } - - public TimeSeriesPredictorModelCommandFactory (TimeSeriesPredictorModelInstance model) { - super (model.getClass (), model); - - } - - @Override - protected void fillInCommandMap () { - m_commandMap.put("Observe".toLowerCase (), ObserveCmd.class); - m_commandMap.put("SetHorizon".toLowerCase (), SetHorizonCmd.class); - } - - @Override - public AbstractSaveModelCmd saveCommand (String location) throws RainbowModelException { - // TODO Auto-generated method stub - return null; - } - - public ObserveCmd observeCmd (double value) { - return new ObserveCmd ((TimeSeriesPredictorModelInstance) m_modelInstance, "", Double.toString (value)); - } - - public SetHorizonCmd setHorizonCmd (int value) { - return new SetHorizonCmd ((TimeSeriesPredictorModelInstance) m_modelInstance, "", Integer.toString (value)); - } - - -} +package org.sa.rainbow.timeseriespredictor.model; + +import java.io.InputStream; + +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class TimeSeriesPredictorModelCommandFactory extends ModelCommandFactory { + + public static TimeSeriesPredictorModelLoadModelCommand loadCommand (ModelsManager mm, + String modelName, + InputStream stream, + String source) { + return new TimeSeriesPredictorModelLoadModelCommand (mm, modelName, stream, source); + } + + public TimeSeriesPredictorModelCommandFactory (TimeSeriesPredictorModelInstance model) { + super (model.getClass (), model); + + } + + @Override + protected void fillInCommandMap () { + m_commandMap.put("Observe".toLowerCase (), ObserveCmd.class); + m_commandMap.put("SetHorizon".toLowerCase (), SetHorizonCmd.class); + } + + @Override + public AbstractSaveModelCmd saveCommand (String location) throws RainbowModelException { + // TODO Auto-generated method stub + return null; + } + + public ObserveCmd observeCmd (double value) { + return new ObserveCmd ((TimeSeriesPredictorModelInstance) m_modelInstance, "", Double.toString (value)); + } + + public SetHorizonCmd setHorizonCmd (int value) { + return new SetHorizonCmd ((TimeSeriesPredictorModelInstance) m_modelInstance, "", Integer.toString (value)); + } + + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelInstance.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelInstance.java index fb3c11eec..aeee9b938 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelInstance.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelInstance.java @@ -1,78 +1,78 @@ -package org.sa.rainbow.timeseriespredictor.model; - -import org.sa.rainbow.core.error.RainbowCopyException; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.commands.ModelCommandFactory; - -public class TimeSeriesPredictorModelInstance implements IModelInstance { - - public static final String MODEL_TYPE = "TSP"; - private TimeSeriesPredictorModel m_model; - private String m_attachedToModel; - private String m_source; - private TimeSeriesPredictorModelCommandFactory m_commandFactory; - - public TimeSeriesPredictorModelInstance (TimeSeriesPredictorModel pModel, String attachedToModel, String source) { - setModelInstance (pModel); - setOriginalSource (source); - m_attachedToModel = attachedToModel; - } - - @Override - public TimeSeriesPredictorModel getModelInstance () { - return m_model; - } - - @Override - public void setModelInstance (TimeSeriesPredictorModel model) { - m_model = model; - } - - @Override - public IModelInstance copyModelInstance (String newName) throws RainbowCopyException { - try { - return new TimeSeriesPredictorModelInstance ((TimeSeriesPredictorModel )m_model.clone (), m_attachedToModel, - getOriginalSource ()); - } - catch (CloneNotSupportedException e) { - return null; - } - } - - @Override - public String getModelType () { - return MODEL_TYPE; - } - - @Override - public String getModelName () { - return m_attachedToModel; - } - - @Override - public ModelCommandFactory getCommandFactory () { - if (m_commandFactory == null) { - m_commandFactory = new TimeSeriesPredictorModelCommandFactory (this); - } - return m_commandFactory; - } - - @Override - public void setOriginalSource (String source) { - m_source = source; - } - - @Override - public String getOriginalSource () { - return m_source; - } - - @Override - public void dispose () throws RainbowException { - m_source = null; - m_model = null; - m_attachedToModel = null; - } - -} +package org.sa.rainbow.timeseriespredictor.model; + +import org.sa.rainbow.core.error.RainbowCopyException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.commands.ModelCommandFactory; + +public class TimeSeriesPredictorModelInstance implements IModelInstance { + + public static final String MODEL_TYPE = "TSP"; + private TimeSeriesPredictorModel m_model; + private String m_attachedToModel; + private String m_source; + private TimeSeriesPredictorModelCommandFactory m_commandFactory; + + public TimeSeriesPredictorModelInstance (TimeSeriesPredictorModel pModel, String attachedToModel, String source) { + setModelInstance (pModel); + setOriginalSource (source); + m_attachedToModel = attachedToModel; + } + + @Override + public TimeSeriesPredictorModel getModelInstance () { + return m_model; + } + + @Override + public void setModelInstance (TimeSeriesPredictorModel model) { + m_model = model; + } + + @Override + public IModelInstance copyModelInstance (String newName) throws RainbowCopyException { + try { + return new TimeSeriesPredictorModelInstance ((TimeSeriesPredictorModel )m_model.clone (), m_attachedToModel, + getOriginalSource ()); + } + catch (CloneNotSupportedException e) { + return null; + } + } + + @Override + public String getModelType () { + return MODEL_TYPE; + } + + @Override + public String getModelName () { + return m_attachedToModel; + } + + @Override + public ModelCommandFactory getCommandFactory () { + if (m_commandFactory == null) { + m_commandFactory = new TimeSeriesPredictorModelCommandFactory (this); + } + return m_commandFactory; + } + + @Override + public void setOriginalSource (String source) { + m_source = source; + } + + @Override + public String getOriginalSource () { + return m_source; + } + + @Override + public void dispose () throws RainbowException { + m_source = null; + m_model = null; + m_attachedToModel = null; + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelLoadModelCommand.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelLoadModelCommand.java index d072dc08f..32cff22b5 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelLoadModelCommand.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/timeseriespredictor/model/TimeSeriesPredictorModelLoadModelCommand.java @@ -1,59 +1,59 @@ -package org.sa.rainbow.timeseriespredictor.model; - -import java.io.InputStream; - -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; - -public class TimeSeriesPredictorModelLoadModelCommand extends AbstractLoadModelCmd { - - private static final String PROP_ARGS = "customize.model.timeseriespredictor.args"; - public static final String PROP_TRAININGLENGTH = "customize.model.timeseriespredictor.traininglength"; - private String m_name; - private TimeSeriesPredictorModelInstance m_result; - - public TimeSeriesPredictorModelLoadModelCommand (IModelsManager mm, String modelName, InputStream is, String source) { - super ("loadTimeSeriesPredictorModel", mm, modelName, is, source); - m_name = modelName; - } - - @Override - public IModelInstance getResult () throws IllegalStateException { - return m_result; - } - - @Override - public ModelReference getModelReference () { - return new ModelReference (m_name, TimeSeriesPredictorModelInstance.MODEL_TYPE); - } - - @Override - protected void subExecute () throws RainbowException { - String modelArgs = Rainbow.instance ().getProperty (PROP_ARGS); - int trainingLength = Integer.parseInt(Rainbow.instance ().getProperty (PROP_TRAININGLENGTH)); - - TimeSeriesPredictorModel pm = new TimeSeriesPredictorModel (modelArgs, trainingLength); - m_result = new TimeSeriesPredictorModelInstance(pm, getModelReference().getModelName(), ""); - doPostExecute (); - } - - @Override - protected void subRedo () throws RainbowException { - doPostExecute (); - } - - @Override - protected void subUndo () throws RainbowException { - doPostUndo (); - } - - @Override - protected boolean checkModelValidForCommand (Object model) { - return true; - } - -} +package org.sa.rainbow.timeseriespredictor.model; + +import java.io.InputStream; + +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; + +public class TimeSeriesPredictorModelLoadModelCommand extends AbstractLoadModelCmd { + + private static final String PROP_ARGS = "customize.model.timeseriespredictor.args"; + public static final String PROP_TRAININGLENGTH = "customize.model.timeseriespredictor.traininglength"; + private String m_name; + private TimeSeriesPredictorModelInstance m_result; + + public TimeSeriesPredictorModelLoadModelCommand (IModelsManager mm, String modelName, InputStream is, String source) { + super ("loadTimeSeriesPredictorModel", mm, modelName, is, source); + m_name = modelName; + } + + @Override + public IModelInstance getResult () throws IllegalStateException { + return m_result; + } + + @Override + public ModelReference getModelReference () { + return new ModelReference (m_name, TimeSeriesPredictorModelInstance.MODEL_TYPE); + } + + @Override + protected void subExecute () throws RainbowException { + String modelArgs = Rainbow.instance ().getProperty (PROP_ARGS); + int trainingLength = Integer.parseInt(Rainbow.instance ().getProperty (PROP_TRAININGLENGTH)); + + TimeSeriesPredictorModel pm = new TimeSeriesPredictorModel (modelArgs, trainingLength); + m_result = new TimeSeriesPredictorModelInstance(pm, getModelReference().getModelName(), ""); + doPostExecute (); + } + + @Override + protected void subRedo () throws RainbowException { + doPostExecute (); + } + + @Override + protected void subUndo () throws RainbowException { + doPostUndo (); + } + + @Override + protected boolean checkModelValidForCommand (Object model) { + return true; + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java index 0706576f6..7c245ff75 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerActiveGauge.java @@ -1,92 +1,92 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created November 1, 2006. - */ -package org.sa.rainbow.translator.swim.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Gauge for marking servers as active or not - * - * @author gmoreno - */ -public class ServerActiveGauge extends RegularPatternGauge { - - public static final String NAME = "G - ServerActive"; - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "activateServer" - }; - private static final String DEFAULT = "DEFAULT"; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public ServerActiveGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern (DEFAULT, Pattern.compile (".*")); - } - - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - int numServers = Integer.parseInt(m.group(0)); - int thisServer = (int) m_configParams.get("serverNum").getValue(); - - boolean serverActive = numServers >= thisServer; - - m_reportingPort.trace (getComponentType (), "Updating server active condition to " + serverActive); - if (m_commands.containsKey (valueNames[0])) { - IRainbowOperation cmd = getCommand (valueNames[0]); - Map parameterMap = new HashMap<> (); - parameterMap.put (cmd.getParameters ()[0], (serverActive) ? "true" : "false"); - issueCommand (cmd, parameterMap); - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.swim.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Gauge for marking servers as active or not + * + * @author gmoreno + */ +public class ServerActiveGauge extends RegularPatternGauge { + + public static final String NAME = "G - ServerActive"; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "activateServer" + }; + private static final String DEFAULT = "DEFAULT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public ServerActiveGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile (".*")); + } + + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + int numServers = Integer.parseInt(m.group(0)); + int thisServer = (int) m_configParams.get("serverNum").getValue(); + + boolean serverActive = numServers >= thisServer; + + m_reportingPort.trace (getComponentType (), "Updating server active condition to " + serverActive); + if (m_commands.containsKey (valueNames[0])) { + IRainbowOperation cmd = getCommand (valueNames[0]); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], (serverActive) ? "true" : "false"); + issueCommand (cmd, parameterMap); + } + } + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java index 83f165470..046629644 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/ServerEnabledGauge.java @@ -1,91 +1,91 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created November 1, 2006. - */ -package org.sa.rainbow.translator.swim.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Gauge for marking servers as enabled or not - * - * @author gmoreno - */ -public class ServerEnabledGauge extends RegularPatternGauge { - - public static final String NAME = "G - ServerEnabled"; - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "serverEnabled" - }; - private static final String DEFAULT = "DEFAULT"; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public ServerEnabledGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern (DEFAULT, Pattern.compile (".*")); - } - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - int numServers = Integer.parseInt(m.group(0)); - int thisServer = (int) m_configParams.get("serverNum").getValue(); - - boolean serverEnabled = numServers >= thisServer; - - m_reportingPort.trace (getComponentType (), "Updating server enablement to " + serverEnabled); - if (m_commands.containsKey (valueNames[0])) { - IRainbowOperation cmd = getCommand (valueNames[0]); - Map parameterMap = new HashMap<> (); - parameterMap.put (cmd.getParameters ()[0], (serverEnabled) ? "true" : "false"); - issueCommand (cmd, parameterMap); - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.swim.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Gauge for marking servers as enabled or not + * + * @author gmoreno + */ +public class ServerEnabledGauge extends RegularPatternGauge { + + public static final String NAME = "G - ServerEnabled"; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "serverEnabled" + }; + private static final String DEFAULT = "DEFAULT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public ServerEnabledGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile (".*")); + } + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + int numServers = Integer.parseInt(m.group(0)); + int thisServer = (int) m_configParams.get("serverNum").getValue(); + + boolean serverEnabled = numServers >= thisServer; + + m_reportingPort.trace (getComponentType (), "Updating server enablement to " + serverEnabled); + if (m_commands.containsKey (valueNames[0])) { + IRainbowOperation cmd = getCommand (valueNames[0]); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], (serverEnabled) ? "true" : "false"); + issueCommand (cmd, parameterMap); + } + } + } + +} diff --git a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java index 11d6ba6d4..284439232 100644 --- a/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java +++ b/deployments/rainbow-swim/src/main/java/org/sa/rainbow/translator/swim/gauges/SimpleGauge.java @@ -1,84 +1,84 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created November 1, 2006. - */ -package org.sa.rainbow.translator.swim.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Simple gauge: complete probe output passed as arg to command - * - * @author gmoreno - */ -public class SimpleGauge extends RegularPatternGauge { - - public static final String NAME = "G - SimpleGauge"; - - private static final String DEFAULT = "DEFAULT"; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public SimpleGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern (DEFAULT, Pattern.compile (".*")); - } - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - String value = m.group(0); - String commandName = m_commands.keySet().iterator().next(); - m_reportingPort.trace (getComponentType (), - "Updating component prop using command " - + commandName + " and value = " + value); - IRainbowOperation cmd = getCommand (commandName); - Map parameterMap = new HashMap<> (); - parameterMap.put (cmd.getParameters ()[0], value); - issueCommand (cmd, parameterMap); - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.swim.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Simple gauge: complete probe output passed as arg to command + * + * @author gmoreno + */ +public class SimpleGauge extends RegularPatternGauge { + + public static final String NAME = "G - SimpleGauge"; + + private static final String DEFAULT = "DEFAULT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public SimpleGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile (".*")); + } + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + String value = m.group(0); + String commandName = m_commands.keySet().iterator().next(); + m_reportingPort.trace (getComponentType (), + "Updating component prop using command " + + commandName + " and value = " + value); + IRainbowOperation cmd = getCommand (commandName); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], value); + issueCommand (cmd, parameterMap); + } + } + +} diff --git a/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/model/gauges.rbw b/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/model/gauges.rbw new file mode 100644 index 000000000..5e50971a8 --- /dev/null +++ b/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/model/gauges.rbw @@ -0,0 +1,208 @@ +target rainbow-example +import properties "../properties.rbw" +import configuration "../system/probes.rbw" + +gauge type LoadGaugeT = { + model factory org.sa.rainbow.^model.acme.swim.^commands.SwimCommandFactory + command load = ServerT.setLoad(double) + setup = { + targetIP = "localhost" + beaconPeriod = 20000 + javaClass = org.sa.rainbow.translator.swim.gauges.SimpleGauge + } + config = { + samplingFrequency = 5000 + targetProbe = probe GenericProbeT + } + comment = "LoadGaugeT measures and reports CPU load for the target host" +} + +gauge type DimmerGaugeT = { + model factory org.sa.rainbow.^model.acme.swim.^commands.SwimCommandFactory + command dimmer = ServerT.setDimmer(double) + setup = { + targetIP = "localhost" + beaconPeriod = 30000 + javaClass = org.sa.rainbow.translator.swim.gauges.SimpleGauge + } + config = { + samplingFrequency = 1500 + } + comment = "DimmerGaugeT measures and reports the dimmer value of the system" +} + +gauge type ServerEnablementGaugeT = { + model factory org.sa.rainbow.^model.acme.swim.^commands.SwimCommandFactory + command serverEnabled = ServerT.enableServer(boolean) + setup = { + targetIP = "localhost" + beaconPeriod = 30000 + javaClass = org.sa.rainbow.translator.swim.gauges.ServerEnabledGauge + } + config = { + samplingFrequency = 10000 + serverNum = java.lang.Integer + } +} + +gauge type ServerActivationGaugeT = { + model factory org.sa.rainbow.^model.acme.swim.^commands.SwimCommandFactory + command activateServer = ServerT.activateServer(boolean) + setup = { + targetIP = "localhost" + beaconPeriod = 30000 + javaClass = org.sa.rainbow.translator.swim.gauges.ServerActiveGauge + } + config = { + samplingFrequency = 10000 + serverNum = java.lang.Integer + } + comment = "ServerActivationGaugeT reports if a server is active or not. serverNum is the server number (e.g., 1, 2 3), so that if there are N active servers, this server is active if N >= serverNum" +} + +gauge DimmerG0 -> DimmerGaugeT = { + model ««SwimSys»» + command dimmer = LB0.setDimmer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = probe DimmerProbe + } + comment = "DimmerG0 is associated with the component LB0 of the System, SwimSys, defined as an Acme model" +} + +gauge ServerEnabledG1 -> ServerEnablementGaugeT = { + model ««SwimSys»» + command serverEnabled = server1.enableServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = probe ServersProbe + serverNum = 1 + } +} + +gauge ServerEnabledG2 -> ServerEnablementGaugeT = { + model ««SwimSys»» + command serverEnabled = server2.enableServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = probe ServersProbe + serverNum = 2 + } +} + +gauge ServerEnabledG3 -> ServerEnablementGaugeT = { + model ««SwimSys»» + command serverEnabled = server3.enableServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = probe ServersProbe + serverNum = 3 + } +} + +gauge ServerActiveG1 -> ServerActivationGaugeT = { + model ««SwimSys»» + command activateServer = server1.activateServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = probe ActivateServersProbe + serverNum = 1 + } +} + +gauge ServerActiveG2 -> ServerActivationGaugeT = { + model ««SwimSys»» + command activateServer = server2.activateServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = probe ActivateServersProbe + serverNum = 2 + } +} + +gauge ServerActiveG3 -> ServerActivationGaugeT = { + model ««SwimSys»» + command activateServer = server3.activateServer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = probe ActivateServersProbe + serverNum = 3 + } +} + +gauge BasicResponseTimeG0 = { + model ««SwimSys»» + command basicResponseTime = LB0.setBasicResponseTime($) + setup = { + targetIP = ««customize.system.^target.lb»» + beaconPeriod = 30000 + javaClass = org.sa.rainbow.translator.swim.gauges.SimpleGauge + } + config = { + targetProbe = probe BasicResponseTimeProbe + samplingFrequency = 15000 + } +} + +gauge OptResponseTimeG0 = { + model ««SwimSys»» + command optResponseTime = LB0.setOptResponseTime($) + setup = { + targetIP = ««customize.system.^target.lb»» + beaconPeriod = 30000 + javaClass = org.sa.rainbow.translator.swim.gauges.SimpleGauge + } + config = { + targetProbe = probe OptResponseTimeProbe + samplingFrequency = 15000 + } +} + +gauge LoadG1 -> LoadGaugeT= { + model SwimSys::Acme + command load = server1.setLoad($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = probe LoadProbe1 + } +} + +gauge LoadG2 -> LoadGaugeT= { + model SwimSys::Acme + command load = server2.setLoad($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = probe LoadProbe2 + } +} + +gauge LoadG3 -> LoadGaugeT= { + model SwimSys::Acme + command load = server3.setLoad($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = probe LoadProbe3 + } +} + +export * to "model/gauges.yml" \ No newline at end of file diff --git a/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/properties.rbw b/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/properties.rbw new file mode 100644 index 000000000..498535559 --- /dev/null +++ b/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/properties.rbw @@ -0,0 +1,124 @@ +target rainbow-example + +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. +def rainbow.path # Default property defined by rainbow + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +def logging.level = DEBUG +def event.log.path = "log" +def logging.path = "«event.log.path»/rainbow.out" +def monitoring.log.path = "«event.log.path»/rainbow-data.log" +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +def rainbow.master.location.host = "rainbow-example" +#- Location information of the deployed delegate +def rainbow.deployment.location = "rainbow-example" +#- default registry port; change if port-tunneling +def rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +def rainbow.deployment.environment = "linux" + +def rainbow.delegate.beaconperiod = 10000 +def rainbow.deployment.^factory.class = org.sa.rainbow.core.ports.guava.GuavaRainbowPortFactory + +### Rainbow models + +def rainbow.^model.number=2 + +# Rainbow Acme model of SWIM +def model SwimSys= { + ^type="Acme" + path="model/swim.acme" + ^factory=org.sa.rainbow.^model.acme.swim.commands.SwimCommandFactory + saveOnClose = true + saveLocation="model/swim-post.acme" +} + +# Rainbow Utility Model +def model USwimSys = { + name="SwimSys" + //^type="Utility" + path="stitch/utilities.yml" + ^factory=org.sa.rainbow.^model.utility.UtilityCommandFactory +} + +### Rainbow analyses +def analysis ArchEvaluator = { + class = org.sa.rainbow.evaluator.acme.ArchEvaluator +} + + +def adaptation-manager AdaptationManager = { + ^model=««SwimSys»» + class=org.sa.rainbow.stitch.adaptation.AdaptationManager +} + +def executor StitchExecutor = { + ^model=««SwimSys»» + class=org.sa.rainbow.stitch.adaptation.StitchExecutor +} + +def effector-manager AcmeEffectorManager = { + class = org.sa.rainbow.effectors.acme.AcmeEffectorManager +} + + +def rainbow.^gui=org.sa.rainbow.^gui.RainbowWindoe +def rainbow.^gui.specs = "ui.yml" + +def customize.^model.evaluate.period = 60000 +def customize.^model.timeseriespredictor.args="LES 0.8 0.15" +def customize.^model.timeseriespredictor.traininglength=15 + +## Translator customization +#- Gauge spec +def customize.gauges.path = "model/gauges.yml" +#- Probe spec +def customize.probes.path = "system/probes.yml" +#- Operator spec as mapping to effector +def customize.archop.map.path = "model/op.map" +#- Effector spec +def customize.effectors.path = "system/effectors.yml" +## Adaptation Manager +#- Directory of Stitch adaptation script +def customize.scripts.path = "stitch" +#- Utilities description file, Strategy evaluation config, and minimum score threshold +def customize.utility.path = "stitch/utilities.yml" +def customize.utility.trackStrategy = "uC" +def customize.utility.score.minimum.threshold = 0.033 +def customize.utility.scenario = "scenario 1" +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# These properties may be referred to in various files +# in the target (e.g., Acme, gauges, effectors, probes) +# and are replaced by Rainbow with the actual values. +# They may define deployment information (e.g., in terms of IPs and ports) +# among other things +def customize.system.^target.master = ««rainbow.deployment.location»» +def customize.system.^target.lb = ««rainbow.deployment.location»» + +export * to "rainbow.properties" diff --git a/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/system/effectors.rbw b/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/system/effectors.rbw new file mode 100644 index 000000000..154b0abe8 --- /dev/null +++ b/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/system/effectors.rbw @@ -0,0 +1,35 @@ +target rainbow-example +import properties "../properties.rbw" +def effectors.commonPath = "«rainbow.path»/system/probes" + +effector setDimmer = { + model ««SwimSys»» + command ««customize.system.^target.lb»».setDimmer($) + location = ««customize.system.^target.lb»» + script = { + path = "«effectors.commonPath»/setDimmer.sh" + argument = "{0}" + } +} + +effector addServer = { + model ««SwimSys»» + command ««customize.system.^target.lb»».addServer($) + location = ««customize.system.^target.lb»» + script = { + path = "«effectors.commonPath»/addServer.sh" + argument = "" + } +} + +effector removeServer = { + model ««SwimSys»» + command ««customize.system.^target.lb»».removeServer($) + location = ««customize.system.^target.lb»» + script = { + path = "«effectors.commonPath»/removeServer.sh" + argument = "" + } +} + +export * to "system/effectors.yml" \ No newline at end of file diff --git a/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/system/probes.rbw b/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/system/probes.rbw new file mode 100644 index 000000000..d24e9a619 --- /dev/null +++ b/deployments/rainbow-swim/src/main/resources/rbw/rainbow-example/system/probes.rbw @@ -0,0 +1,70 @@ +target rainbow-example // generates "system/probes.yml" +import properties "../properties.rbw" +def probes.commonPath = "«rainbow.path»/system/probes" + +probe type GenericProbeT = { + location = ««customize.system.^target.lb»» + script = { + mode = "continual" + path = "«probes.commonPath»/genericProbe.pl" + } +} + +probe DimmerProbe -> GenericProbeT = { + alias = "dimmer" + script = { + argument = "get_dimmer" + } +} + +probe ServersProbe -> GenericProbeT = { + alias = "servers" + script = { + argument = "servers" + } +} + +probe ActivateServersProbe -> GenericProbeT = { + alias = "activeServers" + script = { + argument="get_active_servers" + } +} + +probe LoadProbe1 -> GenericProbeT = { + alias="load1" + script = { + argument = "-d 5000 get_utilization server1" + } +} + +probe LoadProbe2 -> GenericProbeT = { + alias = "load2" + script = { + argument = "-d 5000 get_utilization server2" + } +} + +probe LoadProbe3 -> GenericProbeT = { + alias = "load3" + script = { + argument = "-d 5000 get_utilization server3" + } +} + +probe BasicResponseTimeProbe -> GenericProbeT = { + alias = "basicResponseTime" + script = { + argument = "get_basic_rt" + } +} + +probe OptResponseTimeProbe -> GenericProbeT = { + alias = "optResponseTime" + script = { + argument = "get_opt_rt" + } +} + +export * to "system/probes.yml" + diff --git a/deployments/rainbow-swim/src/test/java/org/sa/rainbow/translator/swim/gauges/GaugesTest.java b/deployments/rainbow-swim/src/test/java/org/sa/rainbow/translator/swim/gauges/GaugesTest.java new file mode 100644 index 000000000..729421194 --- /dev/null +++ b/deployments/rainbow-swim/src/test/java/org/sa/rainbow/translator/swim/gauges/GaugesTest.java @@ -0,0 +1,22 @@ +package org.sa.rainbow.translator.swim.gauges; + +import static org.junit.Assert.fail; + +import org.junit.Before; +import org.junit.Test; +import org.sa.rainbow.testing.prepare.RainbowMocker; + +public class GaugesTest { + + @Before + public void setUp() throws Exception { + RainbowMocker.injectRainbow(); + IRainbowConnectionPortFactory mockedPortFactory = mockCOnnectionPo + } + + @Test + public void test() { + fail("Not yet implemented"); + } + +} diff --git a/deployments/rainbow-swim/src/test/resources/acme/imports.acme b/deployments/rainbow-swim/src/test/resources/acme/imports.acme index 3ac812089..9050035ed 100644 --- a/deployments/rainbow-swim/src/test/resources/acme/imports.acme +++ b/deployments/rainbow-swim/src/test/resources/acme/imports.acme @@ -1,4 +1,4 @@ -import "families/f1.acme"; -system s : f1 = new f1 extended with { - component c : CT = new CT; +import "families/f1.acme"; +system s : f1 = new f1 extended with { + component c : CT = new CT; } \ No newline at end of file diff --git a/deployments/rainbow-swim/src/test/resources/acme/inbuilt-system.acme b/deployments/rainbow-swim/src/test/resources/acme/inbuilt-system.acme index 3898789d8..addb5fe5b 100644 --- a/deployments/rainbow-swim/src/test/resources/acme/inbuilt-system.acme +++ b/deployments/rainbow-swim/src/test/resources/acme/inbuilt-system.acme @@ -1,9 +1,9 @@ -family f1 = { - - component type CT = { - property p : int; - } -} -system s : f1 = new f1 extended with { - component c : CT = new CT; +family f1 = { + + component type CT = { + property p : int; + } +} +system s : f1 = new f1 extended with { + component c : CT = new CT; } \ No newline at end of file diff --git a/deployments/rainbow-swim/src/test/resources/acme/self-contained.acme b/deployments/rainbow-swim/src/test/resources/acme/self-contained.acme index 63362bbe3..a019b82c9 100644 --- a/deployments/rainbow-swim/src/test/resources/acme/self-contained.acme +++ b/deployments/rainbow-swim/src/test/resources/acme/self-contained.acme @@ -1,3 +1,3 @@ -system s = { - component c; +system s = { + component c; } \ No newline at end of file diff --git a/deployments/rainbow-swim/src/test/resources/acme/znn.acme b/deployments/rainbow-swim/src/test/resources/acme/znn.acme index 15511dbfe..5da216500 100644 --- a/deployments/rainbow-swim/src/test/resources/acme/znn.acme +++ b/deployments/rainbow-swim/src/test/resources/acme/znn.acme @@ -1,270 +1,270 @@ -Family ZNewsFam = { - - Port Type HttpPortT = { - - } - Role Type RequestorRoleT = { - - } - Component Type ProxyT = { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - } - Port Type ProxyForwardPortT = { - - } - Component Type ServerT = { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - Property reqServiceRate : float << default : float = 0.0; >> ; - - Property byteServiceRate : float << default : float = 0.0; >> ; - - Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; - - Property cost : float << default : float = 1.0; >> ; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - Role Type ReceiverRoleT = { - - } - Connector Type ProxyConnT = { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - Component Type ClientT = { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property experRespTime : float << default : float = 0.0; >> ; - - Property reqRate : float << default : float = 0.0; >> ; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - Port Type HttpReqPortT = { - - } - Connector Type HttpConnT = { - - Property bandwidth : float << default : float = 0.0; >> ; - - Property latency : float << default : float = 0.0; >> ; - - Property numReqsSuccess : int << default : int = 0; >> ; - - Property numReqsRedirect : int << default : int = 0; >> ; - - Property numReqsClientError : int << default : int = 0; >> ; - - Property numReqsServerError : int << default : int = 0; >> ; - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - - Property MIN_RESPTIME : float; - - Property MAX_RESPTIME : float; - - Property TOLERABLE_PERCENT_UNHAPPY : float; - - Property UNHAPPY_GRADIENT_1 : float; - - Property UNHAPPY_GRADIENT_2 : float; - - Property UNHAPPY_GRADIENT_3 : float; - - Property FRACTION_GRADIENT_1 : float; - - Property FRACTION_GRADIENT_2 : float; - - Property FRACTION_GRADIENT_3 : float; - - Property MIN_UTIL : float; - - Property MAX_UTIL : float; - - Property MAX_FIDELITY_LEVEL : int; - - Property THRESHOLD_FIDELITY : int; - - Property THRESHOLD_COST : float; -} - -System ZNewsSys : ZNewsFam = { - - - Property MIN_RESPTIME : float = 100; - - Property MAX_RESPTIME : float = 2000; - - Property UNHAPPY_GRADIENT_1 : float = 0.1; - - Property UNHAPPY_GRADIENT_2 : float = 0.2; - - Property UNHAPPY_GRADIENT_3 : float = 0.5; - - Property FRACTION_GRADIENT_1 : float = 0.2; - - Property FRACTION_GRADIENT_2 : float = 0.4; - - Property FRACTION_GRADIENT_3 : float = 1.0; - - Property TOLERABLE_PERCENT_UNHAPPY : float = 0.25; - - Property MIN_UTIL : float = 0.1; - - Property MAX_UTIL : float = 0.75; - - Property MAX_FIDELITY_LEVEL : int = 5; - - Property THRESHOLD_FIDELITY : int = 2; - - Property THRESHOLD_COST : float = 6.0; - Component s1 : ServerT = new ServerT extended with { - - Property deploymentLocation = "127.0.0.2"; - Port http0 : HttpPortT = new HttpPortT extended with { - - } - - } - Component lbproxy : ProxyT = new ProxyT extended with { - - Property deploymentLocation = "127.0.0.1"; - Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port http0 : HttpPortT = new HttpPortT extended with { - - } - Port http1 : HttpPortT = new HttpPortT extended with { - - } - Port http2 : HttpPortT = new HttpPortT extended with { - - } - - } - Component s2 : ServerT = new ServerT extended with { - - Property deploymentLocation = "127.0.0.3"; - Port http0 : HttpPortT = new HttpPortT extended with { - - } - - } - Component s3 : ServerT = new ServerT extended with { - - Property deploymentLocation = "127.0.0.4"; - Port http0 : HttpPortT = new HttpPortT extended with { - - } - - } - Component s0 : ServerT = new ServerT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property cost = 1.0; - - Property fidelity = 5; - - Property load = 0.0; - Port http0 : HttpPortT = new HttpPortT extended with { - - } - - } - Component c0 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property experRespTime : float = 50.0; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - } - - } - Component c1 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property experRespTime : float = 50; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - } - - } - Component c2 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property experRespTime : float = 50; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - } - - } - Connector conn0 : HttpConnT = new HttpConnT extended with { - - } - Connector proxyconn0 : ProxyConnT = new ProxyConnT extended with { - - } - Connector proxyconn1 : ProxyConnT = new ProxyConnT extended with { - - } - Connector proxyconn3 : ProxyConnT = new ProxyConnT extended with { - - } - Connector proxyconn2 : ProxyConnT = new ProxyConnT extended with { - - } - Connector conn : HttpConnT = new HttpConnT extended with { - - } - Connector conn1 : HttpConnT = new HttpConnT extended with { - - } - Attachment lbproxy.fwd0 to proxyconn0.req; - Attachment s2.http0 to proxyconn2.rec; - Attachment lbproxy.fwd1 to proxyconn1.req; - Attachment s1.http0 to proxyconn1.rec; - Attachment s0.http0 to proxyconn0.rec; - Attachment c0.p0 to conn0.req; - Attachment lbproxy.http0 to conn0.rec; - Attachment s3.http0 to proxyconn3.rec; - Attachment lbproxy.fwd3 to proxyconn3.req; - Attachment c1.p0 to conn.req; - Attachment c2.p0 to conn1.req; - Attachment lbproxy.http2 to conn1.rec; - Attachment lbproxy.http1 to conn.rec; -} - +Family ZNewsFam = { + + Port Type HttpPortT = { + + } + Role Type RequestorRoleT = { + + } + Component Type ProxyT = { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Port Type ProxyForwardPortT = { + + } + Component Type ServerT = { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + Property reqServiceRate : float << default : float = 0.0; >> ; + + Property byteServiceRate : float << default : float = 0.0; >> ; + + Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; + + Property cost : float << default : float = 1.0; >> ; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + Role Type ReceiverRoleT = { + + } + Connector Type ProxyConnT = { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Component Type ClientT = { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property experRespTime : float << default : float = 0.0; >> ; + + Property reqRate : float << default : float = 0.0; >> ; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + Port Type HttpReqPortT = { + + } + Connector Type HttpConnT = { + + Property bandwidth : float << default : float = 0.0; >> ; + + Property latency : float << default : float = 0.0; >> ; + + Property numReqsSuccess : int << default : int = 0; >> ; + + Property numReqsRedirect : int << default : int = 0; >> ; + + Property numReqsClientError : int << default : int = 0; >> ; + + Property numReqsServerError : int << default : int = 0; >> ; + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + + Property MIN_RESPTIME : float; + + Property MAX_RESPTIME : float; + + Property TOLERABLE_PERCENT_UNHAPPY : float; + + Property UNHAPPY_GRADIENT_1 : float; + + Property UNHAPPY_GRADIENT_2 : float; + + Property UNHAPPY_GRADIENT_3 : float; + + Property FRACTION_GRADIENT_1 : float; + + Property FRACTION_GRADIENT_2 : float; + + Property FRACTION_GRADIENT_3 : float; + + Property MIN_UTIL : float; + + Property MAX_UTIL : float; + + Property MAX_FIDELITY_LEVEL : int; + + Property THRESHOLD_FIDELITY : int; + + Property THRESHOLD_COST : float; +} + +System ZNewsSys : ZNewsFam = { + + + Property MIN_RESPTIME : float = 100; + + Property MAX_RESPTIME : float = 2000; + + Property UNHAPPY_GRADIENT_1 : float = 0.1; + + Property UNHAPPY_GRADIENT_2 : float = 0.2; + + Property UNHAPPY_GRADIENT_3 : float = 0.5; + + Property FRACTION_GRADIENT_1 : float = 0.2; + + Property FRACTION_GRADIENT_2 : float = 0.4; + + Property FRACTION_GRADIENT_3 : float = 1.0; + + Property TOLERABLE_PERCENT_UNHAPPY : float = 0.25; + + Property MIN_UTIL : float = 0.1; + + Property MAX_UTIL : float = 0.75; + + Property MAX_FIDELITY_LEVEL : int = 5; + + Property THRESHOLD_FIDELITY : int = 2; + + Property THRESHOLD_COST : float = 6.0; + Component s1 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.2"; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component lbproxy : ProxyT = new ProxyT extended with { + + Property deploymentLocation = "127.0.0.1"; + Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port http0 : HttpPortT = new HttpPortT extended with { + + } + Port http1 : HttpPortT = new HttpPortT extended with { + + } + Port http2 : HttpPortT = new HttpPortT extended with { + + } + + } + Component s2 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.3"; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component s3 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.4"; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component s0 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property cost = 1.0; + + Property fidelity = 5; + + Property load = 0.0; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component c0 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50.0; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + } + + } + Component c1 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + } + + } + Component c2 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + } + + } + Connector conn0 : HttpConnT = new HttpConnT extended with { + + } + Connector proxyconn0 : ProxyConnT = new ProxyConnT extended with { + + } + Connector proxyconn1 : ProxyConnT = new ProxyConnT extended with { + + } + Connector proxyconn3 : ProxyConnT = new ProxyConnT extended with { + + } + Connector proxyconn2 : ProxyConnT = new ProxyConnT extended with { + + } + Connector conn : HttpConnT = new HttpConnT extended with { + + } + Connector conn1 : HttpConnT = new HttpConnT extended with { + + } + Attachment lbproxy.fwd0 to proxyconn0.req; + Attachment s2.http0 to proxyconn2.rec; + Attachment lbproxy.fwd1 to proxyconn1.req; + Attachment s1.http0 to proxyconn1.rec; + Attachment s0.http0 to proxyconn0.rec; + Attachment c0.p0 to conn0.req; + Attachment lbproxy.http0 to conn0.rec; + Attachment s3.http0 to proxyconn3.rec; + Attachment lbproxy.fwd3 to proxyconn3.req; + Attachment c1.p0 to conn.req; + Attachment c2.p0 to conn1.req; + Attachment lbproxy.http2 to conn1.rec; + Attachment lbproxy.http1 to conn.rec; +} + diff --git a/deployments/rainbow-swim/src/test/resources/log4j.properties b/deployments/rainbow-swim/src/test/resources/log4j.properties index 6b8797ece..4c0d3a502 100644 --- a/deployments/rainbow-swim/src/test/resources/log4j.properties +++ b/deployments/rainbow-swim/src/test/resources/log4j.properties @@ -1,4 +1,4 @@ -log4j.rootLogger=INFO,CONSOLE -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%-5p $c{1} - %m%n +log4j.rootLogger=INFO,CONSOLE +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%-5p $c{1} - %m%n diff --git a/deployments/rainbow-swim/src/test/resources/log4j.xml b/deployments/rainbow-swim/src/test/resources/log4j.xml index 74d4dcd16..829891348 100644 --- a/deployments/rainbow-swim/src/test/resources/log4j.xml +++ b/deployments/rainbow-swim/src/test/resources/log4j.xml @@ -1,21 +1,21 @@ - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/deployments/rainbow-znn/.project b/deployments/rainbow-znn/.project index a92ee7679..20cec0bb2 100644 --- a/deployments/rainbow-znn/.project +++ b/deployments/rainbow-znn/.project @@ -1,23 +1,23 @@ - - - rainbow-znn - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - org.eclipse.jdt.core.javanature - - + + + rainbow-znn + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + + diff --git a/deployments/rainbow-znn/.settings/org.eclipse.core.resources.prefs b/deployments/rainbow-znn/.settings/org.eclipse.core.resources.prefs index 52d2be156..226a7eb35 100644 --- a/deployments/rainbow-znn/.settings/org.eclipse.core.resources.prefs +++ b/deployments/rainbow-znn/.settings/org.eclipse.core.resources.prefs @@ -1,5 +1,5 @@ -eclipse.preferences.version=1 -encoding//src/main/java=utf-8 -encoding//src/test/java=utf-8 -encoding//src/test/resources=utf-8 -encoding/=utf-8 +eclipse.preferences.version=1 +encoding//src/main/java=utf-8 +encoding//src/test/java=utf-8 +encoding//src/test/resources=utf-8 +encoding/=utf-8 diff --git a/deployments/rainbow-znn/.settings/org.eclipse.jdt.core.prefs b/deployments/rainbow-znn/.settings/org.eclipse.jdt.core.prefs index f4217b01d..62492222a 100644 --- a/deployments/rainbow-znn/.settings/org.eclipse.jdt.core.prefs +++ b/deployments/rainbow-znn/.settings/org.eclipse.jdt.core.prefs @@ -1,12 +1,12 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.7 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.7 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/deployments/rainbow-znn/.settings/org.eclipse.m2e.core.prefs b/deployments/rainbow-znn/.settings/org.eclipse.m2e.core.prefs index 14b697b7b..f897a7f1c 100644 --- a/deployments/rainbow-znn/.settings/org.eclipse.m2e.core.prefs +++ b/deployments/rainbow-znn/.settings/org.eclipse.m2e.core.prefs @@ -1,4 +1,4 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/evaluator/znn/ZNNStateAnalyzer.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/evaluator/znn/ZNNStateAnalyzer.java index 24c24a5a7..2b2923363 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/evaluator/znn/ZNNStateAnalyzer.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/evaluator/znn/ZNNStateAnalyzer.java @@ -1,222 +1,228 @@ -package org.sa.rainbow.evaluator.znn; - -import org.acmestudio.acme.core.exception.AcmeException; -import org.acmestudio.acme.core.resource.IAcmeLanguageHelper; -import org.acmestudio.acme.core.resource.RegionManager; -import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; -import org.acmestudio.acme.element.IAcmeElementInstance; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.environment.error.AcmeError; -import org.acmestudio.acme.model.event.AcmeModelEventType; -import org.acmestudio.acme.rule.AcmeSet; -import org.acmestudio.acme.rule.node.IExpressionNode; -import org.acmestudio.acme.type.verification.NodeScopeLookup; -import org.acmestudio.acme.type.verification.RuleTypeChecker; -import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; -import org.sa.rainbow.core.*; -import org.sa.rainbow.core.analysis.IRainbowAnalysis; -import org.sa.rainbow.core.error.RainbowConnectionException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.ports.*; -import org.sa.rainbow.model.acme.AcmeModelOperation; -import org.sa.rainbow.model.acme.znn.ZNNModelUpdateOperatorsImpl; -import org.sa.rainbow.model.acme.znn.commands.SetSystemPropertiesCmd; -import org.sa.rainbow.translator.znn.gauges.ClientResponseTimeGauge; - -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * Created by schmerl on 9/10/2015. - *

- * Records the overall state of the system as system level properties. Mostly used for tracing. - */ -public class ZNNStateAnalyzer extends AbstractRainbowRunnable implements IRainbowAnalysis, IModelChangeBusSubscriberPort.IRainbowModelChangeCallback { - - public static final String NAME = "ZNN State Evaluator"; - public static final String OPERATION_NAME = "setSystemProperties"; - - // These match some of the statements in the stitch conditions - public static final String CLIENTS_SELECTION = "/self/components:!ClientT"; // All clients - public static final String MALICIOUS_CLIENTS_SELECTION = "/self/components:!PotentiallyMaliciousT[maliciousness>self.MALICIOUS_THRESHOLD]"; // All malicious clients - public static final String ABOVE_MALICIOUSNESS = "aboveMaliciousThreshold (self)"; // #malicious clients exceeds threshold - public static final String HIGH_RT = "exists c :! ClientT in self.components | (c.experRespTime > self.MAX_RESPTIME)"; // Is a client getting bad response - - private IModelChangeBusSubscriberPort m_modelChangePort; - private IModelUSBusPort m_modelUSPort; - private IModelsManagerPort m_modelsManagerPort; - - /** - * Match if a client's maliciousness or experienced response time changes - */ - private IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription m_modelChangeSubscriber = new ClientResponseTimeGauge.ModelBasedSubscription ("ZNewsSys", "Acme") { - @Override - public boolean matches (IRainbowMessage message) { - boolean b = super.matches (message); - String type = (String) message - .getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); - if (type != null) { - return b && ((AcmeModelEventType.ADD_PROPERTY.name ().equals (type) - && message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) - && ((String) message.getProperty (AcmeModelOperation.PROPERTY_PROP)) - .endsWith ("maliciousness")) || - (AcmeModelEventType.ADD_PROPERTY.name ().equals (type) - && message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) - && ((String) message.getProperty (AcmeModelOperation.PROPERTY_PROP)) - .endsWith ("experRespTime")) || - (AcmeModelEventType.SET_PROPERTY_VALUE.name ().equals (type) && message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) && ((String) message.getProperty (AcmeModelOperation.PROPERTY_PROP)).endsWith ("maliciousness")) - || (AcmeModelEventType.SET_PROPERTY_VALUE.name ().equals (type) && message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) && ((String) message.getProperty (AcmeModelOperation.PROPERTY_PROP)).endsWith ("experRespTime")) - ); - } - return false; - } - }; - - private final LinkedBlockingQueue m_modelCheckQ = new LinkedBlockingQueue<> (); - private IExpressionNode m_clientsSelection; - private IExpressionNode m_maliciousSelection; - private Map properties = new HashMap<> (); - private IExpressionNode m_aboveRT; - private IExpressionNode m_aboveMal; - - public ZNNStateAnalyzer () { - super (NAME); - String per = Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); - if (per != null) { - setSleepTime (Long.parseLong (per)); - } else { - setSleepTime (IRainbowRunnable.LONG_SLEEP_TIME); - } - } - - @Override - public void initialize (IRainbowReportingPort port) throws RainbowConnectionException { - super.initialize (port); - initializeConnections (); - initializeSubscriptions (); - initializeAcmeExpressions (); - } - - private void initializeAcmeExpressions () { - IAcmeLanguageHelper lp = StandaloneLanguagePackHelper.defaultLanguageHelper (); - try { - m_clientsSelection = lp.designRuleExpressionFromString (CLIENTS_SELECTION, new RegionManager ()); - m_maliciousSelection = lp.designRuleExpressionFromString (MALICIOUS_CLIENTS_SELECTION, new RegionManager ()); - m_aboveRT = lp.designRuleExpressionFromString (HIGH_RT, new RegionManager ()); - m_aboveMal = lp.designRuleExpressionFromString (ABOVE_MALICIOUSNESS, new RegionManager ()); - } catch (Exception e) { - m_reportingPort.error (RainbowComponentT.ANALYSIS, "Failed to parse selection expressions", e); - } - - } - - private void initializeSubscriptions () { - m_modelChangePort.subscribe (m_modelChangeSubscriber, this); - } - - private void initializeConnections () throws RainbowConnectionException { - m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort (); - m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort (); - m_modelUSPort = RainbowPortFactory.createModelsManagerClientUSPort (this); - } - - @Override - protected void log (String txt) { - m_reportingPort.info (RainbowComponentT.ANALYSIS, txt); - } - - @Override - protected void runAction () { - final ZNNModelUpdateOperatorsImpl model = m_modelCheckQ.poll (); - if (model != null) { - Stack errors = new Stack<> (); - IAcmeSystem system = model.getModelInstance (); - - if (m_clientsSelection != null && m_maliciousSelection != null) { - NodeScopeLookup lookup = new NodeScopeLookup (); - try { - AcmeSet clients = RuleTypeChecker.evaluateAsSet (system, null, m_clientsSelection, errors, lookup); - -// AcmeSet maliciousClients = RuleTypeChecker.evaluateAsSet (system, null, m_maliciousSelection, errors, lookup); - boolean aboveMal = RuleTypeChecker.evaluateAsBoolean (system, null, m_aboveMal, errors, lookup); - boolean aboveRT = RuleTypeChecker.evaluateAsBoolean (system, null, m_aboveRT, errors, lookup); - float avgRT = 0.0f; - float perMal = 0.0f; - if (clients != null) { - float cum = 0.0f; - int numMal = 0; - for (Object o : clients.getValues ()) { - IAcmeProperty prop; - float mal = 0; - if (o instanceof IAcmeElementInstance) { - IAcmeElementInstance client = (IAcmeElementInstance) o; - if ((prop = client.getProperty ("experRespTime")) != null) { - cum += ((IAcmeFloatingPointValue) prop.getValue ()).getFloatValue (); - } - if ((prop = client.getProperty ("maliciousness")) != null) { - mal = ((IAcmeFloatingPointValue) prop.getValue ()).getFloatValue (); - log (MessageFormat.format ("{0}.maliciousness={1}", client, mal)); - if (mal > 0.5) { - numMal++; - } - } - } - } - avgRT = cum / clients.getValues ().size (); - perMal = ((float) numMal) / clients.getValues ().size () * 100f; - SetSystemPropertiesCmd cmd = model.getCommandFactory ().setSystemProperties (system, avgRT, perMal, aboveRT, aboveMal); - m_modelUSPort.updateModel (cmd); - - } - - - } catch (AcmeException e) { - m_reportingPort.error (RainbowComponentT.ANALYSIS, "Failed to evaluate an expression", e); - } - - } - - - } - - } - - @Override - public RainbowComponentT getComponentType () { - return RainbowComponentT.ANALYSIS; - } - - @Override - public void setProperty (String key, String value) { - properties.put (key, value); - } - - @Override - public String getProperty (String key) { - return properties.get (key); - } - - @Override - public void dispose () { - m_modelChangePort.dispose (); - m_reportingPort.dispose (); - m_modelUSPort.dispose (); - } - - @Override - public void onEvent (ModelReference reference, IRainbowMessage message) { - IModelInstance model = m_modelsManagerPort.getModelInstance (reference); - // Add a model to check, if it doesn't already exist to be processed - synchronized (m_modelCheckQ) { - if (model instanceof ZNNModelUpdateOperatorsImpl && !m_modelCheckQ.contains (model)) { - m_modelCheckQ.offer ((ZNNModelUpdateOperatorsImpl) model); - } - } - } -} +package org.sa.rainbow.evaluator.znn; + +import org.acmestudio.acme.core.exception.AcmeException; +import org.acmestudio.acme.core.resource.IAcmeLanguageHelper; +import org.acmestudio.acme.core.resource.RegionManager; +import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; +import org.acmestudio.acme.element.IAcmeElementInstance; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.environment.error.AcmeError; +import org.acmestudio.acme.model.event.AcmeModelEventType; +import org.acmestudio.acme.rule.AcmeSet; +import org.acmestudio.acme.rule.node.IExpressionNode; +import org.acmestudio.acme.type.verification.NodeScopeLookup; +import org.acmestudio.acme.type.verification.RuleTypeChecker; +import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; +import org.sa.rainbow.core.*; +import org.sa.rainbow.core.analysis.IRainbowAnalysis; +import org.sa.rainbow.core.error.RainbowConnectionException; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.ports.*; +import org.sa.rainbow.model.acme.AcmeModelOperation; +import org.sa.rainbow.model.acme.znn.ZNNModelUpdateOperatorsImpl; +import org.sa.rainbow.model.acme.znn.commands.SetSystemPropertiesCmd; +import org.sa.rainbow.translator.znn.gauges.ClientResponseTimeGauge; + +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; +import java.util.Stack; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * Created by schmerl on 9/10/2015. + *

+ * Records the overall state of the system as system level properties. Mostly used for tracing. + */ +public class ZNNStateAnalyzer extends AbstractRainbowRunnable implements IRainbowAnalysis, IModelChangeBusSubscriberPort.IRainbowModelChangeCallback { + + public static final String NAME = "ZNN State Evaluator"; + public static final String OPERATION_NAME = "setSystemProperties"; + + // These match some of the statements in the stitch conditions + public static final String CLIENTS_SELECTION = "/self/components:!ClientT"; // All clients + public static final String MALICIOUS_CLIENTS_SELECTION = "/self/components:!PotentiallyMaliciousT[maliciousness>self.MALICIOUS_THRESHOLD]"; // All malicious clients + public static final String ABOVE_MALICIOUSNESS = "aboveMaliciousThreshold (self)"; // #malicious clients exceeds threshold + public static final String HIGH_RT = "exists c :! ClientT in self.components | (c.experRespTime > self.MAX_RESPTIME)"; // Is a client getting bad response + + private IModelChangeBusSubscriberPort m_modelChangePort; + private IModelUSBusPort m_modelUSPort; + private IModelsManagerPort m_modelsManagerPort; + + /** + * Match if a client's maliciousness or experienced response time changes + */ + private IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription m_modelChangeSubscriber = new ClientResponseTimeGauge.ModelBasedSubscription ("ZNewsSys", "Acme") { + @Override + public boolean matches (IRainbowMessage message) { + boolean b = super.matches (message); + String type = (String) message + .getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); + if (type != null) { + return b && ((AcmeModelEventType.ADD_PROPERTY.name ().equals (type) + && message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) + && ((String) message.getProperty (AcmeModelOperation.PROPERTY_PROP)) + .endsWith ("maliciousness")) || + (AcmeModelEventType.ADD_PROPERTY.name ().equals (type) + && message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) + && ((String) message.getProperty (AcmeModelOperation.PROPERTY_PROP)) + .endsWith ("experRespTime")) || + (AcmeModelEventType.SET_PROPERTY_VALUE.name ().equals (type) && message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) && ((String) message.getProperty (AcmeModelOperation.PROPERTY_PROP)).endsWith ("maliciousness")) + || (AcmeModelEventType.SET_PROPERTY_VALUE.name ().equals (type) && message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) && ((String) message.getProperty (AcmeModelOperation.PROPERTY_PROP)).endsWith ("experRespTime")) + ); + } + return false; + } + }; + + private final LinkedBlockingQueue m_modelCheckQ = new LinkedBlockingQueue<> (); + private IExpressionNode m_clientsSelection; + private IExpressionNode m_maliciousSelection; + private Map properties = new HashMap<> (); + private IExpressionNode m_aboveRT; + private IExpressionNode m_aboveMal; + + public ZNNStateAnalyzer () { + super (NAME); + String per = Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MODEL_EVAL_PERIOD); + if (per != null) { + setSleepTime (Long.parseLong (per)); + } else { + setSleepTime (IRainbowRunnable.LONG_SLEEP_TIME); + } + } + + @Override + public void initialize (IRainbowReportingPort port) throws RainbowConnectionException { + super.initialize (port); + initializeConnections (); + initializeSubscriptions (); + initializeAcmeExpressions (); + } + + private void initializeAcmeExpressions () { + IAcmeLanguageHelper lp = StandaloneLanguagePackHelper.defaultLanguageHelper (); + try { + m_clientsSelection = lp.designRuleExpressionFromString (CLIENTS_SELECTION, new RegionManager ()); + m_maliciousSelection = lp.designRuleExpressionFromString (MALICIOUS_CLIENTS_SELECTION, new RegionManager ()); + m_aboveRT = lp.designRuleExpressionFromString (HIGH_RT, new RegionManager ()); + m_aboveMal = lp.designRuleExpressionFromString (ABOVE_MALICIOUSNESS, new RegionManager ()); + } catch (Exception e) { + m_reportingPort.error (RainbowComponentT.ANALYSIS, "Failed to parse selection expressions", e); + } + + } + + private void initializeSubscriptions () { + m_modelChangePort.subscribe (m_modelChangeSubscriber, this); + } + + private void initializeConnections () throws RainbowConnectionException { + m_modelChangePort = RainbowPortFactory.createModelChangeBusSubscriptionPort (); + m_modelsManagerPort = RainbowPortFactory.createModelsManagerRequirerPort (); + m_modelUSPort = RainbowPortFactory.createModelsManagerClientUSPort (this); + } + + @Override + protected void log (String txt) { + m_reportingPort.info (RainbowComponentT.ANALYSIS, txt); + } + + @Override + protected void runAction () { + final ZNNModelUpdateOperatorsImpl model = m_modelCheckQ.poll (); + if (model != null) { + Stack errors = new Stack<> (); + IAcmeSystem system = model.getModelInstance (); + + if (m_clientsSelection != null && m_maliciousSelection != null) { + NodeScopeLookup lookup = new NodeScopeLookup (); + try { + AcmeSet clients = RuleTypeChecker.evaluateAsSet (system, null, m_clientsSelection, errors, lookup); + +// AcmeSet maliciousClients = RuleTypeChecker.evaluateAsSet (system, null, m_maliciousSelection, errors, lookup); + boolean aboveMal = RuleTypeChecker.evaluateAsBoolean (system, null, m_aboveMal, errors, lookup); + boolean aboveRT = RuleTypeChecker.evaluateAsBoolean (system, null, m_aboveRT, errors, lookup); + float avgRT = 0.0f; + float perMal = 0.0f; + if (clients != null) { + float cum = 0.0f; + int numMal = 0; + for (Object o : clients.getValues ()) { + IAcmeProperty prop; + float mal = 0; + if (o instanceof IAcmeElementInstance) { + IAcmeElementInstance client = (IAcmeElementInstance) o; + if ((prop = client.getProperty ("experRespTime")) != null) { + cum += ((IAcmeFloatingPointValue) prop.getValue ()).getFloatValue (); + } + if ((prop = client.getProperty ("maliciousness")) != null) { + mal = ((IAcmeFloatingPointValue) prop.getValue ()).getFloatValue (); + log (MessageFormat.format ("{0}.maliciousness={1}", client, mal)); + if (mal > 0.5) { + numMal++; + } + } + } + } + avgRT = cum / clients.getValues ().size (); + perMal = ((float) numMal) / clients.getValues ().size () * 100f; + try { + SetSystemPropertiesCmd cmd = model.getCommandFactory ().setSystemProperties (system, avgRT, perMal, aboveRT, aboveMal); + m_modelUSPort.updateModel (cmd); + } catch (RainbowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + + } catch (AcmeException e) { + m_reportingPort.error (RainbowComponentT.ANALYSIS, "Failed to evaluate an expression", e); + } + + } + + + } + + } + + @Override + public RainbowComponentT getComponentType () { + return RainbowComponentT.ANALYSIS; + } + + @Override + public void setProperty (String key, String value) { + properties.put (key, value); + } + + @Override + public String getProperty (String key) { + return properties.get (key); + } + + @Override + public void dispose () { + m_modelChangePort.dispose (); + m_reportingPort.dispose (); + m_modelUSPort.dispose (); + } + + @Override + public void onEvent (ModelReference reference, IRainbowMessage message) { + IModelInstance model = m_modelsManagerPort.getModelInstance (reference); + // Add a model to check, if it doesn't already exist to be processed + synchronized (m_modelCheckQ) { + if (model instanceof ZNNModelUpdateOperatorsImpl && !m_modelCheckQ.contains (model)) { + m_modelCheckQ.offer ((ZNNModelUpdateOperatorsImpl) model); + } + } + } +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/ZNN.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/ZNN.java index 192ebe061..737cb1b01 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/ZNN.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/ZNN.java @@ -1,115 +1,115 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn; - -import java.util.HashSet; -import java.util.Set; -import java.util.Stack; - -import org.acmestudio.acme.core.resource.RegionManager; -import org.acmestudio.acme.element.IAcmeElementInstance; -import org.acmestudio.acme.element.IAcmeElementType; -import org.acmestudio.acme.environment.error.AcmeError; -import org.acmestudio.acme.rule.AcmeSet; -import org.acmestudio.acme.rule.node.IExpressionNode; -import org.acmestudio.acme.type.verification.NodeScopeLookup; -import org.acmestudio.acme.type.verification.RuleTypeChecker; -import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; - -/** - * This class provides ZNN-specific operators that can be referred to in strategies and tactics. This class can be - * imported into Stitch and the static members called from there. - * - * @author Bradley Schmerl: schmerl - * - */ -public class ZNN { - // Acme expressions for evaluating the methods - private static final String FIND_SERVICES_EXPR = "/self/components:T[!isArchEnabled]"; - private static final String AVAILABLE_SERVICES_EXPR = "size (" + FIND_SERVICES_EXPR + ")"; - // Holder objects for caching parsed Acme expressions - private static IExpressionNode s_availableServicesExpr = null; - private static IExpressionNode s_findServicesExpression; - - /** - * Returns the number services of a particular type that are available. Availability here means that they are not - * yet marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type - * - * @param model - * The model to find availabile services in - * @param elemType - * The type of service to find - * @return the number of services that are available. - * @throws Exception - */ - public static int availableServices (ZNNModelUpdateOperatorsImpl model, IAcmeElementType elemType) - throws Exception { - if (s_availableServicesExpr == null) { - s_availableServicesExpr = StandaloneLanguagePackHelper.defaultLanguageHelper () - .designRuleExpressionFromString ( - AVAILABLE_SERVICES_EXPR, new RegionManager ()); - } - - // Add "T" as a name in scope, referring to the type that we are looking for - NodeScopeLookup nameLookup = new NodeScopeLookup (); - nameLookup.put ("T", elemType); - return RuleTypeChecker.evaluateAsInt (model.getModelInstance (), null, s_availableServicesExpr, - new Stack (), - nameLookup); - - } - - /** - * Returns the services of a particular type that are available. Availability here means that they are not yet - * marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type - * - * @param model - * The model to find availabile services in - * @param type - * The type of service to find - * @return the number of services that are available. - * @throws Exception - */ - public static Set> findServices (ZNNModelUpdateOperatorsImpl model, - IAcmeElementType type) - throws Exception { - if (s_findServicesExpression == null) { - s_findServicesExpression = StandaloneLanguagePackHelper.defaultLanguageHelper () - .designRuleExpressionFromString (FIND_SERVICES_EXPR, new RegionManager ()); - } - NodeScopeLookup nameLookup = new NodeScopeLookup (); - nameLookup.put ("T", type); - AcmeSet set = RuleTypeChecker.evaluateAsSet (model.getModelInstance (), null, s_findServicesExpression, - new Stack (), - nameLookup); - - Set> retSet = new HashSet<> (); - for (Object o : set.getValues ()) { - if (o instanceof IAcmeElementInstance) { - retSet.add ((IAcmeElementInstance )o); - } - } - return retSet; - } -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn; + +import java.util.HashSet; +import java.util.Set; +import java.util.Stack; + +import org.acmestudio.acme.core.resource.RegionManager; +import org.acmestudio.acme.element.IAcmeElementInstance; +import org.acmestudio.acme.element.IAcmeElementType; +import org.acmestudio.acme.environment.error.AcmeError; +import org.acmestudio.acme.rule.AcmeSet; +import org.acmestudio.acme.rule.node.IExpressionNode; +import org.acmestudio.acme.type.verification.NodeScopeLookup; +import org.acmestudio.acme.type.verification.RuleTypeChecker; +import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; + +/** + * This class provides ZNN-specific operators that can be referred to in strategies and tactics. This class can be + * imported into Stitch and the static members called from there. + * + * @author Bradley Schmerl: schmerl + * + */ +public class ZNN { + // Acme expressions for evaluating the methods + private static final String FIND_SERVICES_EXPR = "/self/components:T[!isArchEnabled]"; + private static final String AVAILABLE_SERVICES_EXPR = "size (" + FIND_SERVICES_EXPR + ")"; + // Holder objects for caching parsed Acme expressions + private static IExpressionNode s_availableServicesExpr = null; + private static IExpressionNode s_findServicesExpression; + + /** + * Returns the number services of a particular type that are available. Availability here means that they are not + * yet marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type + * + * @param model + * The model to find availabile services in + * @param elemType + * The type of service to find + * @return the number of services that are available. + * @throws Exception + */ + public static int availableServices (ZNNModelUpdateOperatorsImpl model, IAcmeElementType elemType) + throws Exception { + if (s_availableServicesExpr == null) { + s_availableServicesExpr = StandaloneLanguagePackHelper.defaultLanguageHelper () + .designRuleExpressionFromString ( + AVAILABLE_SERVICES_EXPR, new RegionManager ()); + } + + // Add "T" as a name in scope, referring to the type that we are looking for + NodeScopeLookup nameLookup = new NodeScopeLookup (); + nameLookup.put ("T", elemType); + return RuleTypeChecker.evaluateAsInt (model.getModelInstance (), null, s_availableServicesExpr, + new Stack (), + nameLookup); + + } + + /** + * Returns the services of a particular type that are available. Availability here means that they are not yet + * marked in the architecture as available Assumes: exists property called isArchEnabled on elements of the type + * + * @param model + * The model to find availabile services in + * @param type + * The type of service to find + * @return the number of services that are available. + * @throws Exception + */ + public static Set> findServices (ZNNModelUpdateOperatorsImpl model, + IAcmeElementType type) + throws Exception { + if (s_findServicesExpression == null) { + s_findServicesExpression = StandaloneLanguagePackHelper.defaultLanguageHelper () + .designRuleExpressionFromString (FIND_SERVICES_EXPR, new RegionManager ()); + } + NodeScopeLookup nameLookup = new NodeScopeLookup (); + nameLookup.put ("T", type); + AcmeSet set = RuleTypeChecker.evaluateAsSet (model.getModelInstance (), null, s_findServicesExpression, + new Stack (), + nameLookup); + + Set> retSet = new HashSet<> (); + for (Object o : set.getValues ()) { + if (o instanceof IAcmeElementInstance) { + retSet.add ((IAcmeElementInstance )o); + } + } + return retSet; + } +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/ZNNModelUpdateOperatorsImpl.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/ZNNModelUpdateOperatorsImpl.java index 485e6ac1d..9f3962459 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/ZNNModelUpdateOperatorsImpl.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/ZNNModelUpdateOperatorsImpl.java @@ -1,59 +1,60 @@ -/* - * The MIT License - * - * Copyright 2import org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.model.acme.AcmeModelInstance; -import org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory; -oftware"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn; - -import org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.model.acme.AcmeModelInstance; -import org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory; - -/** - * An Acme model that embodies the ZNN architecture and the associated style-specific operations - * - * @author Bradley Schmerl: schmerl - * - */ -public class ZNNModelUpdateOperatorsImpl extends AcmeModelInstance { - - private ZNNCommandFactory m_commandFactory; - - public ZNNModelUpdateOperatorsImpl (IAcmeSystem system, String source) { - super (system, source); - // Make sure it is the right family - } - - @Override - public ZNNCommandFactory getCommandFactory () { - if (m_commandFactory == null) { - m_commandFactory = new ZNNCommandFactory (this); - } - return m_commandFactory; - } - - @Override - protected AcmeModelInstance generateInstance (IAcmeSystem sys) { - return new ZNNModelUpdateOperatorsImpl (sys, getOriginalSource ()); - } - - -} +/* + * The MIT License + * + * Copyright 2import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory; +oftware"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn; + +import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory; + +/** + * An Acme model that embodies the ZNN architecture and the associated style-specific operations + * + * @author Bradley Schmerl: schmerl + * + */ +public class ZNNModelUpdateOperatorsImpl extends AcmeModelInstance { + + private ZNNCommandFactory m_commandFactory; + + public ZNNModelUpdateOperatorsImpl (IAcmeSystem system, String source) { + super (system, source); + // Make sure it is the right family + } + + @Override + public ZNNCommandFactory getCommandFactory () throws RainbowException { + if (m_commandFactory == null) { + m_commandFactory = new ZNNCommandFactory (this); + } + return m_commandFactory; + } + + @Override + protected AcmeModelInstance generateInstance (IAcmeSystem sys) { + return new ZNNModelUpdateOperatorsImpl (sys, getOriginalSource ()); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/AddClientCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/AddClientCmd.java index cca6fd35f..f10c9b1d8 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/AddClientCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/AddClientCmd.java @@ -1,124 +1,129 @@ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.core.type.IAcmeStringValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.IAcmeCommandFactory; -import org.acmestudio.acme.model.command.*; -import org.acmestudio.acme.model.util.core.UMStringValue; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.*; - -/** - * Creates a new client at the IP indicated, if it doesn't already exist - * - * @author Bradley Schmerl: schmerl - * - */ -public class AddClientCmd extends ZNNAcmeModelCommand { - - private static final List HTTP_PORT = Collections.singletonList ("HttpPortT"); - private static final List HTTP_CONN = Collections.singletonList ("HttpConnT"); - private static final List HTTP_REQ_PORT = Collections.singletonList ("HttpReqPortT"); - private static final List CLIENT_COMP = Collections.singletonList ("ZNewsClientT"); - - private IAcmeComponent m_client; - private String m_lb; - private String m_clientIP; - private IAcmeComponentCreateCommand m_clientCmd; - - /** - * @param model - * The model in which the new client may be created - * @param lb - * The load balancer that the client will be attached to - * @param clientIP - */ - public AddClientCmd (AcmeModelInstance model, String sys, String lb, String clientIP) { - super ("addClient", model, sys, lb, clientIP); - m_lb = lb; - m_clientIP = clientIP; - } - - @Override - public IAcmeComponent getResult () throws IllegalStateException { - return m_clientCmd != null ? m_clientCmd.getComponent () : m_client; - } - - /** - * Executes a list of commands with the following operations - * - *

-     * {@code
-     *   ClientT client = /self/components:!ClientT[deploymentLocation==clientIP]/next;
-     *   if (client == null) {
-     *     client = new ClientT();
-     *     http = new HttpReqPortT() in client;
-     *     httpConn = new HttpConnT ();
-     *     http = new HttpPortT() in lb;
-     *     client.deploymentLocation = clientIP;
-     *     attach client.http to httpConn.req;
-     *     attach lb.http to httpConn.rec;
-     *   }
-     * }
-     * 
- */ - - @Override - protected List> doConstructCommand () throws RainbowModelException { - Set components = getModel ().getComponents (); - IAcmeComponent client = null; - for (Iterator i = components.iterator (); i.hasNext () && client == null;) { - IAcmeComponent comp = (IAcmeComponent )i.next (); - if (comp.declaresType ("ClientT")) { - IAcmeProperty prop = comp.getProperty ("deploymentLocation"); - if (prop != null && prop.getValue () instanceof IAcmeStringValue) { - IAcmeStringValue dl = (IAcmeStringValue )prop.getValue (); - if (dl.getValue ().equals (m_clientIP)) { - client = comp; - } - - } - } - } - m_client = client; - if (m_client == null) { - IAcmeCommandFactory cf = getModel ().getCommandFactory (); - String clientName = ModelHelper.getUniqueName (getModel (), "Client"); - m_clientCmd = cf.componentCreateCommand (getModel (), clientName, CLIENT_COMP, CLIENT_COMP); - IAcmePortCreateCommand httpCmd = cf.portCreateCommand (m_clientCmd, "http", HTTP_PORT, HTTP_PORT); - String connName = ModelHelper.getUniqueName (getModel (), "httpConn"); - IAcmeConnectorCreateCommand httpConnCmd = cf.connectorCreateCommand (getModel (), connName, HTTP_CONN, - HTTP_CONN); - IAcmeComponent lb = getModelContext ().resolveInModel (m_lb, IAcmeComponent.class); - if (lb == null) throw new RainbowModelException ( - MessageFormat.format ("Could not find the load balancer ''{0}''.", m_lb)); - String httpPortName = ModelHelper.getUniqueName (lb, "http"); - IAcmePortCreateCommand lbPortCmd = cf.portCreateCommand (lb, httpPortName, HTTP_PORT, HTTP_PORT); - IAcmePropertyCreateCommand dlCmd = cf.propertyCreateCommand (m_clientCmd, "deploymentLocation", "String", - new UMStringValue (m_clientIP)); - IAcmeAttachmentCommand att1Cmd = cf.attachmentCreateCommand (getModel (), clientName + ".http", - connName + ".req"); - IAcmeAttachmentCommand att2Cmd = cf.attachmentCreateCommand (getModel (), m_lb + "." + httpPortName, - connName + ".rec"); - List> cmds = new LinkedList<> (); - cmds.add (m_clientCmd); - cmds.add (httpCmd); - cmds.add (httpConnCmd); - cmds.add (lbPortCmd); - cmds.add (dlCmd); - cmds.add (att1Cmd); - cmds.add (att2Cmd); - - return cmds; - - } - else - return Collections.emptyList (); - } - -} +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.core.type.IAcmeStringValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.IAcmeCommandFactory; +import org.acmestudio.acme.model.command.*; +import org.acmestudio.acme.model.util.core.UMStringValue; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.*; + +/** + * Creates a new client at the IP indicated, if it doesn't already exist + * + * @author Bradley Schmerl: schmerl + * + */ +public class AddClientCmd extends ZNNAcmeModelCommand { + + private static final List HTTP_PORT = Collections.singletonList ("HttpPortT"); + private static final List HTTP_CONN = Collections.singletonList ("HttpConnT"); + private static final List HTTP_REQ_PORT = Collections.singletonList ("HttpReqPortT"); + private static final List CLIENT_COMP = Collections.singletonList ("ZNewsClientT"); + + private IAcmeComponent m_client; + private String m_lb; + private String m_clientIP; + private IAcmeComponentCreateCommand m_clientCmd; + + /** + * @param model + * The model in which the new client may be created + * @param lb + * The load balancer that the client will be attached to + * @param clientIP + */ + public AddClientCmd (String c, AcmeModelInstance model, String sys, String lb, String clientIP) { + super (c, model, sys, lb, clientIP); + m_lb = lb; + m_clientIP = clientIP; + } + + public AddClientCmd(AcmeModelInstance model, IAcmeSystem sys, IAcmeComponent lb, String clientIP) { + this(model, sys.getQualifiedName(), lb.getQualifiedName(), clientIP); + } + + @Override + public IAcmeComponent getResult () throws IllegalStateException { + return m_clientCmd != null ? m_clientCmd.getComponent () : m_client; + } + + /** + * Executes a list of commands with the following operations + * + *
+     * {@code
+     *   ClientT client = /self/components:!ClientT[deploymentLocation==clientIP]/next;
+     *   if (client == null) {
+     *     client = new ClientT();
+     *     http = new HttpReqPortT() in client;
+     *     httpConn = new HttpConnT ();
+     *     http = new HttpPortT() in lb;
+     *     client.deploymentLocation = clientIP;
+     *     attach client.http to httpConn.req;
+     *     attach lb.http to httpConn.rec;
+     *   }
+     * }
+     * 
+ */ + + @Override + protected List> doConstructCommand () throws RainbowModelException { + Set components = getModel ().getComponents (); + IAcmeComponent client = null; + for (Iterator i = components.iterator (); i.hasNext () && client == null;) { + IAcmeComponent comp = (IAcmeComponent )i.next (); + if (comp.declaresType ("ClientT")) { + IAcmeProperty prop = comp.getProperty ("deploymentLocation"); + if (prop != null && prop.getValue () instanceof IAcmeStringValue) { + IAcmeStringValue dl = (IAcmeStringValue )prop.getValue (); + if (dl.getValue ().equals (m_clientIP)) { + client = comp; + } + + } + } + } + m_client = client; + if (m_client == null) { + IAcmeCommandFactory cf = getModel ().getCommandFactory (); + String clientName = ModelHelper.getUniqueName (getModel (), "Client"); + m_clientCmd = cf.componentCreateCommand (getModel (), clientName, CLIENT_COMP, CLIENT_COMP); + IAcmePortCreateCommand httpCmd = cf.portCreateCommand (m_clientCmd, "http", HTTP_PORT, HTTP_PORT); + String connName = ModelHelper.getUniqueName (getModel (), "httpConn"); + IAcmeConnectorCreateCommand httpConnCmd = cf.connectorCreateCommand (getModel (), connName, HTTP_CONN, + HTTP_CONN); + IAcmeComponent lb = getModelContext ().resolveInModel (m_lb, IAcmeComponent.class); + if (lb == null) throw new RainbowModelException ( + MessageFormat.format ("Could not find the load balancer ''{0}''.", m_lb)); + String httpPortName = ModelHelper.getUniqueName (lb, "http"); + IAcmePortCreateCommand lbPortCmd = cf.portCreateCommand (lb, httpPortName, HTTP_PORT, HTTP_PORT); + IAcmePropertyCreateCommand dlCmd = cf.propertyCreateCommand (m_clientCmd, "deploymentLocation", "String", + new UMStringValue (m_clientIP)); + IAcmeAttachmentCommand att1Cmd = cf.attachmentCreateCommand (getModel (), clientName + ".http", + connName + ".req"); + IAcmeAttachmentCommand att2Cmd = cf.attachmentCreateCommand (getModel (), m_lb + "." + httpPortName, + connName + ".rec"); + List> cmds = new LinkedList<> (); + cmds.add (m_clientCmd); + cmds.add (httpCmd); + cmds.add (httpConnCmd); + cmds.add (lbPortCmd); + cmds.add (dlCmd); + cmds.add (att1Cmd); + cmds.add (att2Cmd); + + return cmds; + + } + else + return Collections.emptyList (); + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ConnectServerCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ConnectServerCmd.java index 1f69c5362..5561699d2 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ConnectServerCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ConnectServerCmd.java @@ -1,159 +1,159 @@ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.core.exception.AcmeException; -import org.acmestudio.acme.core.resource.RegionManager; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.IAcmePort; -import org.acmestudio.acme.environment.error.AcmeError; -import org.acmestudio.acme.model.IAcmeCommandFactory; -import org.acmestudio.acme.model.command.*; -import org.acmestudio.acme.model.util.core.UMStringValue; -import org.acmestudio.acme.rule.AcmeSet; -import org.acmestudio.acme.rule.node.IExpressionNode; -import org.acmestudio.acme.type.verification.NodeScopeLookup; -import org.acmestudio.acme.type.verification.RuleTypeChecker; -import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.Stack; - -/** - * Created by schmerl on 2/4/2016. - */ -public class ConnectServerCmd extends ZNNAcmeModelCommand { - - private final String m_lb; - private final String m_port; - private final String m_host; - private final String m_name; - - private static final String DISCONNECTED_QUERY = "/self/components:!ServerT[!isArchEnabled and " + - "deploymentLocation==\"\"]"; - private static IExpressionNode s_DisconnectedQueryExpr; - - private IAcmeComponent m_server; - - public ConnectServerCmd (AcmeModelInstance model, String lb, String name, String host, String - port) { - super ("connectServer", model, lb, name, host, port); - m_lb = lb; - m_name = name; - m_host = host; - m_port = port; - - - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - - - List> cmds = new LinkedList<> (); - - IAcmeComponent lb = getModelContext ().resolveInModel (m_lb, IAcmeComponent.class); - - IAcmeCommandFactory cf = getModel ().getCommandFactory (); - - // If "name" is an unconnected and disabled server in the model, use it. - // If not, find a disconnected server and attach it - IAcmeComponent srv = getModelContext ().getModelInstance ().getComponent (m_name); - - if (srv != null) { - if (isConnected (srv)) { - srv = null; - } - } - if (srv == null) { - // Find an unenabled server - if (s_DisconnectedQueryExpr == null) { - try { - s_DisconnectedQueryExpr = StandaloneLanguagePackHelper.defaultLanguageHelper () - .designRuleExpressionFromString (DISCONNECTED_QUERY, new RegionManager ()); - } catch (Exception e) { - throw new RainbowModelException (String.format ("Could not construct the query expression '%s'", - DISCONNECTED_QUERY)); - } - } - Stack errorStack = new Stack (); - try { - Object result = RuleTypeChecker.evaluateAsAny (getModel (), null, s_DisconnectedQueryExpr, - errorStack, new - NodeScopeLookup ()); - if (errorStack.isEmpty () && result instanceof AcmeSet) { - AcmeSet set = ((AcmeSet) result); - if (!set.getValues ().isEmpty ()) { - final Object first = set.getValues ().iterator ().next (); - if (first instanceof IAcmeComponent) - srv = (IAcmeComponent) first; - } - - } - } catch (AcmeException e) { - throw new RainbowModelException (e); - } - } - - - if (srv != null) { - m_server = srv; - final IAcmePortCreateCommand httpCreateCommand = cf.portCreateCommand (srv, "http", ZNNConstants - .HTTP_PORT, - ZNNConstants.HTTP_PORT); - String lbName = ModelHelper.getUniqueName (getModel (), "proxyconn"); - // Connector proxyconn : ProxyConnT = new ProxyConnT; - final IAcmeConnectorCreateCommand proxyConnCreateCmd = cf.connectorCreateCommand (getModel (), lbName, - ZNNConstants - .HTTP_CONN_T, - ZNNConstants.HTTP_CONN_T); - String fwd = ModelHelper.getUniqueName (lb, "fwd"); - // m_lb = m_lb extended with { - // port fwd : ProxyForwardPortT = new ProxyForwardPortT; - // } - final IAcmePortCreateCommand lbPortCmd = cf.portCreateCommand (lb, fwd, ZNNConstants.PROXY_FORWARD_PORT, - ZNNConstants.PROXY_FORWARD_PORT); - // attachment m_lb.fwd to proxyconn.req; - final IAcmeAttachmentCommand attachLBEnd = cf.attachmentCreateCommand (getModel (), - lb.getName () + "." + fwd, - lbName + ".req"); - // attachment .http to proxyconn.rec; - final IAcmeAttachmentCommand attachServerEnd = cf.attachmentCreateCommand (getModel (), m_name + ".http", - lbName + ".rec"); - - final IAcmePropertyCommand setLocation = cf.propertyCreateCommand (srv, "deploymentLocation", - "String", - new UMStringValue (m_host)); - final IAcmePropertyCreateCommand setPort = cf.propertyCreateCommand (srv, "httpPort", "String", - new UMStringValue (m_port)); - - cmds.add (proxyConnCreateCmd); - cmds.add (lbPortCmd); - cmds.add (attachLBEnd); - cmds.add (attachServerEnd); - cmds.add (setLocation); - cmds.add (setPort); - - return cmds; - } - throw new RainbowModelException ("There is no server that can be connected"); - } - - private boolean isConnected (IAcmeComponent srv) { - final Set ports = srv.getPorts (); - if (ports.isEmpty ()) return false; - for (IAcmePort port : ports) { - if (!ModelHelper.getAcmeSystem (srv).getAttachments (port).isEmpty ()) - return true; - } - return false; - } - - @Override - public IAcmeComponent getResult () throws IllegalStateException { - return m_server; - } -} +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.core.exception.AcmeException; +import org.acmestudio.acme.core.resource.RegionManager; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.IAcmePort; +import org.acmestudio.acme.environment.error.AcmeError; +import org.acmestudio.acme.model.IAcmeCommandFactory; +import org.acmestudio.acme.model.command.*; +import org.acmestudio.acme.model.util.core.UMStringValue; +import org.acmestudio.acme.rule.AcmeSet; +import org.acmestudio.acme.rule.node.IExpressionNode; +import org.acmestudio.acme.type.verification.NodeScopeLookup; +import org.acmestudio.acme.type.verification.RuleTypeChecker; +import org.acmestudio.standalone.resource.StandaloneLanguagePackHelper; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.Stack; + +/** + * Created by schmerl on 2/4/2016. + */ +public class ConnectServerCmd extends ZNNAcmeModelCommand { + + private final String m_lb; + private final String m_port; + private final String m_host; + private final String m_name; + + private static final String DISCONNECTED_QUERY = "/self/components:!ServerT[!isArchEnabled and " + + "deploymentLocation==\"\"]"; + private static IExpressionNode s_DisconnectedQueryExpr; + + private IAcmeComponent m_server; + + public ConnectServerCmd (String c, AcmeModelInstance model, String lb, String name, String host, String + port) { + super (c, model, lb, name, host, port); + m_lb = lb; + m_name = name; + m_host = host; + m_port = port; + + + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + + + List> cmds = new LinkedList<> (); + + IAcmeComponent lb = getModelContext ().resolveInModel (m_lb, IAcmeComponent.class); + + IAcmeCommandFactory cf = getModel ().getCommandFactory (); + + // If "name" is an unconnected and disabled server in the model, use it. + // If not, find a disconnected server and attach it + IAcmeComponent srv = getModelContext ().getModelInstance ().getComponent (m_name); + + if (srv != null) { + if (isConnected (srv)) { + srv = null; + } + } + if (srv == null) { + // Find an unenabled server + if (s_DisconnectedQueryExpr == null) { + try { + s_DisconnectedQueryExpr = StandaloneLanguagePackHelper.defaultLanguageHelper () + .designRuleExpressionFromString (DISCONNECTED_QUERY, new RegionManager ()); + } catch (Exception e) { + throw new RainbowModelException (String.format ("Could not construct the query expression '%s'", + DISCONNECTED_QUERY)); + } + } + Stack errorStack = new Stack (); + try { + Object result = RuleTypeChecker.evaluateAsAny (getModel (), null, s_DisconnectedQueryExpr, + errorStack, new + NodeScopeLookup ()); + if (errorStack.isEmpty () && result instanceof AcmeSet) { + AcmeSet set = ((AcmeSet) result); + if (!set.getValues ().isEmpty ()) { + final Object first = set.getValues ().iterator ().next (); + if (first instanceof IAcmeComponent) + srv = (IAcmeComponent) first; + } + + } + } catch (AcmeException e) { + throw new RainbowModelException (e); + } + } + + + if (srv != null) { + m_server = srv; + final IAcmePortCreateCommand httpCreateCommand = cf.portCreateCommand (srv, "http", ZNNConstants + .HTTP_PORT, + ZNNConstants.HTTP_PORT); + String lbName = ModelHelper.getUniqueName (getModel (), "proxyconn"); + // Connector proxyconn : ProxyConnT = new ProxyConnT; + final IAcmeConnectorCreateCommand proxyConnCreateCmd = cf.connectorCreateCommand (getModel (), lbName, + ZNNConstants + .HTTP_CONN_T, + ZNNConstants.HTTP_CONN_T); + String fwd = ModelHelper.getUniqueName (lb, "fwd"); + // m_lb = m_lb extended with { + // port fwd : ProxyForwardPortT = new ProxyForwardPortT; + // } + final IAcmePortCreateCommand lbPortCmd = cf.portCreateCommand (lb, fwd, ZNNConstants.PROXY_FORWARD_PORT, + ZNNConstants.PROXY_FORWARD_PORT); + // attachment m_lb.fwd to proxyconn.req; + final IAcmeAttachmentCommand attachLBEnd = cf.attachmentCreateCommand (getModel (), + lb.getName () + "." + fwd, + lbName + ".req"); + // attachment .http to proxyconn.rec; + final IAcmeAttachmentCommand attachServerEnd = cf.attachmentCreateCommand (getModel (), m_name + ".http", + lbName + ".rec"); + + final IAcmePropertyCommand setLocation = cf.propertyCreateCommand (srv, "deploymentLocation", + "String", + new UMStringValue (m_host)); + final IAcmePropertyCreateCommand setPort = cf.propertyCreateCommand (srv, "httpPort", "String", + new UMStringValue (m_port)); + + cmds.add (proxyConnCreateCmd); + cmds.add (lbPortCmd); + cmds.add (attachLBEnd); + cmds.add (attachServerEnd); + cmds.add (setLocation); + cmds.add (setPort); + + return cmds; + } + throw new RainbowModelException ("There is no server that can be connected"); + } + + private boolean isConnected (IAcmeComponent srv) { + final Set ports = srv.getPorts (); + if (ports.isEmpty ()) return false; + for (IAcmePort port : ports) { + if (!ModelHelper.getAcmeSystem (srv).getAttachments (port).isEmpty ()) + return true; + } + return false; + } + + @Override + public IAcmeComponent getResult () throws IllegalStateException { + return m_server; + } +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/CreateDisconnectedServerCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/CreateDisconnectedServerCmd.java index 0ae7e01bb..11e4d8328 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/CreateDisconnectedServerCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/CreateDisconnectedServerCmd.java @@ -1,38 +1,38 @@ -package org.sa.rainbow.model.acme.znn.commands; - -import edu.emory.mathcs.backport.java.util.Collections; -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmeComponentCreateCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.List; - -/** - * Created by schmerl on 2/4/2016. - */ -public class CreateDisconnectedServerCmd extends ZNNAcmeModelCommand { - private String m_newName; - private IAcmeComponentCreateCommand m_cmd; - - public CreateDisconnectedServerCmd (AcmeModelInstance model, String system, String newName) { - super ("createDisconnectedServer", model, system, newName); - m_newName = newName; - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - m_newName = ModelHelper.getUniqueName (getModel (), m_newName); - m_cmd = getModel ().getCommandFactory () - .componentCreateCommand (getModel (), m_newName, ZNNConstants.SERVER_TYPE, - ZNNConstants.SERVER_TYPE); - return Collections.singletonList (m_cmd); - } - - @Override - public IAcmeComponent getResult () throws IllegalStateException { - return m_cmd.getComponent (); - } -} +package org.sa.rainbow.model.acme.znn.commands; + +import edu.emory.mathcs.backport.java.util.Collections; +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmeComponentCreateCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.List; + +/** + * Created by schmerl on 2/4/2016. + */ +public class CreateDisconnectedServerCmd extends ZNNAcmeModelCommand { + private String m_newName; + private IAcmeComponentCreateCommand m_cmd; + + public CreateDisconnectedServerCmd (String c, AcmeModelInstance model, String system, String newName) { + super (c, model, system, newName); + m_newName = newName; + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + m_newName = ModelHelper.getUniqueName (getModel (), m_newName); + m_cmd = getModel ().getCommandFactory () + .componentCreateCommand (getModel (), m_newName, ZNNConstants.SERVER_TYPE, + ZNNConstants.SERVER_TYPE); + return Collections.singletonList (m_cmd); + } + + @Override + public IAcmeComponent getResult () throws IllegalStateException { + return m_cmd.getComponent (); + } +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/EnableServerCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/EnableServerCmd.java index 32a9f2025..aad3091fb 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/EnableServerCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/EnableServerCmd.java @@ -1,98 +1,98 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -/** - * A class representing the Acme command to enable a server in Znn. Currently, this is modeled by setting the property - * "isArchEnabled" on the model. - * - * @author Bradley Schmerl: schmerl - * - */ -public class EnableServerCmd extends ZNNAcmeModelCommand { - - // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" - public EnableServerCmd (AcmeModelInstance model, String target, String enable) { - super ("enableServer", model, target, enable); - } - - /** - * Constructs the list of commands for enabling the server by setting the isArchEnabled property - * - * @return the list of commands - * @throws RainbowModelException - * when the server cannot be found, is of the incorrect type, or the argument is malformed. - */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - List> cmds = new LinkedList<> (); - IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", getTarget ())); - if (!server.declaresType ("ArchElementT")) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' is not of the right type. It does not have a property ''isArchEnabled''", - getTarget ())); - IAcmeProperty property = server.getProperty ("isArchEnabled"); - try { - IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Boolean.valueOf (getParameters ()[0])); - if (propertyValueChanging (property, acmeVal)) { - m_command = property.getCommandFactory ().propertyValueSetCommand (property, - acmeVal); - cmds.add (m_command); - } - } - catch (IllegalArgumentException e) { - throw new RainbowModelException (e.getMessage (), e); - } - return cmds; - - } - - - /** - * - * @return the property after the command has been executed - * @throws IllegalStateException - */ - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * A class representing the Acme command to enable a server in Znn. Currently, this is modeled by setting the property + * "isArchEnabled" on the model. + * + * @author Bradley Schmerl: schmerl + * + */ +public class EnableServerCmd extends ZNNAcmeModelCommand { + + // Target is the server to enable, enable is whether to set it as enabled or not "true" or "false" + public EnableServerCmd (String c, AcmeModelInstance model, String target, String enable) { + super (c, model, target, enable); + } + + /** + * Constructs the list of commands for enabling the server by setting the isArchEnabled property + * + * @return the list of commands + * @throws RainbowModelException + * when the server cannot be found, is of the incorrect type, or the argument is malformed. + */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + List> cmds = new LinkedList<> (); + IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + if (!server.declaresType ("ArchElementT")) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''isArchEnabled''", + getTarget ())); + IAcmeProperty property = server.getProperty ("isArchEnabled"); + try { + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Boolean.valueOf (getParameters ()[0])); + if (propertyValueChanging (property, acmeVal)) { + m_command = property.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + } + catch (IllegalArgumentException e) { + throw new RainbowModelException (e.getMessage (), e); + } + return cmds; + + } + + + /** + * + * @return the property after the command has been executed + * @throws IllegalStateException + */ + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ForceReauthenticationCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ForceReauthenticationCmd.java index 474891180..1bbcb15fe 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ForceReauthenticationCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ForceReauthenticationCmd.java @@ -1,50 +1,50 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.Collections; -import java.util.List; - -public class ForceReauthenticationCmd extends ZNNAcmeModelCommand { - - public ForceReauthenticationCmd (AcmeModelInstance model, String target) { - super ("forceReauthentication", model, target); - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return null; - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - return Collections.emptyList (); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.Collections; +import java.util.List; + +public class ForceReauthenticationCmd extends ZNNAcmeModelCommand { + + public ForceReauthenticationCmd (String c, AcmeModelInstance model, String target) { + super (c, model, target); + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return null; + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + return Collections.emptyList (); + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/NewServerCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/NewServerCmd.java index 7b35159c7..77b323a41 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/NewServerCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/NewServerCmd.java @@ -1,158 +1,158 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.model.IAcmeCommandFactory; -import org.acmestudio.acme.model.command.*; -import org.acmestudio.acme.model.util.core.UMStringValue; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -/** - * Creates a new server in Znn and attaches it to the indicated load balancer - * - * @author Bradley Schmerl: schmerl - * - */ -public class NewServerCmd extends ZNNAcmeModelCommand { - - private String m_name; - public String m_lb; - - private IAcmeComponentCreateCommand m_serverCommand; - - private String m_host; - - private String m_port; - - /** - * - * @param commandName - * The name for the command - * @param model - * The model in which the new server will be created - * @param lb - * The name of the load balancer to which the server will be attached - * @param name - * The name to give the new server - * @param host - * The host on which the server is running - * @param port - * The port on which the server will accept HTTP requests - */ - public NewServerCmd (AcmeModelInstance model, String lb, String name, String host, String port) { - super ("connectNewServer", model, lb, name, host, port); - m_lb = lb; - m_name = name; - m_host = host; - m_port = port; - } - - - /** - * Executes the list of commands to execute the following operations - * - *
-     * {@code
-     *   ServerT name = new ServerT ();
-     *   HttpTPortT http = new HttpPortT () in name;
-     *   ProxyConnT proxyconn = new ProxyConnT ();
-     *   ProxyForwardPortT fwd = new ProxyForwardPortT () in lb;
-     *   attach lb.fwd to proxyconn.req;
-     *   attach http to proxyconn.rec; // maybe name.http?
-     *   name.deploymentLocation = host;
-     *   name.httpPort = port;
-     * }
-     * 
- */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - - IAcmeComponent lb = getModelContext ().resolveInModel (m_lb, IAcmeComponent.class); - - IAcmeCommandFactory cf = getModel ().getCommandFactory (); - // Component = new ServerT extended with { - m_name = ModelHelper.getUniqueName (getModel (), m_name); - m_serverCommand = cf.componentCreateCommand (getModel (), m_name, - ZNNConstants.SERVER_TYPE, ZNNConstants.SERVER_TYPE); - // port http : HttpPortT = new HttpPortT; - // } - final IAcmePortCreateCommand httpCreateCommand = cf.portCreateCommand (m_serverCommand, "http", ZNNConstants - .HTTP_PORT, - ZNNConstants.HTTP_PORT); - String lbName = ModelHelper.getUniqueName (getModel (), "proxyconn"); - // Connector proxyconn : ProxyConnT = new ProxyConnT; - final IAcmeConnectorCreateCommand proxyConnCreateCmd = cf.connectorCreateCommand (getModel (), lbName, - ZNNConstants.HTTP_CONN_T, - ZNNConstants.HTTP_CONN_T); - String fwd = ModelHelper.getUniqueName (lb, "fwd"); - // m_lb = m_lb extended with { - // port fwd : ProxyForwardPortT = new ProxyForwardPortT; - // } - final IAcmePortCreateCommand lbPortCmd = cf.portCreateCommand (lb, fwd, ZNNConstants.PROXY_FORWARD_PORT, - ZNNConstants.PROXY_FORWARD_PORT); - // attachment m_lb.fwd to proxyconn.req; - final IAcmeAttachmentCommand attachLBEnd = cf.attachmentCreateCommand (getModel (), - lb.getName () + "." + fwd, - lbName + ".req"); - // attachment .http to proxyconn.rec; - final IAcmeAttachmentCommand attachServerEnd = cf.attachmentCreateCommand (getModel (), m_name + ".http", - lbName + ".rec"); - - final IAcmePropertyCommand setLocation = cf.propertyCreateCommand (m_serverCommand, "deploymentLocation", - "String", - new UMStringValue (m_host)); - final IAcmePropertyCreateCommand setPort = cf.propertyCreateCommand (m_serverCommand, "httpPort", "String", - new UMStringValue (m_port)); - List> cmds = new LinkedList<> (); - cmds.add (m_serverCommand); - cmds.add (httpCreateCommand); - cmds.add (proxyConnCreateCmd); - cmds.add (lbPortCmd); - cmds.add (attachLBEnd); - cmds.add (attachServerEnd); - cmds.add (setLocation); - cmds.add (setPort); - - return cmds; - } - - - @Override - public IAcmeComponent getResult () { - return m_serverCommand.getComponent (); - } - - @Override - public String getName () { - return "newServer"; - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.model.IAcmeCommandFactory; +import org.acmestudio.acme.model.command.*; +import org.acmestudio.acme.model.util.core.UMStringValue; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +/** + * Creates a new server in Znn and attaches it to the indicated load balancer + * + * @author Bradley Schmerl: schmerl + * + */ +public class NewServerCmd extends ZNNAcmeModelCommand { + + private String m_name; + public String m_lb; + + private IAcmeComponentCreateCommand m_serverCommand; + + private String m_host; + + private String m_port; + + /** + * + * @param commandName + * The name for the command + * @param model + * The model in which the new server will be created + * @param lb + * The name of the load balancer to which the server will be attached + * @param name + * The name to give the new server + * @param host + * The host on which the server is running + * @param port + * The port on which the server will accept HTTP requests + */ + public NewServerCmd (String c, AcmeModelInstance model, String lb, String name, String host, String port) { + super (c, model, lb, name, host, port); + m_lb = lb; + m_name = name; + m_host = host; + m_port = port; + } + + + /** + * Executes the list of commands to execute the following operations + * + *
+     * {@code
+     *   ServerT name = new ServerT ();
+     *   HttpTPortT http = new HttpPortT () in name;
+     *   ProxyConnT proxyconn = new ProxyConnT ();
+     *   ProxyForwardPortT fwd = new ProxyForwardPortT () in lb;
+     *   attach lb.fwd to proxyconn.req;
+     *   attach http to proxyconn.rec; // maybe name.http?
+     *   name.deploymentLocation = host;
+     *   name.httpPort = port;
+     * }
+     * 
+ */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + + IAcmeComponent lb = getModelContext ().resolveInModel (m_lb, IAcmeComponent.class); + + IAcmeCommandFactory cf = getModel ().getCommandFactory (); + // Component = new ServerT extended with { + m_name = ModelHelper.getUniqueName (getModel (), m_name); + m_serverCommand = cf.componentCreateCommand (getModel (), m_name, + ZNNConstants.SERVER_TYPE, ZNNConstants.SERVER_TYPE); + // port http : HttpPortT = new HttpPortT; + // } + final IAcmePortCreateCommand httpCreateCommand = cf.portCreateCommand (m_serverCommand, "http", ZNNConstants + .HTTP_PORT, + ZNNConstants.HTTP_PORT); + String lbName = ModelHelper.getUniqueName (getModel (), "proxyconn"); + // Connector proxyconn : ProxyConnT = new ProxyConnT; + final IAcmeConnectorCreateCommand proxyConnCreateCmd = cf.connectorCreateCommand (getModel (), lbName, + ZNNConstants.HTTP_CONN_T, + ZNNConstants.HTTP_CONN_T); + String fwd = ModelHelper.getUniqueName (lb, "fwd"); + // m_lb = m_lb extended with { + // port fwd : ProxyForwardPortT = new ProxyForwardPortT; + // } + final IAcmePortCreateCommand lbPortCmd = cf.portCreateCommand (lb, fwd, ZNNConstants.PROXY_FORWARD_PORT, + ZNNConstants.PROXY_FORWARD_PORT); + // attachment m_lb.fwd to proxyconn.req; + final IAcmeAttachmentCommand attachLBEnd = cf.attachmentCreateCommand (getModel (), + lb.getName () + "." + fwd, + lbName + ".req"); + // attachment .http to proxyconn.rec; + final IAcmeAttachmentCommand attachServerEnd = cf.attachmentCreateCommand (getModel (), m_name + ".http", + lbName + ".rec"); + + final IAcmePropertyCommand setLocation = cf.propertyCreateCommand (m_serverCommand, "deploymentLocation", + "String", + new UMStringValue (m_host)); + final IAcmePropertyCreateCommand setPort = cf.propertyCreateCommand (m_serverCommand, "httpPort", "String", + new UMStringValue (m_port)); + List> cmds = new LinkedList<> (); + cmds.add (m_serverCommand); + cmds.add (httpCreateCommand); + cmds.add (proxyConnCreateCmd); + cmds.add (lbPortCmd); + cmds.add (attachLBEnd); + cmds.add (attachServerEnd); + cmds.add (setLocation); + cmds.add (setPort); + + return cmds; + } + + + @Override + public IAcmeComponent getResult () { + return m_serverCommand.getComponent (); + } + + @Override + public String getName () { + return "newServer"; + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/RemoveClientCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/RemoveClientCmd.java index 73e4b2f9e..2c400dad4 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/RemoveClientCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/RemoveClientCmd.java @@ -1,92 +1,92 @@ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.element.*; -import org.acmestudio.acme.model.IAcmeCommandFactory; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmeComponentDeleteCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class RemoveClientCmd extends ZNNAcmeModelCommand { - - private IAcmeComponentDeleteCommand m_deleteClientCmd; - - public RemoveClientCmd (AcmeModelInstance model, String sys, String client) { - super ("deleteClient", model, sys, client); - } - - @Override - public IAcmeComponent getResult () throws IllegalStateException { - return m_deleteClientCmd.getComponent (); - } - - @Override - /** - *
-     * {@code
-     *  set{role} roles = client/ports/attachedRoles;
-     *  set{connector} attachedConnectors = select c in connectors | exists r in c.roles | contains (roles, r);
-     *  set{connector} binaryConnectors = select c in attachedConnectors | size (r.roles) <= 2;
-     *  set{connector} otherConnectors = select c in attachedConnectors | size (r.roles) > 2;
-     *  set{port} portsToRemove = binaryConnectors/roles/attachedPorts;
-     *  set{role} rolesToRemove = otherConnectors/r:roles[connected(r, server)]
-     *  foreach p in portsToRemove {
-     *     delete p;
-     *  }
-     *  foreach r in rolesToRemove {
-     *    remove r;
-     *  }
-     *  foreach c in binaryConnectors {
-     *    delete c;
-     *  }
-     *  delete client;
-     * }
-     * 
- */ - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent client = getModelContext ().resolveInModel (getParameters ()[0], IAcmeComponent.class); - IAcmeCommandFactory cf = getModel ().getCommandFactory (); - if (client == null) throw new RainbowModelException ("Cannot delete unknown server " + getTarget ()); - IAcmeSystem system = ModelHelper.getAcmeSystem (client); - List connectorsToRemove = new LinkedList<> (); - List rolesToRemove = new LinkedList<> (); - List portsToRemove = new LinkedList<> (); - for (IAcmePort port : client.getPorts ()) { - for (IAcmeAttachment att : system.getAttachments (port)) { - IAcmeConnector conn = (IAcmeConnector )att.getRole ().getParent (); - if (conn.getRoles ().size () <= 2) { - connectorsToRemove.add (conn); - for (IAcmeRole role : conn.getRoles ()) { - if (role == att.getRole ()) { - continue; - } - for (IAcmeAttachment att2 : system.getAttachments (role)) { - portsToRemove.add (att2.getPort ()); - } - } - } - else { - rolesToRemove.add (att.getRole ()); - } - } - } - List> cmds = new LinkedList<> (); - for (IAcmeConnector conn : connectorsToRemove) { - cmds.add (system.getCommandFactory ().connectorDeleteCommand (conn)); - } - for (IAcmeRole role : rolesToRemove) { - cmds.add (system.getCommandFactory ().roleDeleteCommand (role)); - } - for (IAcmePort port : portsToRemove) { - cmds.add (system.getCommandFactory ().portDeleteCommand (port)); - } - m_deleteClientCmd = system.getCommandFactory ().componentDeleteCommand (client); - cmds.add (m_deleteClientCmd); - return cmds; - } - -} +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.element.*; +import org.acmestudio.acme.model.IAcmeCommandFactory; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmeComponentDeleteCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class RemoveClientCmd extends ZNNAcmeModelCommand { + + private IAcmeComponentDeleteCommand m_deleteClientCmd; + + public RemoveClientCmd (String c, AcmeModelInstance model, String sys, String client) { + super (c, model, sys, client); + } + + @Override + public IAcmeComponent getResult () throws IllegalStateException { + return m_deleteClientCmd.getComponent (); + } + + @Override + /** + *
+     * {@code
+     *  set{role} roles = client/ports/attachedRoles;
+     *  set{connector} attachedConnectors = select c in connectors | exists r in c.roles | contains (roles, r);
+     *  set{connector} binaryConnectors = select c in attachedConnectors | size (r.roles) <= 2;
+     *  set{connector} otherConnectors = select c in attachedConnectors | size (r.roles) > 2;
+     *  set{port} portsToRemove = binaryConnectors/roles/attachedPorts;
+     *  set{role} rolesToRemove = otherConnectors/r:roles[connected(r, server)]
+     *  foreach p in portsToRemove {
+     *     delete p;
+     *  }
+     *  foreach r in rolesToRemove {
+     *    remove r;
+     *  }
+     *  foreach c in binaryConnectors {
+     *    delete c;
+     *  }
+     *  delete client;
+     * }
+     * 
+ */ + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent client = getModelContext ().resolveInModel (getParameters ()[0], IAcmeComponent.class); + IAcmeCommandFactory cf = getModel ().getCommandFactory (); + if (client == null) throw new RainbowModelException ("Cannot delete unknown server " + getTarget ()); + IAcmeSystem system = ModelHelper.getAcmeSystem (client); + List connectorsToRemove = new LinkedList<> (); + List rolesToRemove = new LinkedList<> (); + List portsToRemove = new LinkedList<> (); + for (IAcmePort port : client.getPorts ()) { + for (IAcmeAttachment att : system.getAttachments (port)) { + IAcmeConnector conn = (IAcmeConnector )att.getRole ().getParent (); + if (conn.getRoles ().size () <= 2) { + connectorsToRemove.add (conn); + for (IAcmeRole role : conn.getRoles ()) { + if (role == att.getRole ()) { + continue; + } + for (IAcmeAttachment att2 : system.getAttachments (role)) { + portsToRemove.add (att2.getPort ()); + } + } + } + else { + rolesToRemove.add (att.getRole ()); + } + } + } + List> cmds = new LinkedList<> (); + for (IAcmeConnector conn : connectorsToRemove) { + cmds.add (system.getCommandFactory ().connectorDeleteCommand (conn)); + } + for (IAcmeRole role : rolesToRemove) { + cmds.add (system.getCommandFactory ().roleDeleteCommand (role)); + } + for (IAcmePort port : portsToRemove) { + cmds.add (system.getCommandFactory ().portDeleteCommand (port)); + } + m_deleteClientCmd = system.getCommandFactory ().componentDeleteCommand (client); + cmds.add (m_deleteClientCmd); + return cmds; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/RemoveServerCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/RemoveServerCmd.java index 353f5988c..2ac0dbb62 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/RemoveServerCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/RemoveServerCmd.java @@ -1,120 +1,120 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.element.*; -import org.acmestudio.acme.model.IAcmeCommandFactory; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmeComponentDeleteCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -/** - * Removes the a server from the model, and deletes any binary connectors that are connected to it - * - * @author Bradley Schmerl: schmerl - * - */ -public class RemoveServerCmd extends ZNNAcmeModelCommand { - - private IAcmeComponentDeleteCommand m_deleteServerCmd; - - public RemoveServerCmd (AcmeModelInstance model, String server) { - super ("removeServer", model, server); - } - - @Override - public IAcmeComponent getResult () throws IllegalStateException { - return m_deleteServerCmd.getComponent (); - } - - /** - *
-     * {@code
-     * set{roles} roles = server/ports/attachedRoles;
-     * set{connector} attachedConnectors = select c in connectors | exists r in c.roles | contains (roles, r);
-     * set{connector} binaryConnectors = select c in attachedConnectors | size (r.roles) <= 2;
-     * set{connector} otherConnectors = select c in attachedConnectors | size (r.roles) > 2;
-     * set{port} portsToRemove = binaryConnectors/roles/attachedPorts;
-     * set{role} rolesToRemove = otherConnectors/r:roles[connected(r, server)]
-     * foreach p in  portsToRemove {
-     *   delete p;
-     * }
-     * foreach r in rolesToRemove {
-     *   delete r;
-     * }
-     * foreach c in binaryConnectors {
-     *   delete c;
-     * }
-     * delete server;
-     * 
- */ - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - IAcmeCommandFactory cf = getModel ().getCommandFactory (); - if (server == null) throw new RainbowModelException ("Cannot delete unknown server " + getTarget ()); - IAcmeSystem system = ModelHelper.getAcmeSystem (server); - List connectorsToRemove = new LinkedList<> (); - List rolesToRemove = new LinkedList<> (); - List portsToRemove = new LinkedList<> (); - for (IAcmePort port : server.getPorts ()) { - for (IAcmeAttachment att : system.getAttachments (port)) { - IAcmeConnector conn = (IAcmeConnector )att.getRole ().getParent (); - if (conn.getRoles ().size () <= 2) { - connectorsToRemove.add (conn); - for (IAcmeRole role : conn.getRoles ()) { - if (role == att.getRole ()) { - continue; - } - for (IAcmeAttachment att2 : system.getAttachments (role)) { - portsToRemove.add (att2.getPort ()); - } - } - } - else { - rolesToRemove.add (att.getRole ()); - } - } - } - List> cmds = new LinkedList<> (); - for (IAcmeConnector conn : connectorsToRemove) { - cmds.add (system.getCommandFactory ().connectorDeleteCommand (conn)); - } - for (IAcmeRole role : rolesToRemove) { - cmds.add (system.getCommandFactory ().roleDeleteCommand (role)); - } - for (IAcmePort port : portsToRemove) { - cmds.add (system.getCommandFactory ().portDeleteCommand (port)); - } - m_deleteServerCmd = system.getCommandFactory ().componentDeleteCommand (server); - cmds.add (m_deleteServerCmd); - return cmds; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.element.*; +import org.acmestudio.acme.model.IAcmeCommandFactory; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmeComponentDeleteCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +/** + * Removes the a server from the model, and deletes any binary connectors that are connected to it + * + * @author Bradley Schmerl: schmerl + * + */ +public class RemoveServerCmd extends ZNNAcmeModelCommand { + + private IAcmeComponentDeleteCommand m_deleteServerCmd; + + public RemoveServerCmd (String c, AcmeModelInstance model, String server) { + super (c, model, server); + } + + @Override + public IAcmeComponent getResult () throws IllegalStateException { + return m_deleteServerCmd.getComponent (); + } + + /** + *
+     * {@code
+     * set{roles} roles = server/ports/attachedRoles;
+     * set{connector} attachedConnectors = select c in connectors | exists r in c.roles | contains (roles, r);
+     * set{connector} binaryConnectors = select c in attachedConnectors | size (r.roles) <= 2;
+     * set{connector} otherConnectors = select c in attachedConnectors | size (r.roles) > 2;
+     * set{port} portsToRemove = binaryConnectors/roles/attachedPorts;
+     * set{role} rolesToRemove = otherConnectors/r:roles[connected(r, server)]
+     * foreach p in  portsToRemove {
+     *   delete p;
+     * }
+     * foreach r in rolesToRemove {
+     *   delete r;
+     * }
+     * foreach c in binaryConnectors {
+     *   delete c;
+     * }
+     * delete server;
+     * 
+ */ + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + IAcmeCommandFactory cf = getModel ().getCommandFactory (); + if (server == null) throw new RainbowModelException ("Cannot delete unknown server " + getTarget ()); + IAcmeSystem system = ModelHelper.getAcmeSystem (server); + List connectorsToRemove = new LinkedList<> (); + List rolesToRemove = new LinkedList<> (); + List portsToRemove = new LinkedList<> (); + for (IAcmePort port : server.getPorts ()) { + for (IAcmeAttachment att : system.getAttachments (port)) { + IAcmeConnector conn = (IAcmeConnector )att.getRole ().getParent (); + if (conn.getRoles ().size () <= 2) { + connectorsToRemove.add (conn); + for (IAcmeRole role : conn.getRoles ()) { + if (role == att.getRole ()) { + continue; + } + for (IAcmeAttachment att2 : system.getAttachments (role)) { + portsToRemove.add (att2.getPort ()); + } + } + } + else { + rolesToRemove.add (att.getRole ()); + } + } + } + List> cmds = new LinkedList<> (); + for (IAcmeConnector conn : connectorsToRemove) { + cmds.add (system.getCommandFactory ().connectorDeleteCommand (conn)); + } + for (IAcmeRole role : rolesToRemove) { + cmds.add (system.getCommandFactory ().roleDeleteCommand (role)); + } + for (IAcmePort port : portsToRemove) { + cmds.add (system.getCommandFactory ().portDeleteCommand (port)); + } + m_deleteServerCmd = system.getCommandFactory ().componentDeleteCommand (server); + cmds.add (m_deleteServerCmd); + return cmds; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetAuthenticationResponseCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetAuthenticationResponseCmd.java index 2207f5b11..36659ac12 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetAuthenticationResponseCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetAuthenticationResponseCmd.java @@ -1,70 +1,70 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeIntValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -/** - * This command sets whether a client has responded to an authentication request. - * - * @author Bradley Schmerl: schmerl - * - */ -public class SetAuthenticationResponseCmd extends ZNNAcmeModelCommand { - - public SetAuthenticationResponseCmd (AcmeModelInstance modelInstance, String client, String response) { - super ("setAuthenticationResponse", modelInstance, client, response); - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent client = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - int response = Integer.valueOf (getParameters ()[0]); - IAcmeProperty property = client.getProperty ("authenticate"); - IAcmeIntValue acmeVal = PropertyHelper.toAcmeVal (response); - List> cmds = new LinkedList<> (); - if (propertyValueChanging (property, acmeVal)) { - m_command = client.getCommandFactory ().propertyValueSetCommand (property, acmeVal); - cmds.add (m_command); - } - return cmds; - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeIntValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +/** + * This command sets whether a client has responded to an authentication request. + * + * @author Bradley Schmerl: schmerl + * + */ +public class SetAuthenticationResponseCmd extends ZNNAcmeModelCommand { + + public SetAuthenticationResponseCmd (String c, AcmeModelInstance modelInstance, String client, String response) { + super (c, modelInstance, client, response); + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent client = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + int response = Integer.valueOf (getParameters ()[0]); + IAcmeProperty property = client.getProperty ("authenticate"); + IAcmeIntValue acmeVal = PropertyHelper.toAcmeVal (response); + List> cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = client.getCommandFactory ().propertyValueSetCommand (property, acmeVal); + cmds.add (m_command); + } + return cmds; + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetBlackholedCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetBlackholedCmd.java index c9b256e2e..1c5f0f29b 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetBlackholedCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetBlackholedCmd.java @@ -1,100 +1,100 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - -/** - * This command sets the blackholed property of the load balancer with the ips of the clients that are blackholed (or - * blacklisted). - * - * @author Bradley Schmerl: schmerl - * - */ -public class SetBlackholedCmd extends ZNNAcmeModelCommand { - - /** - * @param model - * @param target - * the load balancer - * @param ipSet - */ - public SetBlackholedCmd (AcmeModelInstance model, String target, String ipSet) { - super ("setBlackholed", model, target, ipSet); - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - - @Override - protected List> doConstructCommand () throws RainbowModelException { - // Resolve and check the load balancer - IAcmeComponent lb = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - if (lb == null) - throw new RainbowModelException (MessageFormat.format ( - "The load balancer ''{0}'' could not be found in the model", getTarget ())); - if (!lb.declaresType ("BlackholerT")) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' is not of the right type. It does not have a property ''blackholed''", - getTarget ())); - - // Form the IP set - String[] split = getParameters ()[0].split (","); - HashSet set = new HashSet<> (); - if (!getParameters ()[0].isEmpty ()) { - set.addAll (Arrays.asList (split)); - } - IAcmeProperty property = lb.getProperty ("blackholed"); - if (property == null) - throw new RainbowModelException ( - MessageFormat - .format ( - "The load balancer ''{0}'' does not have a property called ''blackholed''. This should not happen.", - lb.getQualifiedName ())); - IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (set); - List> cmds = new LinkedList<> (); - if (propertyValueChanging (property, acmeVal)) { - m_command = lb.getCommandFactory ().propertyValueSetCommand (property, acmeVal); - cmds.add (m_command); - } - return cmds; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +/** + * This command sets the blackholed property of the load balancer with the ips of the clients that are blackholed (or + * blacklisted). + * + * @author Bradley Schmerl: schmerl + * + */ +public class SetBlackholedCmd extends ZNNAcmeModelCommand { + + /** + * @param model + * @param target + * the load balancer + * @param ipSet + */ + public SetBlackholedCmd (String c, AcmeModelInstance model, String target, String ipSet) { + super (c, model, target, ipSet); + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + + @Override + protected List> doConstructCommand () throws RainbowModelException { + // Resolve and check the load balancer + IAcmeComponent lb = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (lb == null) + throw new RainbowModelException (MessageFormat.format ( + "The load balancer ''{0}'' could not be found in the model", getTarget ())); + if (!lb.declaresType ("BlackholerT")) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''blackholed''", + getTarget ())); + + // Form the IP set + String[] split = getParameters ()[0].split (","); + HashSet set = new HashSet<> (); + if (!getParameters ()[0].isEmpty ()) { + set.addAll (Arrays.asList (split)); + } + IAcmeProperty property = lb.getProperty ("blackholed"); + if (property == null) + throw new RainbowModelException ( + MessageFormat + .format ( + "The load balancer ''{0}'' does not have a property called ''blackholed''. This should not happen.", + lb.getQualifiedName ())); + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (set); + List> cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = lb.getCommandFactory ().propertyValueSetCommand (property, acmeVal); + cmds.add (m_command); + } + return cmds; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetByteServiceRateCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetByteServiceRateCmd.java index 3fbfed123..a8dda09c0 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetByteServiceRateCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetByteServiceRateCmd.java @@ -1,69 +1,69 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class SetByteServiceRateCmd extends ZNNAcmeModelCommand { - - private String m_server; - private Float m_serviceRate; - - public SetByteServiceRateCmd (AcmeModelInstance model, String target, String serviceRate) { - super ("setByteServiceRate", model, target, serviceRate); - m_server = target; - m_serviceRate = Float.valueOf (serviceRate); - - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); - List> cmds = new LinkedList<> (); - IAcmeProperty property = server.getProperty ("byteServiceRate"); - IAcmePropertyValue newVal = PropertyHelper.toAcmeVal (m_serviceRate); - if (propertyValueChanging (property, newVal)) { - m_command = server.getCommandFactory ().propertyValueSetCommand (property, - newVal); - cmds.add (m_command); - } - return cmds; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class SetByteServiceRateCmd extends ZNNAcmeModelCommand { + + private String m_server; + private Float m_serviceRate; + + public SetByteServiceRateCmd (String c, AcmeModelInstance model, String target, String serviceRate) { + super (c, model, target, serviceRate); + m_server = target; + m_serviceRate = Float.valueOf (serviceRate); + + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); + List> cmds = new LinkedList<> (); + IAcmeProperty property = server.getProperty ("byteServiceRate"); + IAcmePropertyValue newVal = PropertyHelper.toAcmeVal (m_serviceRate); + if (propertyValueChanging (property, newVal)) { + m_command = server.getCommandFactory ().propertyValueSetCommand (property, + newVal); + cmds.add (m_command); + } + return cmds; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetCaptchaEnabledCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetCaptchaEnabledCmd.java index 566470233..45742a237 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetCaptchaEnabledCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetCaptchaEnabledCmd.java @@ -1,94 +1,94 @@ -/* - * The MIT License - * - * Copyright 2014 CMU Aimport java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeBooleanValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; -e shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeBooleanValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -/** - * This commands sets the model property indicating whether captcha is enabled. - * - * @author Bradley Schmerl: schmerl - * - */ -public class SetCaptchaEnabledCmd extends ZNNAcmeModelCommand { - - /** - * @param model - * @param target - * The load balancer to set the property on - * @param enabled - */ - public SetCaptchaEnabledCmd (AcmeModelInstance model, String target, String enabled) { - super ("setCaptchaEnabled", model, target, enabled); - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent lb = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - if (lb == null) - throw new RainbowModelException (MessageFormat.format ( - "The load balancer ''{0}'' could not be found in the model", getTarget ())); - if (!lb.declaresType ("CaptchaRedirectT")) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' is not of the right type. It does not have a property ''captchaEnabled''", - getTarget ())); - - List> cmds; - try { - boolean enabled = Boolean.valueOf (getParameters ()[0]); - IAcmeProperty property = lb.getProperty ("captchaEnabled"); - IAcmeBooleanValue acmeVal = PropertyHelper.toAcmeVal (enabled); - cmds = new LinkedList<> (); - if (propertyValueChanging (property, acmeVal)) { - m_command = lb.getCommandFactory ().propertyValueSetCommand (property, acmeVal); - cmds.add (m_command); - } - } - catch (Exception e) { - throw new RainbowModelException (MessageFormat.format ( - "The parameter ''{0}'' cannot be parsed as a boolean", getParameters ()[0])); - } - return cmds; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU Aimport java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeBooleanValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; +e shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeBooleanValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +/** + * This commands sets the model property indicating whether captcha is enabled. + * + * @author Bradley Schmerl: schmerl + * + */ +public class SetCaptchaEnabledCmd extends ZNNAcmeModelCommand { + + /** + * @param model + * @param target + * The load balancer to set the property on + * @param enabled + */ + public SetCaptchaEnabledCmd (String c, AcmeModelInstance model, String target, String enabled) { + super (c, model, target, enabled); + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent lb = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (lb == null) + throw new RainbowModelException (MessageFormat.format ( + "The load balancer ''{0}'' could not be found in the model", getTarget ())); + if (!lb.declaresType ("CaptchaRedirectT")) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''captchaEnabled''", + getTarget ())); + + List> cmds; + try { + boolean enabled = Boolean.valueOf (getParameters ()[0]); + IAcmeProperty property = lb.getProperty ("captchaEnabled"); + IAcmeBooleanValue acmeVal = PropertyHelper.toAcmeVal (enabled); + cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = lb.getCommandFactory ().propertyValueSetCommand (property, acmeVal); + cmds.add (m_command); + } + } + catch (Exception e) { + throw new RainbowModelException (MessageFormat.format ( + "The parameter ''{0}'' cannot be parsed as a boolean", getParameters ()[0])); + } + return cmds; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetCaptchaResponseCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetCaptchaResponseCmd.java index 4c62e8154..a7912d6c5 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetCaptchaResponseCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetCaptchaResponseCmd.java @@ -1,79 +1,79 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeIntValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -public class SetCaptchaResponseCmd extends ZNNAcmeModelCommand { - - public SetCaptchaResponseCmd (AcmeModelInstance modelInstance, String client, String response) { - super ("setCaptchaResponse", modelInstance, client, response); - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent client = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - if (client == null) - throw new RainbowModelException (MessageFormat.format ( - "The load balancer ''{0}'' could not be found in the model", getTarget ())); - if (!client.declaresType ("CaptchaHandlerT")) - throw new RainbowModelException (MessageFormat.format ( - "The client ''{0}'' is not of the right type. It does not have a property ''captcha''", - getTarget ())); - - try { - int response = Integer.valueOf (getParameters ()[0]); - IAcmeProperty property = client.getProperty ("captcha"); - IAcmeIntValue acmeVal = PropertyHelper.toAcmeVal (response); - List> cmds = new LinkedList<> (); - if (propertyValueChanging (property, acmeVal)) { - m_command = client.getCommandFactory ().propertyValueSetCommand (property, acmeVal); - cmds.add (m_command); - } - return cmds; - } - catch (NumberFormatException e) { - throw new RainbowModelException (MessageFormat.format ("Could not parse ''{0}'' as an integer", - getParameters ()[0])); - } - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeIntValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +public class SetCaptchaResponseCmd extends ZNNAcmeModelCommand { + + public SetCaptchaResponseCmd (String c, AcmeModelInstance modelInstance, String client, String response) { + super (c, modelInstance, client, response); + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent client = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (client == null) + throw new RainbowModelException (MessageFormat.format ( + "The load balancer ''{0}'' could not be found in the model", getTarget ())); + if (!client.declaresType ("CaptchaHandlerT")) + throw new RainbowModelException (MessageFormat.format ( + "The client ''{0}'' is not of the right type. It does not have a property ''captcha''", + getTarget ())); + + try { + int response = Integer.valueOf (getParameters ()[0]); + IAcmeProperty property = client.getProperty ("captcha"); + IAcmeIntValue acmeVal = PropertyHelper.toAcmeVal (response); + List> cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = client.getCommandFactory ().propertyValueSetCommand (property, acmeVal); + cmds.add (m_command); + } + return cmds; + } + catch (NumberFormatException e) { + throw new RainbowModelException (MessageFormat.format ("Could not parse ''{0}'' as an integer", + getParameters ()[0])); + } + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetClientRequestRateCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetClientRequestRateCmd.java index ea389bb7c..c16a002f3 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetClientRequestRateCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetClientRequestRateCmd.java @@ -1,43 +1,43 @@ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.acmestudio.acme.model.util.core.UMFloatingPointValue; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -public class SetClientRequestRateCmd extends ZNNAcmeModelCommand { - - private String m_client; - private Float m_reqRate; - - public SetClientRequestRateCmd (AcmeModelInstance model, String client, String reqRate) { - super ("setClientRequestRate", model, client, reqRate); - m_client = client; - m_reqRate = Float.valueOf (reqRate); - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent client = getModelContext ().resolveInModel (m_client, IAcmeComponent.class); - if (client == null) - throw new RainbowModelException (MessageFormat.format ("Could not find client ''{0}'' in model", m_client)); - m_command = client.getCommandFactory ().propertyValueSetCommand (client.getProperty ("reqRate"), - new UMFloatingPointValue (m_reqRate)); - List> cmds = new LinkedList<> (); - cmds.add (m_command); - return cmds; - } - -} +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.acmestudio.acme.model.util.core.UMFloatingPointValue; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +public class SetClientRequestRateCmd extends ZNNAcmeModelCommand { + + private String m_client; + private Float m_reqRate; + + public SetClientRequestRateCmd (String c, AcmeModelInstance model, String client, String reqRate) { + super (c, model, client, reqRate); + m_client = client; + m_reqRate = Float.valueOf (reqRate); + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent client = getModelContext ().resolveInModel (m_client, IAcmeComponent.class); + if (client == null) + throw new RainbowModelException (MessageFormat.format ("Could not find client ''{0}'' in model", m_client)); + m_command = client.getCommandFactory ().propertyValueSetCommand (client.getProperty ("reqRate"), + new UMFloatingPointValue (m_reqRate)); + List> cmds = new LinkedList<> (); + cmds.add (m_command); + return cmds; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetFidelityCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetFidelityCmd.java index e7f2340f7..39f2f0747 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetFidelityCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetFidelityCmd.java @@ -1,85 +1,85 @@ -/* - * The MIT License - * - * Copyright 2014 CMU Aimport java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeIntValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; -otice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeIntValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -public class SetFidelityCmd extends ZNNAcmeModelCommand { - - private String m_server; - private int m_fidelity; - - public SetFidelityCmd (AcmeModelInstance model, String server, String fidelity) { - super ("setFidelity", model, server, fidelity); - m_server = server; - m_fidelity = Integer.valueOf (fidelity); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", getTarget ())); - if (!server.declaresType ("ArchElementT")) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' is not of the right type. It does not have a property ''fidelity''", - getTarget ())); - IAcmeProperty property = server.getProperty ("fidelity"); - try { - IAcmeIntValue acmeVal = PropertyHelper.toAcmeVal (m_fidelity); - List> cmds = new LinkedList<> (); - if (propertyValueChanging (property, acmeVal)) { - m_command = server.getCommandFactory ().propertyValueSetCommand (property, acmeVal); - cmds.add (m_command); - } - return cmds; - } - catch (Exception e) { - throw new RainbowModelException (MessageFormat.format ("Could not parse ''{0}'' as an integer.", - getParameters ()[0])); - } - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU Aimport java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeIntValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; +otice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeIntValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +public class SetFidelityCmd extends ZNNAcmeModelCommand { + + private String m_server; + private int m_fidelity; + + public SetFidelityCmd (String c, AcmeModelInstance model, String server, String fidelity) { + super (c, model, server, fidelity); + m_server = server; + m_fidelity = Integer.valueOf (fidelity); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + if (!server.declaresType ("ArchElementT")) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''fidelity''", + getTarget ())); + IAcmeProperty property = server.getProperty ("fidelity"); + try { + IAcmeIntValue acmeVal = PropertyHelper.toAcmeVal (m_fidelity); + List> cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = server.getCommandFactory ().propertyValueSetCommand (property, acmeVal); + cmds.add (m_command); + } + return cmds; + } + catch (Exception e) { + throw new RainbowModelException (MessageFormat.format ("Could not parse ''{0}'' as an integer.", + getParameters ()[0])); + } + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLastPageHitCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLastPageHitCmd.java index c6691388b..4d257b5e5 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLastPageHitCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLastPageHitCmd.java @@ -1,69 +1,69 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeStringValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class SetLastPageHitCmd extends ZNNAcmeModelCommand { - - private String m_server; - private String m_page; - - public SetLastPageHitCmd (AcmeModelInstance model, String target, String page) { - super ("setLastPageHit", model, target, page); - m_server = target; - m_page = page; - - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); - IAcmeProperty property = server.getProperty ("lastPageHit"); - IAcmeStringValue acmeVal = PropertyHelper.toAcmeVal (m_page); - List> cmds = new LinkedList<> (); - if (propertyValueChanging (property, acmeVal)) { - m_command = server.getCommandFactory ().propertyValueSetCommand (property, - acmeVal); - cmds.add (m_command); - } - return cmds; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeStringValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class SetLastPageHitCmd extends ZNNAcmeModelCommand { + + private String m_server; + private String m_page; + + public SetLastPageHitCmd (String c, AcmeModelInstance model, String target, String page) { + super (c, model, target, page); + m_server = target; + m_page = page; + + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); + IAcmeProperty property = server.getProperty ("lastPageHit"); + IAcmeStringValue acmeVal = PropertyHelper.toAcmeVal (m_page); + List> cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = server.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + return cmds; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLatencyCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLatencyCmd.java index 32aeeca51..4fa1c6d5b 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLatencyCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLatencyCmd.java @@ -1,69 +1,69 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; -import org.acmestudio.acme.element.IAcmeConnector; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class SetLatencyCmd extends ZNNAcmeModelCommand { - - private String m_httpConn; - private double m_latency; - - public SetLatencyCmd (AcmeModelInstance model, String conn, String latency) { - super ("setLatency", model, conn, latency); - m_httpConn = conn; - m_latency = Double.valueOf (latency); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeConnector httpConn = getModelContext ().resolveInModel (m_httpConn, IAcmeConnector.class); - IAcmeProperty property = httpConn.getProperty ("latency"); - IAcmeFloatingPointValue acmeVal = PropertyHelper.toAcmeVal (m_latency); - List> cmds = new LinkedList<> (); - if (propertyValueChanging (property, acmeVal)) { - m_command = httpConn.getCommandFactory ().propertyValueSetCommand (property, - acmeVal); - cmds.add (m_command); - } - return cmds; - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeFloatingPointValue; +import org.acmestudio.acme.element.IAcmeConnector; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class SetLatencyCmd extends ZNNAcmeModelCommand { + + private String m_httpConn; + private double m_latency; + + public SetLatencyCmd (String c, AcmeModelInstance model, String conn, String latency) { + super (c, model, conn, latency); + m_httpConn = conn; + m_latency = Double.valueOf (latency); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeConnector httpConn = getModelContext ().resolveInModel (m_httpConn, IAcmeConnector.class); + IAcmeProperty property = httpConn.getProperty ("latency"); + IAcmeFloatingPointValue acmeVal = PropertyHelper.toAcmeVal (m_latency); + List> cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = httpConn.getCommandFactory ().propertyValueSetCommand (property, + acmeVal); + cmds.add (m_command); + } + return cmds; + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLatencyRateCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLatencyRateCmd.java index 249e29273..a8bc6496c 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLatencyRateCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLatencyRateCmd.java @@ -1,64 +1,64 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeConnector; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class SetLatencyRateCmd extends ZNNAcmeModelCommand { - - private String m_httpConn; - private double m_latencyRate; - - public SetLatencyRateCmd (AcmeModelInstance model, String conn, String latencyRate) { - super ("setLatency", model, conn, latencyRate); - m_httpConn = conn; - m_latencyRate = Double.valueOf (latencyRate); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeConnector httpConn = getModelContext ().resolveInModel (m_httpConn, IAcmeConnector.class); - m_command = httpConn.getCommandFactory ().propertyValueSetCommand (httpConn.getProperty ("latencyRate"), - PropertyHelper.toAcmeVal (m_latencyRate)); - List> cmds = new LinkedList<> (); - cmds.add (m_command); - return cmds; - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeConnector; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class SetLatencyRateCmd extends ZNNAcmeModelCommand { + + private String m_httpConn; + private double m_latencyRate; + + public SetLatencyRateCmd (String c, AcmeModelInstance model, String conn, String latencyRate) { + super (c, model, conn, latencyRate); + m_httpConn = conn; + m_latencyRate = Double.valueOf (latencyRate); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeConnector httpConn = getModelContext ().resolveInModel (m_httpConn, IAcmeConnector.class); + m_command = httpConn.getCommandFactory ().propertyValueSetCommand (httpConn.getProperty ("latencyRate"), + PropertyHelper.toAcmeVal (m_latencyRate)); + List> cmds = new LinkedList<> (); + cmds.add (m_command); + return cmds; + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLoadCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLoadCmd.java index 496ad8410..06d9b1601 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLoadCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetLoadCmd.java @@ -1,64 +1,64 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class SetLoadCmd extends ZNNAcmeModelCommand { - - private String m_server; - private float m_load; - - public SetLoadCmd (AcmeModelInstance model, String server, String load) { - super ("setLoad", model, server, load); - m_server = server; - m_load = Float.valueOf (load); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); - m_command = server.getCommandFactory ().propertyValueSetCommand (server.getProperty ("load"), - PropertyHelper.toAcmeVal (m_load)); - List> cmds = new LinkedList<> (); - cmds.add (m_command); - return cmds; - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class SetLoadCmd extends ZNNAcmeModelCommand { + + private String m_server; + private float m_load; + + public SetLoadCmd (String c, AcmeModelInstance model, String server, String load) { + super (c, model, server, load); + m_server = server; + m_load = Float.valueOf (load); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); + m_command = server.getCommandFactory ().propertyValueSetCommand (server.getProperty ("load"), + PropertyHelper.toAcmeVal (m_load)); + List> cmds = new LinkedList<> (); + cmds.add (m_command); + return cmds; + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetMaliciousnessCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetMaliciousnessCmd.java index 9dddca165..513a5f092 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetMaliciousnessCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetMaliciousnessCmd.java @@ -1,77 +1,77 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -public class SetMaliciousnessCmd extends ZNNAcmeModelCommand { - - public SetMaliciousnessCmd (AcmeModelInstance model, String target, - String maliciousness) { - super ("setMaliciousness", model, target, maliciousness); - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent client = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - if (client == null) - throw new RainbowModelException (MessageFormat.format ( - "The client ''{0}'' could not be found in the model", getTarget ())); - if (!client.declaresType ("ClientT")) - throw new RainbowModelException (MessageFormat.format ( - "The client ''{0}'' is not of the right type. It does not have a property ''maliciousness''", - getTarget ())); - IAcmeProperty property = client.getProperty ("maliciousness"); - try { - IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Float.valueOf (getParameters ()[0])); - List> cmds = new LinkedList<> (); - if (propertyValueChanging (property, acmeVal)) { - m_command = client.getCommandFactory ().propertyValueSetCommand (property, acmeVal); - cmds.add (m_command); - } - return cmds; - } - catch (NumberFormatException e) { - throw new RainbowModelException (MessageFormat.format ("Could not parse ''{0}'' as a float number.", - getParameters ()[0])); - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +public class SetMaliciousnessCmd extends ZNNAcmeModelCommand { + + public SetMaliciousnessCmd (String c, AcmeModelInstance model, String target, + String maliciousness) { + super (c, model, target, maliciousness); + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent client = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (client == null) + throw new RainbowModelException (MessageFormat.format ( + "The client ''{0}'' could not be found in the model", getTarget ())); + if (!client.declaresType ("ClientT")) + throw new RainbowModelException (MessageFormat.format ( + "The client ''{0}'' is not of the right type. It does not have a property ''maliciousness''", + getTarget ())); + IAcmeProperty property = client.getProperty ("maliciousness"); + try { + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (Float.valueOf (getParameters ()[0])); + List> cmds = new LinkedList<> (); + if (propertyValueChanging (property, acmeVal)) { + m_command = client.getCommandFactory ().propertyValueSetCommand (property, acmeVal); + cmds.add (m_command); + } + return cmds; + } + catch (NumberFormatException e) { + throw new RainbowModelException (MessageFormat.format ("Could not parse ''{0}'' as a float number.", + getParameters ()[0])); + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRedirectedRequestsCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRedirectedRequestsCmd.java index 3a1ec8060..3fa3b40bd 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRedirectedRequestsCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRedirectedRequestsCmd.java @@ -1,68 +1,68 @@ -/* - * The MIT License - * - * Copyright 2014 CMU Aimport java.util.LinkedList; -import java.util.List; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeConnector; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeConnector; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class SetNumRedirectedRequestsCmd extends ZNNAcmeModelCommand { - - private String m_server; - private float m_requests; - - public SetNumRedirectedRequestsCmd (AcmeModelInstance model, String server, - String requests) { - super ("setNumRedirectedRequests", model, server, requests); - m_server = server; - m_requests = Integer.valueOf (requests); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeConnector httpConn = getModelContext ().resolveInModel (m_server, IAcmeConnector.class); - m_command = httpConn.getCommandFactory ().propertyValueSetCommand (httpConn.getProperty ("numReqsRedirect"), - PropertyHelper.toAcmeVal (m_requests)); - List> cmds = new LinkedList<> (); - cmds.add (m_command); - return cmds; - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU Aimport java.util.LinkedList; +import java.util.List; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeConnector; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeConnector; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class SetNumRedirectedRequestsCmd extends ZNNAcmeModelCommand { + + private String m_server; + private float m_requests; + + public SetNumRedirectedRequestsCmd (String c, AcmeModelInstance model, String server, + String requests) { + super (c, model, server, requests); + m_server = server; + m_requests = Integer.valueOf (requests); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeConnector httpConn = getModelContext ().resolveInModel (m_server, IAcmeConnector.class); + m_command = httpConn.getCommandFactory ().propertyValueSetCommand (httpConn.getProperty ("numReqsRedirect"), + PropertyHelper.toAcmeVal (m_requests)); + List> cmds = new LinkedList<> (); + cmds.add (m_command); + return cmds; + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRequestsClientErrorCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRequestsClientErrorCmd.java index c83ffac7d..f3be384ab 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRequestsClientErrorCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRequestsClientErrorCmd.java @@ -1,68 +1,68 @@ -/* - * The MIT License - * - * Copyright 2014 CMU Aimport java.util.LinkedList; -import java.util.List; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeConnector; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeConnector; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class SetNumRequestsClientErrorCmd extends ZNNAcmeModelCommand { - - private String m_server; - private float m_requests; - - public SetNumRequestsClientErrorCmd (AcmeModelInstance model, String server, - String requests) { - super ("setNumRequestsClientError", model, server, requests); - m_server = server; - m_requests = Integer.valueOf (requests); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeConnector httpConn = getModelContext ().resolveInModel (m_server, IAcmeConnector.class); - m_command = httpConn.getCommandFactory ().propertyValueSetCommand (httpConn.getProperty ("numReqsClientError"), - PropertyHelper.toAcmeVal (m_requests)); - List> cmds = new LinkedList<> (); - cmds.add (m_command); - return cmds; - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU Aimport java.util.LinkedList; +import java.util.List; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeConnector; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeConnector; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class SetNumRequestsClientErrorCmd extends ZNNAcmeModelCommand { + + private String m_server; + private float m_requests; + + public SetNumRequestsClientErrorCmd (String c, AcmeModelInstance model, String server, + String requests) { + super (c, model, server, requests); + m_server = server; + m_requests = Integer.valueOf (requests); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeConnector httpConn = getModelContext ().resolveInModel (m_server, IAcmeConnector.class); + m_command = httpConn.getCommandFactory ().propertyValueSetCommand (httpConn.getProperty ("numReqsClientError"), + PropertyHelper.toAcmeVal (m_requests)); + List> cmds = new LinkedList<> (); + cmds.add (m_command); + return cmds; + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRequestsServerErrorCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRequestsServerErrorCmd.java index 168a6c305..35d7cb972 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRequestsServerErrorCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumRequestsServerErrorCmd.java @@ -1,65 +1,65 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeConnector; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class SetNumRequestsServerErrorCmd extends ZNNAcmeModelCommand { - - private String m_server; - private float m_requests; - - public SetNumRequestsServerErrorCmd (AcmeModelInstance model, String server, - String requests) { - super ("setNumRequestsServerError", model, server, requests); - m_server = server; - m_requests = Integer.valueOf (requests); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeConnector httpConn = getModelContext ().resolveInModel (m_server, IAcmeConnector.class); - m_command = httpConn.getCommandFactory ().propertyValueSetCommand (httpConn.getProperty ("numReqsServerError"), - PropertyHelper.toAcmeVal (m_requests)); - List> cmds = new LinkedList<> (); - cmds.add (m_command); - return cmds; - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeConnector; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class SetNumRequestsServerErrorCmd extends ZNNAcmeModelCommand { + + private String m_server; + private float m_requests; + + public SetNumRequestsServerErrorCmd (String c, AcmeModelInstance model, String server, + String requests) { + super (c, model, server, requests); + m_server = server; + m_requests = Integer.valueOf (requests); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeConnector httpConn = getModelContext ().resolveInModel (m_server, IAcmeConnector.class); + m_command = httpConn.getCommandFactory ().propertyValueSetCommand (httpConn.getProperty ("numReqsServerError"), + PropertyHelper.toAcmeVal (m_requests)); + List> cmds = new LinkedList<> (); + cmds.add (m_command); + return cmds; + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumSuccessfulRequestsCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumSuccessfulRequestsCmd.java index 49d743f46..da125b431 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumSuccessfulRequestsCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetNumSuccessfulRequestsCmd.java @@ -1,65 +1,65 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeConnector; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class SetNumSuccessfulRequestsCmd extends ZNNAcmeModelCommand { - - private String m_server; - private float m_requests; - - public SetNumSuccessfulRequestsCmd (AcmeModelInstance model, String server, - String requests) { - super ("setNumSuccessfulRequests", model, server, requests); - m_server = server; - m_requests = Integer.valueOf (requests); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeConnector httpConn = getModelContext ().resolveInModel (m_server, IAcmeConnector.class); - m_command = httpConn.getCommandFactory ().propertyValueSetCommand (httpConn.getProperty ("numReqsSuccess"), - PropertyHelper.toAcmeVal (m_requests)); - List> cmds = new LinkedList<> (); - cmds.add (m_command); - return cmds; - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeConnector; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class SetNumSuccessfulRequestsCmd extends ZNNAcmeModelCommand { + + private String m_server; + private float m_requests; + + public SetNumSuccessfulRequestsCmd (String c, AcmeModelInstance model, String server, + String requests) { + super (c, model, server, requests); + m_server = server; + m_requests = Integer.valueOf (requests); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeConnector httpConn = getModelContext ().resolveInModel (m_server, IAcmeConnector.class); + m_command = httpConn.getCommandFactory ().propertyValueSetCommand (httpConn.getProperty ("numReqsSuccess"), + PropertyHelper.toAcmeVal (m_requests)); + List> cmds = new LinkedList<> (); + cmds.add (m_command); + return cmds; + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetReqServiceRateCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetReqServiceRateCmd.java index f68489dc0..e123d2d83 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetReqServiceRateCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetReqServiceRateCmd.java @@ -1,64 +1,64 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -public class SetReqServiceRateCmd extends ZNNAcmeModelCommand { - - private String m_server; - private Float m_serviceRate; - - public SetReqServiceRateCmd (AcmeModelInstance model, String target, String serviceRate) { - super ("setReqServiceRate", model, target, serviceRate); - m_server = target; - m_serviceRate = Float.valueOf (serviceRate); - - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); - m_command = server.getCommandFactory ().propertyValueSetCommand (server.getProperty ("reqServiceRate"), - PropertyHelper.toAcmeVal (m_serviceRate)); - List> cmds = new LinkedList<> (); - cmds.add (m_command); - return cmds; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +public class SetReqServiceRateCmd extends ZNNAcmeModelCommand { + + private String m_server; + private Float m_serviceRate; + + public SetReqServiceRateCmd (String c, AcmeModelInstance model, String target, String serviceRate) { + super (c, model, target, serviceRate); + m_server = target; + m_serviceRate = Float.valueOf (serviceRate); + + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent server = getModelContext ().resolveInModel (m_server, IAcmeComponent.class); + m_command = server.getCommandFactory ().propertyValueSetCommand (server.getProperty ("reqServiceRate"), + PropertyHelper.toAcmeVal (m_serviceRate)); + List> cmds = new LinkedList<> (); + cmds.add (m_command); + return cmds; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetResponseTimeCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetResponseTimeCmd.java index ecac4671b..bbd9fb40e 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetResponseTimeCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetResponseTimeCmd.java @@ -1,73 +1,73 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.LinkedList; -import java.util.List; - -public class SetResponseTimeCmd extends ZNNAcmeModelCommand { - - private String m_client; - private float m_responseTime; - - public SetResponseTimeCmd (AcmeModelInstance model, String client, String rt) { - super ("setResponseTime", model, client, rt); - m_client = client; - m_responseTime = Float.valueOf (rt); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent client = getModelContext ().resolveInModel (m_client, IAcmeComponent.class); - if (client == null) - throw new RainbowModelException (MessageFormat.format ( - "The client ''{0}'' could not be found in the model", getTarget ())); - if (!client.declaresType ("ClientT")) - throw new RainbowModelException (MessageFormat.format ( - "The client ''{0}'' is not of the right type. It does not have a property ''experRespTime''", - getTarget ())); - IAcmeProperty expRT = client.getProperty ("experRespTime"); - m_command = client.getCommandFactory ().propertyValueSetCommand (expRT, - PropertyHelper.toAcmeVal (m_responseTime)); - List> cmds = new LinkedList<> (); - cmds.add (m_command); - return cmds; - } - - @Override - public IAcmeProperty getResult () { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +public class SetResponseTimeCmd extends ZNNAcmeModelCommand { + + private String m_client; + private float m_responseTime; + + public SetResponseTimeCmd (String c, AcmeModelInstance model, String client, String rt) { + super (c, model, client, rt); + m_client = client; + m_responseTime = Float.valueOf (rt); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent client = getModelContext ().resolveInModel (m_client, IAcmeComponent.class); + if (client == null) + throw new RainbowModelException (MessageFormat.format ( + "The client ''{0}'' could not be found in the model", getTarget ())); + if (!client.declaresType ("ClientT")) + throw new RainbowModelException (MessageFormat.format ( + "The client ''{0}'' is not of the right type. It does not have a property ''experRespTime''", + getTarget ())); + IAcmeProperty expRT = client.getProperty ("experRespTime"); + m_command = client.getCommandFactory ().propertyValueSetCommand (expRT, + PropertyHelper.toAcmeVal (m_responseTime)); + List> cmds = new LinkedList<> (); + cmds.add (m_command); + return cmds; + } + + @Override + public IAcmeProperty getResult () { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetSystemPropertiesCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetSystemPropertiesCmd.java index c1e09c482..dc53dcce7 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetSystemPropertiesCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetSystemPropertiesCmd.java @@ -1,64 +1,64 @@ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.DefaultAcmeModel; -import org.acmestudio.acme.model.IAcmeCommandFactory; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.util.core.UMFloatingPointValue; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by schmerl on 9/10/2015. - */ -public class SetSystemPropertiesCmd extends ZNNAcmeModelCommand { - - - public static final String AVERAGE_CLIENT_RESPONSE_TIME = "averageClientResponseTime"; - public static final String PERCENTAGE_MALICIOUS = "percentageMalicious"; - private String m_avgRt; - private String m_maliciousness; - private String m_aboveRT; - private String m_aboveMal; - - public SetSystemPropertiesCmd (AcmeModelInstance model, String target, String avgRt, String maliciousness, String aboveRT, String aboveMal) { - super ("setSystemProperties", model, target, avgRt, maliciousness, aboveRT, aboveMal); - m_avgRt = avgRt; - m_maliciousness = maliciousness; - m_aboveRT = aboveRT; - m_aboveMal = aboveMal; - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeSystem system = getModelContext ().getModelInstance (); - - List> cmds = new LinkedList<> (); - IAcmeProperty rtProp = system.getProperty (AVERAGE_CLIENT_RESPONSE_TIME); - IAcmeCommandFactory cf = system.getCommandFactory (); - UMFloatingPointValue rtAcme = new UMFloatingPointValue (Float.valueOf (m_avgRt)); - if (rtProp == null) { - cmds.add (cf.propertyCreateCommand (system, AVERAGE_CLIENT_RESPONSE_TIME, DefaultAcmeModel.defaultFloatType (), rtAcme)); - } else { - cmds.add (cf.propertyValueSetCommand (rtProp, rtAcme)); - } - - IAcmeProperty malProp = system.getProperty (PERCENTAGE_MALICIOUS); - UMFloatingPointValue malAcme = new UMFloatingPointValue (Float.valueOf (m_maliciousness)); - if (malProp == null) { - cmds.add (cf.propertyCreateCommand (system, PERCENTAGE_MALICIOUS, DefaultAcmeModel.defaultFloatType (), malAcme)); - } else { - cmds.add (cf.propertyValueSetCommand (malProp, malAcme)); - } - return cmds; - } - - @Override - public IAcmeSystem getResult () throws IllegalStateException { - return getModel (); - } -} +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.DefaultAcmeModel; +import org.acmestudio.acme.model.IAcmeCommandFactory; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.util.core.UMFloatingPointValue; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.LinkedList; +import java.util.List; + +/** + * Created by schmerl on 9/10/2015. + */ +public class SetSystemPropertiesCmd extends ZNNAcmeModelCommand { + + + public static final String AVERAGE_CLIENT_RESPONSE_TIME = "averageClientResponseTime"; + public static final String PERCENTAGE_MALICIOUS = "percentageMalicious"; + private String m_avgRt; + private String m_maliciousness; + private String m_aboveRT; + private String m_aboveMal; + + public SetSystemPropertiesCmd (String c, AcmeModelInstance model, String target, String avgRt, String maliciousness, String aboveRT, String aboveMal) { + super (c, model, target, avgRt, maliciousness, aboveRT, aboveMal); + m_avgRt = avgRt; + m_maliciousness = maliciousness; + m_aboveRT = aboveRT; + m_aboveMal = aboveMal; + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeSystem system = getModelContext ().getModelInstance (); + + List> cmds = new LinkedList<> (); + IAcmeProperty rtProp = system.getProperty (AVERAGE_CLIENT_RESPONSE_TIME); + IAcmeCommandFactory cf = system.getCommandFactory (); + UMFloatingPointValue rtAcme = new UMFloatingPointValue (Float.valueOf (m_avgRt)); + if (rtProp == null) { + cmds.add (cf.propertyCreateCommand (system, AVERAGE_CLIENT_RESPONSE_TIME, DefaultAcmeModel.defaultFloatType (), rtAcme)); + } else { + cmds.add (cf.propertyValueSetCommand (rtProp, rtAcme)); + } + + IAcmeProperty malProp = system.getProperty (PERCENTAGE_MALICIOUS); + UMFloatingPointValue malAcme = new UMFloatingPointValue (Float.valueOf (m_maliciousness)); + if (malProp == null) { + cmds.add (cf.propertyCreateCommand (system, PERCENTAGE_MALICIOUS, DefaultAcmeModel.defaultFloatType (), malAcme)); + } else { + cmds.add (cf.propertyValueSetCommand (malProp, malAcme)); + } + return cmds; + } + + @Override + public IAcmeSystem getResult () throws IllegalStateException { + return getModel (); + } +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetThrottledCmd.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetThrottledCmd.java index 5cbee7434..b330c0041 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetThrottledCmd.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/SetThrottledCmd.java @@ -1,77 +1,77 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - -public class SetThrottledCmd extends ZNNAcmeModelCommand { - - public SetThrottledCmd (AcmeModelInstance model, String target, String parameters) { - super ("setThrottled", model, target, parameters); - } - - @Override - public IAcmeProperty getResult () throws IllegalStateException { - return ((IAcmePropertyCommand )m_command).getProperty (); - } - - @Override - protected List> doConstructCommand () throws RainbowModelException { - IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); - if (server == null) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' could not be found in the model", getTarget ())); - if (!server.declaresType ("ThrottlerT")) - throw new RainbowModelException (MessageFormat.format ( - "The server ''{0}'' is not of the right type. It does not have a property ''throttled''", - getTarget ())); - String[] ips = getParameters ()[0].split (","); - HashSet ipSet = new HashSet<> (); - if (!getParameters ()[0].isEmpty ()) { - ipSet.addAll (Arrays.asList (ips)); - } - List> cmds = new LinkedList<> (); - IAcmeProperty property = server.getProperty ("throttled"); - IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (ipSet); - if (propertyValueChanging (property, acmeVal)) { - m_command = server.getCommandFactory ().propertyValueSetCommand (property, acmeVal); - cmds.add (m_command); - } - return cmds; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +public class SetThrottledCmd extends ZNNAcmeModelCommand { + + public SetThrottledCmd (String c, AcmeModelInstance model, String target, String parameters) { + super (c, model, target, parameters); + } + + @Override + public IAcmeProperty getResult () throws IllegalStateException { + return ((IAcmePropertyCommand )m_command).getProperty (); + } + + @Override + protected List> doConstructCommand () throws RainbowModelException { + IAcmeComponent server = getModelContext ().resolveInModel (getTarget (), IAcmeComponent.class); + if (server == null) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' could not be found in the model", getTarget ())); + if (!server.declaresType ("ThrottlerT")) + throw new RainbowModelException (MessageFormat.format ( + "The server ''{0}'' is not of the right type. It does not have a property ''throttled''", + getTarget ())); + String[] ips = getParameters ()[0].split (","); + HashSet ipSet = new HashSet<> (); + if (!getParameters ()[0].isEmpty ()) { + ipSet.addAll (Arrays.asList (ips)); + } + List> cmds = new LinkedList<> (); + IAcmeProperty property = server.getProperty ("throttled"); + IAcmePropertyValue acmeVal = PropertyHelper.toAcmeVal (ipSet); + if (propertyValueChanging (property, acmeVal)) { + m_command = server.getCommandFactory ().propertyValueSetCommand (property, acmeVal); + cmds.add (m_command); + } + return cmds; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNAcmeModelCommand.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNAcmeModelCommand.java index 9816d03ba..a7c8ebd5f 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNAcmeModelCommand.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNAcmeModelCommand.java @@ -1,43 +1,43 @@ -/* - * The MIT License - * - * Copyright 2014 CMU Aimport org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.model.acme.AcmeModelInstance; -import org.sa.rainbow.model.acme.AcmeModelOperation; - "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.model.acme.AcmeModelOperation; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public abstract class ZNNAcmeModelCommand extends AcmeModelOperation { - - public ZNNAcmeModelCommand (String commandName, AcmeModelInstance model, String target, - String... parameters) { - super (commandName, model, target, parameters); - } - - - @Override - protected boolean checkModelValidForCommand (IAcmeSystem model) { - return model.declaresType ("ZNewsFam"); - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU Aimport org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.AcmeModelOperation; + "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.model.acme.AcmeModelOperation; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public abstract class ZNNAcmeModelCommand extends AcmeModelOperation { + + public ZNNAcmeModelCommand (String commandName, AcmeModelInstance model, String target, + String... parameters) { + super (commandName, model, target, parameters); + } + + + @Override + protected boolean checkModelValidForCommand (IAcmeSystem model) { + return model.declaresType ("ZNewsFam"); + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNCommandFactory.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNCommandFactory.java index 131fc6d25..40ff65e6a 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNCommandFactory.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNCommandFactory.java @@ -1,366 +1,389 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import incubator.pval.Ensure; -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.IAcmeConnector; -import org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.core.models.ModelsManager; -import org.sa.rainbow.model.acme.AcmeModelCommandFactory; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.io.InputStream; -import java.util.Set; - -import static incubator.pval.Ensure.isTrue; - -public class ZNNCommandFactory extends AcmeModelCommandFactory { - - - public static ZNNLoadModelCommand loadCommand (ModelsManager modelsManager, - String modelName, - InputStream stream, - String source) { - return new ZNNLoadModelCommand (modelName, modelsManager, stream, source); - } - - public ZNNCommandFactory (AcmeModelInstance modelInstance) { - super (modelInstance); - } - - @Override - protected void fillInCommandMap () { - super.fillInCommandMap (); - m_commandMap.put ("setResponseTime".toLowerCase (), SetResponseTimeCmd.class); - m_commandMap.put ("setLoad".toLowerCase (), SetLoadCmd.class); - m_commandMap.put ("connectNewServer".toLowerCase (), NewServerCmd.class); - m_commandMap.put ("deleteServer".toLowerCase (), RemoveServerCmd.class); - m_commandMap.put ("setReqServiceRate".toLowerCase (), SetReqServiceRateCmd.class); - m_commandMap.put ("setByteServiceRate".toLowerCase (), SetByteServiceRateCmd.class); - m_commandMap.put ("setLatencyRate".toLowerCase (), SetLatencyRateCmd.class); - m_commandMap.put ("setLatency".toLowerCase (), SetLatencyCmd.class); - m_commandMap.put ("setLastPageHit".toLowerCase (), SetLastPageHitCmd.class); - m_commandMap.put ("setNumRedirectedRequests".toLowerCase (), SetNumRedirectedRequestsCmd.class); - m_commandMap.put ("setNumRequestsClientError".toLowerCase (), SetNumRequestsClientErrorCmd.class); - m_commandMap.put ("SetNumRequestsServerError".toLowerCase (), SetNumRequestsServerErrorCmd.class); - m_commandMap.put ("SetNumSuccessfulRequests".toLowerCase (), SetNumSuccessfulRequestsCmd.class); - m_commandMap.put ("SetBlackholed".toLowerCase (), SetBlackholedCmd.class); - m_commandMap.put ("SetCaptchaEnabled".toLowerCase (), SetCaptchaEnabledCmd.class); - m_commandMap.put ("SetMaliciousness".toLowerCase (), SetMaliciousnessCmd.class); - m_commandMap.put ("SetClientRequestRate".toLowerCase (), SetClientRequestRateCmd.class); - m_commandMap.put ("EnableServer".toLowerCase (), EnableServerCmd.class); - m_commandMap.put ("SetFidelity".toLowerCase (), SetFidelityCmd.class); - m_commandMap.put ("SetThrottled".toLowerCase (), SetThrottledCmd.class); - m_commandMap.put ("forceReauthentication".toLowerCase (), ForceReauthenticationCmd.class); - m_commandMap.put ("SetCaptchaResponse".toLowerCase (), SetCaptchaResponseCmd.class); - m_commandMap.put ("SetAuthenticationResponse".toLowerCase (), SetAuthenticationResponseCmd.class); - m_commandMap.put ("AddClient".toLowerCase (), AddClientCmd.class); - m_commandMap.put ("DeleteClient".toLowerCase (), RemoveClientCmd.class); - m_commandMap.put ("setSystemProperties".toLowerCase (), SetSystemPropertiesCmd.class); - m_commandMap.put ("connectServer".toLowerCase (), ConnectServerCmd.class); - m_commandMap.put ("createDisconnectedServer".toLowerCase (), CreateDisconnectedServerCmd.class); - - } - - public CreateDisconnectedServerCmd createDiconnectedServer (IAcmeSystem system, String name) { - if (ModelHelper.getAcmeSystem (system) != m_modelInstance.getModelInstance ()) { - throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); - } - return new CreateDisconnectedServerCmd ((AcmeModelInstance) m_modelInstance, system.getName (), name); - } - - public ConnectServerCmd connectServer (IAcmeComponent lb, String name, String deploymentLocation, - String port) { - if (ModelHelper.getAcmeSystem (lb) != m_modelInstance.getModelInstance ()) { - throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); - } - return new ConnectServerCmd ((AcmeModelInstance) m_modelInstance, lb.getQualifiedName (), name, - deploymentLocation, port); - } - - public SetSystemPropertiesCmd setSystemProperties (IAcmeSystem sys, float avgRt, float perMalicious, boolean - highResponseTime, boolean aboveMalicious) { - if (ModelHelper.getAcmeSystem (sys) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); - return new SetSystemPropertiesCmd ((AcmeModelInstance) m_modelInstance, sys.getQualifiedName (), Float - .toString (avgRt), Float.toString (perMalicious), Boolean.toString (highResponseTime), Boolean - .toString (aboveMalicious)); - } - - public SetResponseTimeCmd setResponseTimeCmd (IAcmeComponent client, float rt) { - assert client.declaresType ("ClientT"); - if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetResponseTimeCmd ((AcmeModelInstance) m_modelInstance, - client.getQualifiedName (), Float.toString (rt)); - } - - public SetLoadCmd setLoadCmd (IAcmeComponent server, float load) { - assert server.declaresType ("ServerT") || server.declaresType ("ProxyT"); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetLoadCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - Float.toString (load)); - } - - public SetLatencyRateCmd setLatencyRateCmd (IAcmeConnector conn, float latencyRate) { - assert conn.declaresType ("HttpConnT"); - if (ModelHelper.getAcmeSystem (conn) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetLatencyRateCmd ((AcmeModelInstance) m_modelInstance, conn.getQualifiedName (), - Float.toString (latencyRate)); - } - - public SetLastPageHitCmd setLastPageHitCmd (IAcmeComponent server, String page) { - assert server.declaresType ("ServerT") || server.declaresType ("ProxyT"); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetLastPageHitCmd ((AcmeModelInstance) m_modelInstance, - server.getQualifiedName (), page); - } - - public SetClientRequestRateCmd setClientRequestRateCmd (IAcmeComponent client, float reqRate) { - Ensure.is_true (client.declaresType ("ClientT")); - if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetClientRequestRateCmd ((AcmeModelInstance) m_modelInstance, - client.getQualifiedName (), Float.toString (reqRate)); - } - - public SetByteServiceRateCmd setByteServiceRateCmd (IAcmeComponent server, float load) { - assert server.declaresType ("ServerT") || server.declaresType ("ProxyT"); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetByteServiceRateCmd ((AcmeModelInstance) m_modelInstance, - server.getQualifiedName (), - Float.toString (load)); - } - - public SetReqServiceRateCmd setReqServiceRateCmd (IAcmeComponent server, float load) { - assert server.declaresType ("ServerT") || server.declaresType ("ProxyT"); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetReqServiceRateCmd ((AcmeModelInstance) m_modelInstance, - server.getQualifiedName (), - Float.toString (load)); - } - - - public SetLatencyCmd setLatencyCmd (IAcmeConnector httpConn, float latency) { - assert httpConn.declaresType ("HttpConnT"); - if (ModelHelper.getAcmeSystem (httpConn) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetLatencyCmd ((AcmeModelInstance) m_modelInstance, httpConn.getQualifiedName (), - Float.toString (latency)); - } - - public SetNumRedirectedRequestsCmd setNumRedirectedRequestsCmd (IAcmeConnector httpConn, float serviceRate) { - assert httpConn.declaresType ("HttpConnT"); - if (ModelHelper.getAcmeSystem (httpConn) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetNumRedirectedRequestsCmd ((AcmeModelInstance) m_modelInstance, - httpConn.getQualifiedName (), - Float.toString (serviceRate)); - } - - public SetNumRequestsClientErrorCmd setNumRequestsClientErrorCmd (IAcmeConnector httpConn, float serviceRate) { - assert httpConn.declaresType ("HttpConnT"); - if (ModelHelper.getAcmeSystem (httpConn) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetNumRequestsClientErrorCmd ((AcmeModelInstance) m_modelInstance, - httpConn.getQualifiedName (), - Float.toString (serviceRate)); - } - - public SetNumRequestsServerErrorCmd setNumRequestsServerErrorCmd (IAcmeConnector httpConn, float serviceRate) { - assert httpConn.declaresType ("HttpConnT"); - if (ModelHelper.getAcmeSystem (httpConn) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetNumRequestsServerErrorCmd ((AcmeModelInstance) m_modelInstance, - httpConn.getQualifiedName (), - Float.toString (serviceRate)); - } - - public SetNumSuccessfulRequestsCmd setNumSuccessfulRequestsCmd (IAcmeConnector httpConn, float serviceRate) { - assert httpConn.declaresType ("HttpConnT"); - if (ModelHelper.getAcmeSystem (httpConn) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetNumSuccessfulRequestsCmd ((AcmeModelInstance) m_modelInstance, - httpConn.getQualifiedName (), - Float.toString (serviceRate)); - } - - public SetCaptchaEnabledCmd setCaptchaEnabledCmd (IAcmeComponent lb, boolean enabled) { - assert lb.declaresType ("ProxyT"); - if (ModelHelper.getAcmeSystem (lb) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetCaptchaEnabledCmd ((AcmeModelInstance) m_modelInstance, - lb.getQualifiedName (), - Boolean.toString (enabled)); - } - - public SetBlackholedCmd setBlackholedCmd (IAcmeComponent server, Set blackholdIps) { - assert server.declaresType ("BlackholerT"); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - StringBuilder sb = new StringBuilder (); - if (!blackholdIps.isEmpty ()) { - for (String ip : blackholdIps) { - sb.append (ip); - sb.append (","); - } - sb.deleteCharAt (sb.length () - 1); - } - return new SetBlackholedCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - sb.toString ()); - } - - public SetThrottledCmd setThrottledCmd (IAcmeComponent server, Set throttledIPs) { - isTrue ("Server should declare the type 'ThrottlerT'", server.declaresType ("ThrottlerT")); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - StringBuilder sb = new StringBuilder (); - if (!throttledIPs.isEmpty ()) { - for (String ip : throttledIPs) { - sb.append (ip); - sb.append (","); - } - sb.deleteCharAt (sb.length () - 1); - } - return new SetThrottledCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - sb.toString ()); - } - - public ForceReauthenticationCmd forceReauthenticationCmd (IAcmeComponent server) { - isTrue ("server should declare the type 'ServerT'", server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new ForceReauthenticationCmd ((AcmeModelInstance) m_modelInstance, - server.getQualifiedName ()); - } - - public SetMaliciousnessCmd setMaliciousnessCmd (IAcmeComponent client, float maliciousness) { - Ensure.is_true (client.declaresType ("PotentiallyMaliciousT")); - if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetMaliciousnessCmd ((AcmeModelInstance) m_modelInstance, - client.getQualifiedName (), - Float.toString (maliciousness)); - } - - public NewServerCmd connectNewServerCmd (IAcmeComponent proxy, - String name, - String deploymentLocation, - String port) { - assert proxy.declaresType ("ProxyT"); - if (ModelHelper.getAcmeSystem (proxy) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new NewServerCmd ((AcmeModelInstance) m_modelInstance, proxy.getQualifiedName (), - name, - deploymentLocation, port); - } - - public RemoveServerCmd deleteServerCmd (IAcmeComponent server) { - assert server.declaresType ("ServerT"); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ("Cannot delete a server that is not part of this model"); - return new RemoveServerCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName ()); - } - - public EnableServerCmd enableServerCmd (IAcmeComponent server, boolean enabled) { - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new EnableServerCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - Boolean.toString (enabled)); - } - - public SetFidelityCmd setFidelityCmd (IAcmeComponent server, int fidelity) { - Ensure.is_true (server.declaresType ("ServerT")); - if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetFidelityCmd ((AcmeModelInstance) m_modelInstance, server.getQualifiedName (), - Integer.toString (fidelity)); - } - - public SetCaptchaResponseCmd setCaptchaResponseCmd (IAcmeComponent client, int response) { - Ensure.is_true (client.declaresType ("CaptchaHandlerT")); - if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetCaptchaResponseCmd ((AcmeModelInstance) m_modelInstance, - client.getQualifiedName (), - Integer.toString (response)); - } - - public SetAuthenticationResponseCmd setAuthenticationResponseCmd (IAcmeComponent client, int response) { - Ensure.is_true (client.declaresType ("AuthenticationHandlerT")); - if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ( - "Cannot create a command for a component that is not part of the system"); - return new SetAuthenticationResponseCmd ((AcmeModelInstance) m_modelInstance, - client.getQualifiedName (), Integer.toString (response)); - } - - public AddClientCmd addClientCmd (IAcmeSystem sys, IAcmeComponent lb, String deploymentLocation) { - Ensure.is_true (lb.declaresType ("ProxyT")); - if (ModelHelper.getAcmeSystem (lb) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ( - "Cannot create a command for a new client that is not part of the system"); - return new AddClientCmd ((AcmeModelInstance) m_modelInstance, sys.getQualifiedName (), - lb.getQualifiedName (), - deploymentLocation); - } - - public RemoveClientCmd deleteClientCmd (IAcmeSystem sys, IAcmeComponent client) { - assert client.declaresType ("ClientT"); - if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) - throw new IllegalArgumentException ("Cannot delete a server that is not part of this model"); - return new RemoveClientCmd ((AcmeModelInstance) m_modelInstance, sys.getQualifiedName (), - client.getQualifiedName ()); - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import incubator.pval.Ensure; +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.IAcmeConnector; +import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.ModelsManager; +import org.sa.rainbow.model.acme.AcmeModelCommandFactory; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.io.InputStream; +import java.util.Set; + +import static incubator.pval.Ensure.isTrue; + +public class ZNNCommandFactory extends AcmeModelCommandFactory { + + + private static final String CREATE_DISCONNECTED_SERVER_CMD = "createDisconnectedServer"; + private static final String CONNECT_SERVER_CMD = "connectServer"; + private static final String SET_SYSTEM_PROPERTIES_CMD = "setSystemProperties"; + private static final String DELETE_CLIENT_CMD = "DeleteClient"; + private static final String ADD_CLIENT_CMD = "AddClient"; + private static final String SET_AUTHENTICATION_RESPONSE_CMD = "SetAuthenticationResponse"; + private static final String SET_CAPTCHA_RESPONSE_CMD = "SetCaptchaResponse"; + private static final String FORCE_REAUTHENTICATION_CMD = "forceReauthentication"; + private static final String SET_THROTTLED_CMD = "SetThrottled"; + private static final String SET_FIDELITY_CMD = "SetFidelity"; + private static final String ENABLE_SERVER_CMD = "EnableServer"; + private static final String SET_CLIENT_REQUEST_RATE_CMD = "SetClientRequestRate"; + private static final String SET_MALICIOUSNESS_CMD = "SetMaliciousness"; + private static final String SET_CAPTCHA_ENABLED_CMD = "SetCaptchaEnabled"; + private static final String SET_BLACKHOLED_CMD = "SetBlackholed"; + private static final String SET_NUM_SUCCESSFUL_REQUESTS_CMD = "SetNumSuccessfulRequests"; + private static final String SET_NUM_REQUESTS_SERVER_ERROR_CMD = "SetNumRequestsServerError"; + private static final String SET_NUM_REQUESTS_CLIENT_ERROR_CMD = "setNumRequestsClientError"; + private static final String SET_NUM_REDIRECTED_REQUESTS_CMD = "setNumRedirectedRequests"; + private static final String SET_LAST_PAGE_HIT_CMD = "setLastPageHit"; + private static final String SET_LATENCY_CMD = "setLatency"; + private static final String SET_LATENCY_RATE_CMD = "setLatencyRate"; + private static final String SET_BYTE_SERVICE_RATE_CMD = "setByteServiceRate"; + private static final String SET_REQ_SERVICE_RATE_CMD = "setReqServiceRate"; + private static final String DELETE_SERVER_CMD = "deleteServer"; + private static final String CONNECT_NEW_SERVER_CMD = "connectNewServer"; + private static final String SET_LOAD_CMD = "setLoad"; + private static final String SET_RESPONSE_TIME_CMD = "setResponseTime"; + + @LoadOperation + public static ZNNLoadModelCommand loadCommand (ModelsManager modelsManager, + String modelName, + InputStream stream, + String source) { + return new ZNNLoadModelCommand (modelName, modelsManager, stream, source); + } + + public ZNNCommandFactory (AcmeModelInstance modelInstance) throws RainbowException { + super (modelInstance); + } + + @Operation(name=CREATE_DISCONNECTED_SERVER_CMD) + public CreateDisconnectedServerCmd createDiconnectedServer (IAcmeSystem system, String name) { + if (ModelHelper.getAcmeSystem (system) != m_modelInstance.getModelInstance ()) { + throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); + } + return new CreateDisconnectedServerCmd (CREATE_DISCONNECTED_SERVER_CMD, (AcmeModelInstance) m_modelInstance, system.getName (), name); + } + + @Operation(name=CONNECT_SERVER_CMD) + public ConnectServerCmd connectServer (IAcmeComponent lb, String name, String deploymentLocation, + String port) { + if (ModelHelper.getAcmeSystem (lb) != m_modelInstance.getModelInstance ()) { + throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); + } + return new ConnectServerCmd (CONNECT_SERVER_CMD, (AcmeModelInstance) m_modelInstance, lb.getQualifiedName (), name, + deploymentLocation, port); + } + + @Operation(name=SET_SYSTEM_PROPERTIES_CMD) + public SetSystemPropertiesCmd setSystemProperties (IAcmeSystem sys, float avgRt, float perMalicious, boolean + highResponseTime, boolean aboveMalicious) { + if (ModelHelper.getAcmeSystem (sys) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ("Cannot create a command for a system that is not part of the system"); + return new SetSystemPropertiesCmd (SET_SYSTEM_PROPERTIES_CMD,(AcmeModelInstance) m_modelInstance, sys.getQualifiedName (), Float + .toString (avgRt), Float.toString (perMalicious), Boolean.toString (highResponseTime), Boolean + .toString (aboveMalicious)); + } + + @Operation(name=SET_RESPONSE_TIME_CMD) + public SetResponseTimeCmd setResponseTimeCmd (IAcmeComponent client, float rt) { + assert client.declaresType ("ClientT"); + if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetResponseTimeCmd (SET_RESPONSE_TIME_CMD, (AcmeModelInstance) m_modelInstance, + client.getQualifiedName (), Float.toString (rt)); + } + + @Operation(name=SET_LOAD_CMD) + public SetLoadCmd setLoadCmd (IAcmeComponent server, float load) { + assert server.declaresType ("ServerT") || server.declaresType ("ProxyT"); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetLoadCmd (SET_LOAD_CMD, (AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + Float.toString (load)); + } + + @Operation(name=SET_LATENCY_RATE_CMD) + public SetLatencyRateCmd setLatencyRateCmd (IAcmeConnector conn, float latencyRate) { + assert conn.declaresType ("HttpConnT"); + if (ModelHelper.getAcmeSystem (conn) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetLatencyRateCmd (SET_LATENCY_RATE_CMD, (AcmeModelInstance) m_modelInstance, conn.getQualifiedName (), + Float.toString (latencyRate)); + } + + @Operation(name=SET_LAST_PAGE_HIT_CMD) + public SetLastPageHitCmd setLastPageHitCmd (IAcmeComponent server, String page) { + assert server.declaresType ("ServerT") || server.declaresType ("ProxyT"); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetLastPageHitCmd (SET_LAST_PAGE_HIT_CMD, (AcmeModelInstance) m_modelInstance, + server.getQualifiedName (), page); + } + + @Operation(name=SET_CLIENT_REQUEST_RATE_CMD) + public SetClientRequestRateCmd setClientRequestRateCmd (IAcmeComponent client, float reqRate) { + Ensure.is_true (client.declaresType ("ClientT")); + if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetClientRequestRateCmd (SET_CLIENT_REQUEST_RATE_CMD, (AcmeModelInstance) m_modelInstance, + client.getQualifiedName (), Float.toString (reqRate)); + } + + @Operation(name=SET_BYTE_SERVICE_RATE_CMD) + public SetByteServiceRateCmd setByteServiceRateCmd (IAcmeComponent server, float load) { + assert server.declaresType ("ServerT") || server.declaresType ("ProxyT"); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetByteServiceRateCmd (SET_BYTE_SERVICE_RATE_CMD, (AcmeModelInstance) m_modelInstance, + server.getQualifiedName (), + Float.toString (load)); + } + + @Operation(name=SET_REQ_SERVICE_RATE_CMD) + public SetReqServiceRateCmd setReqServiceRateCmd (IAcmeComponent server, float load) { + assert server.declaresType ("ServerT") || server.declaresType ("ProxyT"); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetReqServiceRateCmd (SET_REQ_SERVICE_RATE_CMD, (AcmeModelInstance) m_modelInstance, + server.getQualifiedName (), + Float.toString (load)); + } + + @Operation(name=SET_LATENCY_CMD) + public SetLatencyCmd setLatencyCmd (IAcmeConnector httpConn, float latency) { + assert httpConn.declaresType ("HttpConnT"); + if (ModelHelper.getAcmeSystem (httpConn) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetLatencyCmd (SET_LATENCY_CMD, (AcmeModelInstance) m_modelInstance, httpConn.getQualifiedName (), + Float.toString (latency)); + } + + @Operation(name=SET_NUM_REDIRECTED_REQUESTS_CMD) + public SetNumRedirectedRequestsCmd setNumRedirectedRequestsCmd (IAcmeConnector httpConn, float serviceRate) { + assert httpConn.declaresType ("HttpConnT"); + if (ModelHelper.getAcmeSystem (httpConn) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetNumRedirectedRequestsCmd (SET_NUM_REDIRECTED_REQUESTS_CMD, (AcmeModelInstance) m_modelInstance, + httpConn.getQualifiedName (), + Float.toString (serviceRate)); + } + + @Operation(name=SET_NUM_REQUESTS_CLIENT_ERROR_CMD) + public SetNumRequestsClientErrorCmd setNumRequestsClientErrorCmd (IAcmeConnector httpConn, float serviceRate) { + assert httpConn.declaresType ("HttpConnT"); + if (ModelHelper.getAcmeSystem (httpConn) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetNumRequestsClientErrorCmd (SET_NUM_REQUESTS_CLIENT_ERROR_CMD, (AcmeModelInstance) m_modelInstance, + httpConn.getQualifiedName (), + Float.toString (serviceRate)); + } + + @Operation(name=SET_NUM_REQUESTS_SERVER_ERROR_CMD) + public SetNumRequestsServerErrorCmd setNumRequestsServerErrorCmd (IAcmeConnector httpConn, float serviceRate) { + assert httpConn.declaresType ("HttpConnT"); + if (ModelHelper.getAcmeSystem (httpConn) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetNumRequestsServerErrorCmd (SET_NUM_REQUESTS_SERVER_ERROR_CMD, (AcmeModelInstance) m_modelInstance, + httpConn.getQualifiedName (), + Float.toString (serviceRate)); + } + + @Operation(name=SET_NUM_SUCCESSFUL_REQUESTS_CMD) + public SetNumSuccessfulRequestsCmd setNumSuccessfulRequestsCmd (IAcmeConnector httpConn, float serviceRate) { + assert httpConn.declaresType ("HttpConnT"); + if (ModelHelper.getAcmeSystem (httpConn) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetNumSuccessfulRequestsCmd (SET_NUM_SUCCESSFUL_REQUESTS_CMD, (AcmeModelInstance) m_modelInstance, + httpConn.getQualifiedName (), + Float.toString (serviceRate)); + } + + @Operation(name=SET_CAPTCHA_ENABLED_CMD) + public SetCaptchaEnabledCmd setCaptchaEnabledCmd (IAcmeComponent lb, boolean enabled) { + assert lb.declaresType ("ProxyT"); + if (ModelHelper.getAcmeSystem (lb) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetCaptchaEnabledCmd (SET_CAPTCHA_ENABLED_CMD, (AcmeModelInstance) m_modelInstance, + lb.getQualifiedName (), + Boolean.toString (enabled)); + } + + @Operation(name=SET_BLACKHOLED_CMD) + public SetBlackholedCmd setBlackholedCmd (IAcmeComponent server, Set blackholdIps) { + assert server.declaresType ("BlackholerT"); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + StringBuilder sb = new StringBuilder (); + if (!blackholdIps.isEmpty ()) { + for (String ip : blackholdIps) { + sb.append (ip); + sb.append (","); + } + sb.deleteCharAt (sb.length () - 1); + } + return new SetBlackholedCmd (SET_BLACKHOLED_CMD, (AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + sb.toString ()); + } + + @Operation(name=SET_THROTTLED_CMD) + public SetThrottledCmd setThrottledCmd (IAcmeComponent server, Set throttledIPs) { + isTrue ("Server should declare the type 'ThrottlerT'", server.declaresType ("ThrottlerT")); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + StringBuilder sb = new StringBuilder (); + if (!throttledIPs.isEmpty ()) { + for (String ip : throttledIPs) { + sb.append (ip); + sb.append (","); + } + sb.deleteCharAt (sb.length () - 1); + } + return new SetThrottledCmd (SET_THROTTLED_CMD, (AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + sb.toString ()); + } + + @Operation(name=FORCE_REAUTHENTICATION_CMD) + public ForceReauthenticationCmd forceReauthenticationCmd (IAcmeComponent server) { + isTrue ("server should declare the type 'ServerT'", server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new ForceReauthenticationCmd (FORCE_REAUTHENTICATION_CMD, (AcmeModelInstance) m_modelInstance, + server.getQualifiedName ()); + } + + @Operation(name=SET_MALICIOUSNESS_CMD) + public SetMaliciousnessCmd setMaliciousnessCmd (IAcmeComponent client, float maliciousness) { + Ensure.is_true (client.declaresType ("PotentiallyMaliciousT")); + if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetMaliciousnessCmd (SET_MALICIOUSNESS_CMD, (AcmeModelInstance) m_modelInstance, + client.getQualifiedName (), + Float.toString (maliciousness)); + } + + @Operation(name=CONNECT_NEW_SERVER_CMD) + public NewServerCmd connectNewServerCmd (IAcmeComponent proxy, + String name, + String deploymentLocation, + String port) { + assert proxy.declaresType ("ProxyT"); + if (ModelHelper.getAcmeSystem (proxy) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new NewServerCmd (CONNECT_NEW_SERVER_CMD, (AcmeModelInstance) m_modelInstance, proxy.getQualifiedName (), + name, + deploymentLocation, port); + } + + @Operation(name=DELETE_SERVER_CMD) + public RemoveServerCmd deleteServerCmd (IAcmeComponent server) { + assert server.declaresType ("ServerT"); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ("Cannot delete a server that is not part of this model"); + return new RemoveServerCmd (DELETE_SERVER_CMD, (AcmeModelInstance) m_modelInstance, server.getQualifiedName ()); + } + + @Operation(name=ENABLE_SERVER_CMD) + public EnableServerCmd enableServerCmd (IAcmeComponent server, boolean enabled) { + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new EnableServerCmd (ENABLE_SERVER_CMD, (AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + Boolean.toString (enabled)); + } + + public SetFidelityCmd setFidelityCmd (IAcmeComponent server, int fidelity) { + Ensure.is_true (server.declaresType ("ServerT")); + if (ModelHelper.getAcmeSystem (server) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetFidelityCmd (ENABLE_SERVER_CMD, (AcmeModelInstance) m_modelInstance, server.getQualifiedName (), + Integer.toString (fidelity)); + } + + @Operation(name=SET_CAPTCHA_RESPONSE_CMD) + public SetCaptchaResponseCmd setCaptchaResponseCmd (IAcmeComponent client, int response) { + Ensure.is_true (client.declaresType ("CaptchaHandlerT")); + if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetCaptchaResponseCmd (SET_CAPTCHA_RESPONSE_CMD, (AcmeModelInstance) m_modelInstance, + client.getQualifiedName (), + Integer.toString (response)); + } + + @Operation(name=SET_AUTHENTICATION_RESPONSE_CMD) + public SetAuthenticationResponseCmd setAuthenticationResponseCmd (IAcmeComponent client, int response) { + Ensure.is_true (client.declaresType ("AuthenticationHandlerT")); + if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ( + "Cannot create a command for a component that is not part of the system"); + return new SetAuthenticationResponseCmd (SET_AUTHENTICATION_RESPONSE_CMD, (AcmeModelInstance) m_modelInstance, + client.getQualifiedName (), Integer.toString (response)); + } + + @Operation(name=ADD_CLIENT_CMD) + public AddClientCmd addClientCmd (IAcmeSystem sys, IAcmeComponent lb, String deploymentLocation) { + Ensure.is_true (lb.declaresType ("ProxyT")); + if (ModelHelper.getAcmeSystem (lb) != m_modelInstance.getModelInstance ()) throw new IllegalArgumentException ( + "Cannot create a command for a new client that is not part of the system"); + return new AddClientCmd (ADD_CLIENT_CMD, (AcmeModelInstance) m_modelInstance, sys.getQualifiedName (), + lb.getQualifiedName (), + deploymentLocation); + } + + @Operation(name=DELETE_CLIENT_CMD) + public RemoveClientCmd deleteClientCmd (IAcmeSystem sys, IAcmeComponent client) { + assert client.declaresType ("ClientT"); + if (ModelHelper.getAcmeSystem (client) != m_modelInstance.getModelInstance ()) + throw new IllegalArgumentException ("Cannot delete a server that is not part of this model"); + return new RemoveClientCmd (DELETE_CLIENT_CMD, (AcmeModelInstance) m_modelInstance, sys.getQualifiedName (), + client.getQualifiedName ()); + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNConstants.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNConstants.java index 32e7745de..06fe2f687 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNConstants.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNConstants.java @@ -1,19 +1,19 @@ -package org.sa.rainbow.model.acme.znn.commands; - -import java.util.Collections; -import java.util.List; - -/** - * Created by schmerl on 2/4/2016. - */ -public class ZNNConstants { - public static final String SERVER_T_NAME = "ServerT"; - public static final String PROXY_CONN_T_NAME = "ProxyConnT"; - public static final String PROXY_FORWARD_PORT_T_NAME = "ProxyForwardPortT"; - public static final String HTTP_PORT_T_NAME = "HttpPortT"; - - static final List SERVER_TYPE = Collections.singletonList (SERVER_T_NAME); - static final List HTTP_CONN_T = Collections.singletonList (PROXY_CONN_T_NAME); - static final List PROXY_FORWARD_PORT = Collections.singletonList (PROXY_FORWARD_PORT_T_NAME); - static final List HTTP_PORT = Collections.singletonList (HTTP_PORT_T_NAME); -} +package org.sa.rainbow.model.acme.znn.commands; + +import java.util.Collections; +import java.util.List; + +/** + * Created by schmerl on 2/4/2016. + */ +public class ZNNConstants { + public static final String SERVER_T_NAME = "ServerT"; + public static final String PROXY_CONN_T_NAME = "ProxyConnT"; + public static final String PROXY_FORWARD_PORT_T_NAME = "ProxyForwardPortT"; + public static final String HTTP_PORT_T_NAME = "HttpPortT"; + + static final List SERVER_TYPE = Collections.singletonList (SERVER_T_NAME); + static final List HTTP_CONN_T = Collections.singletonList (PROXY_CONN_T_NAME); + static final List PROXY_FORWARD_PORT = Collections.singletonList (PROXY_FORWARD_PORT_T_NAME); + static final List HTTP_PORT = Collections.singletonList (HTTP_PORT_T_NAME); +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNLoadModelCommand.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNLoadModelCommand.java index de548ccdd..c8c71e790 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNLoadModelCommand.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/model/acme/znn/commands/ZNNLoadModelCommand.java @@ -1,148 +1,148 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.model.acme.znn.commands; - -import org.acmestudio.acme.core.exception.AcmeException; -import org.acmestudio.acme.core.exception.AcmeVisitorException; -import org.acmestudio.acme.core.resource.IAcmeResource; -import org.acmestudio.acme.core.resource.ParsingFailureException; -import org.acmestudio.acme.core.type.IAcmeStringValue; -import org.acmestudio.acme.element.AbstractAcmeElementVisitor; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmePropertyCommand; -import org.acmestudio.acme.model.util.core.UMStringValue; -import org.acmestudio.standalone.resource.StandaloneResourceProvider; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.IModelsManager; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; -import org.sa.rainbow.model.acme.znn.ZNNModelUpdateOperatorsImpl; -import org.sa.rainbow.util.Util; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.LinkedList; -import java.util.List; - -public class ZNNLoadModelCommand extends AbstractLoadModelCmd { - - public class AcmePropertySubstitutionVisitor extends AbstractAcmeElementVisitor { - - protected List> m_commands = new LinkedList<> (); - - public IAcmeCommand getCommand () { - if (m_commands.isEmpty ()) return null; - if (m_commands.size () == 1) return m_commands.get (0); - return m_commands.get (0).getCommandFactory ().compoundCommand (m_commands); - } - - @Override - public Object visitIAcmeProperty (IAcmeProperty property, Object data) throws AcmeVisitorException { - if (property.getValue () instanceof IAcmeStringValue) { - IAcmeStringValue val = (IAcmeStringValue )property.getValue (); - String origVal = val.getValue (); - String newVal = Util.evalTokens (origVal); - if (!newVal.equals (origVal)) { - IAcmePropertyCommand cmd = property.getCommandFactory ().propertyValueSetCommand (property, - new UMStringValue (newVal)); - m_commands.add (cmd); - } - } - return data; - } - } - - private InputStream m_inputStream; - private String m_systemName; - private ZNNModelUpdateOperatorsImpl m_result; - - public ZNNLoadModelCommand (String systemName, IModelsManager mm, InputStream is, String source) { - super ("loadZNNModel", mm, systemName, is, source); - m_systemName = systemName; - m_inputStream = is; - } - - @Override - public ModelReference getModelReference () { - return new ModelReference (m_systemName, "Acme"); - } - - - @Override - protected void subExecute () throws RainbowException { - try { - IAcmeResource resource = StandaloneResourceProvider.instance () - .acmeResourceForObject ( - new File (getOriginalSource ())); - m_result = new ZNNModelUpdateOperatorsImpl (resource.getModel ().getSystem (m_systemName), - getOriginalSource ()); - - // Do property substitution - try { - AcmePropertySubstitutionVisitor visitor = new AcmePropertySubstitutionVisitor (); - m_result.getModelInstance ().visit (visitor, null); - IAcmeCommand cmd = visitor.getCommand (); - cmd.execute (); - } - catch (IllegalStateException | AcmeException e) { - e.printStackTrace (); - } - - doPostExecute (); - } - catch (ParsingFailureException | IOException e) { - throw new RainbowException (e); - } - } - - @Override - protected void subRedo () throws RainbowException { - doPostExecute (); - } - - @Override - protected void subUndo () throws RainbowException { - doPostUndo (); - } - - @Override - public IModelInstance getResult () { - return m_result; - } - - @Override - public String getName () { - return "LoadZNNModel"; - } - - @Override - protected boolean checkModelValidForCommand (Object model) { - return true; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.model.acme.znn.commands; + +import org.acmestudio.acme.core.exception.AcmeException; +import org.acmestudio.acme.core.exception.AcmeVisitorException; +import org.acmestudio.acme.core.resource.IAcmeResource; +import org.acmestudio.acme.core.resource.ParsingFailureException; +import org.acmestudio.acme.core.type.IAcmeStringValue; +import org.acmestudio.acme.element.AbstractAcmeElementVisitor; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmePropertyCommand; +import org.acmestudio.acme.model.util.core.UMStringValue; +import org.acmestudio.standalone.resource.StandaloneResourceProvider; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelsManager; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd; +import org.sa.rainbow.model.acme.znn.ZNNModelUpdateOperatorsImpl; +import org.sa.rainbow.util.Util; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedList; +import java.util.List; + +public class ZNNLoadModelCommand extends AbstractLoadModelCmd { + + public class AcmePropertySubstitutionVisitor extends AbstractAcmeElementVisitor { + + protected List> m_commands = new LinkedList<> (); + + public IAcmeCommand getCommand () { + if (m_commands.isEmpty ()) return null; + if (m_commands.size () == 1) return m_commands.get (0); + return m_commands.get (0).getCommandFactory ().compoundCommand (m_commands); + } + + @Override + public Object visitIAcmeProperty (IAcmeProperty property, Object data) throws AcmeVisitorException { + if (property.getValue () instanceof IAcmeStringValue) { + IAcmeStringValue val = (IAcmeStringValue )property.getValue (); + String origVal = val.getValue (); + String newVal = Util.evalTokens (origVal); + if (!newVal.equals (origVal)) { + IAcmePropertyCommand cmd = property.getCommandFactory ().propertyValueSetCommand (property, + new UMStringValue (newVal)); + m_commands.add (cmd); + } + } + return data; + } + } + + private InputStream m_inputStream; + private String m_systemName; + private ZNNModelUpdateOperatorsImpl m_result; + + public ZNNLoadModelCommand (String systemName, IModelsManager mm, InputStream is, String source) { + super ("loadZNNModel", mm, systemName, is, source); + m_systemName = systemName; + m_inputStream = is; + } + + @Override + public ModelReference getModelReference () { + return new ModelReference (m_systemName, "Acme"); + } + + + @Override + protected void subExecute () throws RainbowException { + try { + IAcmeResource resource = StandaloneResourceProvider.instance () + .acmeResourceForObject ( + new File (getOriginalSource ())); + m_result = new ZNNModelUpdateOperatorsImpl (resource.getModel ().getSystem (m_systemName), + getOriginalSource ()); + + // Do property substitution + try { + AcmePropertySubstitutionVisitor visitor = new AcmePropertySubstitutionVisitor (); + m_result.getModelInstance ().visit (visitor, null); + IAcmeCommand cmd = visitor.getCommand (); + cmd.execute (); + } + catch (IllegalStateException | AcmeException e) { + e.printStackTrace (); + } + + doPostExecute (); + } + catch (ParsingFailureException | IOException e) { + throw new RainbowException (e); + } + } + + @Override + protected void subRedo () throws RainbowException { + doPostExecute (); + } + + @Override + protected void subUndo () throws RainbowException { + doPostUndo (); + } + + @Override + public IModelInstance getResult () { + return m_result; + } + + @Override + public String getName () { + return "LoadZNNModel"; + } + + @Override + protected boolean checkModelValidForCommand (Object model) { + return true; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ApacheTopGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ApacheTopGauge.java index c6c4ac6b6..3dc5cd193 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ApacheTopGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ApacheTopGauge.java @@ -1,186 +1,186 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created November 1, 2006. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Gauge for consuming Apache Top's monitoring output. - * - * This is no longer used in the experiments. - * - * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) - */ -public class ApacheTopGauge extends RegularPatternGauge { - - public static final String NAME = "G - Apache Top"; - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "reqServiceRate", - "byteServiceRate", - "numReqsSuccess", - "numReqsRedirect", - "numReqsClientError", - "numReqsServerError", - "pageHit" - }; - private static final String LAST_HIT = "LAST_HIT"; - private static final String RUNTIME = "RUNTIME"; - private static final String CURTIME = "CURTIME"; - private static final String ALL_HITS = "ALL_HITS"; - private static final String RECENT_HITS = "RECENT_HITS"; - private static final String ALL_RC = "ALL_RC"; - private static final String RECENT_RC = "RECENT_RC"; - private static final String RC = "RC"; - private static final String HIT = "HIT"; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public ApacheTopGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern(LAST_HIT, Pattern.compile("last hit: (\\d{2}+):(\\d{2}+):(\\d{2}+)")); - addPattern(RUNTIME, Pattern.compile("atop runtime: (\\d{2}+) days, (\\d{2}+):(\\d{2}+):(\\d{2}+)")); - addPattern(CURTIME, Pattern.compile("curtime: (\\d{2}+):(\\d{2}+):(\\d{2}+)")); - addPattern(ALL_HITS, Pattern.compile("All: (\\d{12}+) reqs \\(([0-9.]{6}+)/sec\\) ([0-9.]{11}+)(\\w) \\(([0-9.]{7}+)(\\w)/sec\\) ([0-9.]{7}+)(\\w)/req")); - addPattern(RECENT_HITS, Pattern.compile("R\\((\\d{3}+)s\\): (\\d{7}+) reqs \\(([0-9.]{6}+)/sec\\) ([0-9.]{11}+)(\\w) \\(([0-9.]{7}+)(\\w)/sec\\) ([0-9.]{7}+)(\\w)/req")); - addPattern(ALL_RC, Pattern.compile("All: 2xx: (\\d{7}+) \\(([0-9.]{4}+)%\\) 3xx: (\\d{7}+) \\(([0-9.]{4}+)%\\) 4xx: (\\d{5}+) \\(([0-9.]{4}+)%\\) 5xx: (\\d{5}+) \\(([0-9.]{4}+)%\\)")); - addPattern(RECENT_RC, Pattern.compile("R: 2xx: (\\d{7}+) \\(([0-9.]{4}+)%\\) 3xx: (\\d{7}+) \\(([0-9.]{4}+)%\\) 4xx: (\\d{5}+) \\(([0-9.]{4}+)%\\) 5xx: (\\d{5}+) \\(([0-9.]{4}+)%\\)")); - addPattern(RC, Pattern.compile("R: (\\d{5}+) ([0-9.]{5}+) ([0-9.]{5}+) ([0-9.]{4}+) (.*+)")); - addPattern(HIT, Pattern.compile("H: (\\d{5}+) ([0-9.]{5}+) ([0-9.]{5}+) ([0-9.]{4}+) (.+?)( \\[(.+)\\])?")); - } - - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - //log(" - line matches pattern \"" + p + "\" with " + m.groupCount() + " groups"); - if (matchName == CURTIME) { - // should we remember the report time? - } else if (matchName == RECENT_HITS) { - // acquire the recent hits data - int numSecs = Integer.parseInt(m.group(1)); - int numReqs = Integer.parseInt(m.group(2)); - double numBytes = Double.parseDouble(m.group(4)); - char unit = m.group(5).charAt(0); - // convert to kBps - switch (unit) { - case 'G': - numBytes *= 1024; - // intentional fall thru - case 'M': - numBytes *= 1024; - // intentional fall thru - case 'K': - break; - case 'B': - numBytes /= 1024; - break; - } - if (numReqs > 0 && numBytes > 0) { - // update server comp in model with requests per sec - m_reportingPort.trace (getComponentType (), "Updating server prop using (sec,req,kBps) = (" + numSecs - + "," + numReqs + "," + numBytes + ")"); - // ZNewsSys.s0.reqServiceRate - IRainbowOperation reqServiceRateCmd = getCommand (valueNames[0]); - Map pMap = new HashMap<> (); - pMap.put (reqServiceRateCmd.getParameters ()[0], Double.toString ((double )numReqs / numSecs)); - issueCommand (reqServiceRateCmd, pMap); - // ZNewsSys.s0.byteServiceRate - IRainbowOperation byteServiceRateCmd = getCommand (valueNames[0]); - pMap = new HashMap<> (); - pMap.put (reqServiceRateCmd.getParameters ()[0], Double.toString (numBytes / numSecs)); - issueCommand (byteServiceRateCmd, pMap); - } - } else if (matchName == RECENT_RC) { - int num2x = Integer.parseInt(m.group(1)); - int num3x = Integer.parseInt(m.group(3)); - int num4x = Integer.parseInt(m.group(5)); - int num5x = Integer.parseInt(m.group(7)); - if (num2x + num3x + num4x + num5x > 0) { - // update http conn in model with requests per sec - m_reportingPort.trace (getComponentType (),"Updating server prop using (2xx,3xx,4xx,5xx) = (" - + num2x + "," + num3x + "," + num4x + "," + num5x + ")"); - // ZNewsSys.conn0.numReqsSuccess - - IRainbowOperation numReqsSuccessCmd = getCommand (valueNames[2]); - Map pMap = new HashMap<> (); - pMap.put (numReqsSuccessCmd.getParameters ()[0], Integer.toString (num2x)); - issueCommand (numReqsSuccessCmd, pMap); - IRainbowOperation numReqsRedirect = getCommand (valueNames[3]); - pMap = new HashMap<> (); - pMap.put (numReqsRedirect.getParameters ()[0], Integer.toString (num3x)); - issueCommand (numReqsRedirect, pMap); - IRainbowOperation numReqsClientError = getCommand (valueNames[4]); - pMap = new HashMap<> (); - pMap.put (numReqsClientError.getParameters ()[0], Integer.toString (num4x)); - issueCommand (numReqsClientError, pMap); - IRainbowOperation numReqsServerError = getCommand (valueNames[5]); - pMap = new HashMap<> (); - pMap.put (numReqsServerError.getParameters ()[0], Integer.toString (num5x)); - issueCommand (numReqsServerError, pMap); - - } - } else if (matchName == HIT) { - int hitCnt = Integer.parseInt(m.group(1)); -// double rps = Double.parseDouble(m.group(2)); - double kB = Double.parseDouble(m.group(3)); -// double kbps = Double.parseDouble(m.group(4)); - String uri = m.group(5); -// String ip = m.group(7); // 6th is the "optional" grouping - String hitStr = - "[ uri:string=\"" + uri + "\"; cnt:int=" + hitCnt - + "; kbytes:float=" + kB + "; ]"; - - IRainbowOperation lastPageHit = getCommand (valueNames[6]); - Map pMap = new HashMap<> (); - pMap.put (lastPageHit.getParameters ()[0], hitStr); - issueCommand (lastPageHit, pMap); - } - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Gauge for consuming Apache Top's monitoring output. + * + * This is no longer used in the experiments. + * + * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) + */ +public class ApacheTopGauge extends RegularPatternGauge { + + public static final String NAME = "G - Apache Top"; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "reqServiceRate", + "byteServiceRate", + "numReqsSuccess", + "numReqsRedirect", + "numReqsClientError", + "numReqsServerError", + "pageHit" + }; + private static final String LAST_HIT = "LAST_HIT"; + private static final String RUNTIME = "RUNTIME"; + private static final String CURTIME = "CURTIME"; + private static final String ALL_HITS = "ALL_HITS"; + private static final String RECENT_HITS = "RECENT_HITS"; + private static final String ALL_RC = "ALL_RC"; + private static final String RECENT_RC = "RECENT_RC"; + private static final String RC = "RC"; + private static final String HIT = "HIT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public ApacheTopGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern(LAST_HIT, Pattern.compile("last hit: (\\d{2}+):(\\d{2}+):(\\d{2}+)")); + addPattern(RUNTIME, Pattern.compile("atop runtime: (\\d{2}+) days, (\\d{2}+):(\\d{2}+):(\\d{2}+)")); + addPattern(CURTIME, Pattern.compile("curtime: (\\d{2}+):(\\d{2}+):(\\d{2}+)")); + addPattern(ALL_HITS, Pattern.compile("All: (\\d{12}+) reqs \\(([0-9.]{6}+)/sec\\) ([0-9.]{11}+)(\\w) \\(([0-9.]{7}+)(\\w)/sec\\) ([0-9.]{7}+)(\\w)/req")); + addPattern(RECENT_HITS, Pattern.compile("R\\((\\d{3}+)s\\): (\\d{7}+) reqs \\(([0-9.]{6}+)/sec\\) ([0-9.]{11}+)(\\w) \\(([0-9.]{7}+)(\\w)/sec\\) ([0-9.]{7}+)(\\w)/req")); + addPattern(ALL_RC, Pattern.compile("All: 2xx: (\\d{7}+) \\(([0-9.]{4}+)%\\) 3xx: (\\d{7}+) \\(([0-9.]{4}+)%\\) 4xx: (\\d{5}+) \\(([0-9.]{4}+)%\\) 5xx: (\\d{5}+) \\(([0-9.]{4}+)%\\)")); + addPattern(RECENT_RC, Pattern.compile("R: 2xx: (\\d{7}+) \\(([0-9.]{4}+)%\\) 3xx: (\\d{7}+) \\(([0-9.]{4}+)%\\) 4xx: (\\d{5}+) \\(([0-9.]{4}+)%\\) 5xx: (\\d{5}+) \\(([0-9.]{4}+)%\\)")); + addPattern(RC, Pattern.compile("R: (\\d{5}+) ([0-9.]{5}+) ([0-9.]{5}+) ([0-9.]{4}+) (.*+)")); + addPattern(HIT, Pattern.compile("H: (\\d{5}+) ([0-9.]{5}+) ([0-9.]{5}+) ([0-9.]{4}+) (.+?)( \\[(.+)\\])?")); + } + + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + //log(" - line matches pattern \"" + p + "\" with " + m.groupCount() + " groups"); + if (matchName == CURTIME) { + // should we remember the report time? + } else if (matchName == RECENT_HITS) { + // acquire the recent hits data + int numSecs = Integer.parseInt(m.group(1)); + int numReqs = Integer.parseInt(m.group(2)); + double numBytes = Double.parseDouble(m.group(4)); + char unit = m.group(5).charAt(0); + // convert to kBps + switch (unit) { + case 'G': + numBytes *= 1024; + // intentional fall thru + case 'M': + numBytes *= 1024; + // intentional fall thru + case 'K': + break; + case 'B': + numBytes /= 1024; + break; + } + if (numReqs > 0 && numBytes > 0) { + // update server comp in model with requests per sec + m_reportingPort.trace (getComponentType (), "Updating server prop using (sec,req,kBps) = (" + numSecs + + "," + numReqs + "," + numBytes + ")"); + // ZNewsSys.s0.reqServiceRate + IRainbowOperation reqServiceRateCmd = getCommand (valueNames[0]); + Map pMap = new HashMap<> (); + pMap.put (reqServiceRateCmd.getParameters ()[0], Double.toString ((double )numReqs / numSecs)); + issueCommand (reqServiceRateCmd, pMap); + // ZNewsSys.s0.byteServiceRate + IRainbowOperation byteServiceRateCmd = getCommand (valueNames[0]); + pMap = new HashMap<> (); + pMap.put (reqServiceRateCmd.getParameters ()[0], Double.toString (numBytes / numSecs)); + issueCommand (byteServiceRateCmd, pMap); + } + } else if (matchName == RECENT_RC) { + int num2x = Integer.parseInt(m.group(1)); + int num3x = Integer.parseInt(m.group(3)); + int num4x = Integer.parseInt(m.group(5)); + int num5x = Integer.parseInt(m.group(7)); + if (num2x + num3x + num4x + num5x > 0) { + // update http conn in model with requests per sec + m_reportingPort.trace (getComponentType (),"Updating server prop using (2xx,3xx,4xx,5xx) = (" + + num2x + "," + num3x + "," + num4x + "," + num5x + ")"); + // ZNewsSys.conn0.numReqsSuccess + + IRainbowOperation numReqsSuccessCmd = getCommand (valueNames[2]); + Map pMap = new HashMap<> (); + pMap.put (numReqsSuccessCmd.getParameters ()[0], Integer.toString (num2x)); + issueCommand (numReqsSuccessCmd, pMap); + IRainbowOperation numReqsRedirect = getCommand (valueNames[3]); + pMap = new HashMap<> (); + pMap.put (numReqsRedirect.getParameters ()[0], Integer.toString (num3x)); + issueCommand (numReqsRedirect, pMap); + IRainbowOperation numReqsClientError = getCommand (valueNames[4]); + pMap = new HashMap<> (); + pMap.put (numReqsClientError.getParameters ()[0], Integer.toString (num4x)); + issueCommand (numReqsClientError, pMap); + IRainbowOperation numReqsServerError = getCommand (valueNames[5]); + pMap = new HashMap<> (); + pMap.put (numReqsServerError.getParameters ()[0], Integer.toString (num5x)); + issueCommand (numReqsServerError, pMap); + + } + } else if (matchName == HIT) { + int hitCnt = Integer.parseInt(m.group(1)); +// double rps = Double.parseDouble(m.group(2)); + double kB = Double.parseDouble(m.group(3)); +// double kbps = Double.parseDouble(m.group(4)); + String uri = m.group(5); +// String ip = m.group(7); // 6th is the "optional" grouping + String hitStr = + "[ uri:string=\"" + uri + "\"; cnt:int=" + hitCnt + + "; kbytes:float=" + kB + "; ]"; + + IRainbowOperation lastPageHit = getCommand (valueNames[6]); + Map pMap = new HashMap<> (); + pMap.put (lastPageHit.getParameters ()[0], hitStr); + issueCommand (lastPageHit, pMap); + } + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/AuthenticationEnablementGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/AuthenticationEnablementGauge.java index 35ae94040..469384d4c 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/AuthenticationEnablementGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/AuthenticationEnablementGauge.java @@ -1,110 +1,110 @@ -package org.sa.rainbow.translator.znn.gauges; - -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Sets whether authentication has been enabled in ZNN. This information is reported by an authentication probe. The - * gauge issues the appropriate model command. - * - *

- * The command that is issued on the model is named "clientMgmt" and is mapped to the setAuthenticationResponse command. - * - *

- * The gauge type is as follows: - * - *

- *  AuthenticationEnablementGaugeT:
- *     commands:
- *       clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int)
- *     setupParams:
- *       targetIP:
- *         type: String
- *         default: "localhost"
- *       beaconPeriod:
- *         type: long
- *         default: 5000
- *       javaClass:
- *         type: String
- *         default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge"
- *     configParams:
- *       targetProbeType:
- *         type: String
- *         default: ~
- * 
- * - * @author Bradley Schmerl: schmerl - * - */ -public class AuthenticationEnablementGauge extends RegularPatternGauge { - - public static final String NAME = "G - Authentication Enablement"; - - private static final String OFF = "off"; - private static final String ON = "on"; - - public AuthenticationEnablementGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, - TypedAttribute modelDesc, List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern (ON, Pattern.compile ("^on$")); - addPattern (OFF, Pattern.compile ("^off$")); - } - - @Override - protected void doMatch (String matchName, Matcher m) { - boolean authenticationOff = OFF.equals (matchName); - if (authenticationOff) { - // Reset everything to unknown - List ops = new LinkedList<> (); - List> params = new LinkedList<> (); - - for (Entry entry : m_commands.entrySet ()) { - if (entry.getKey ().startsWith ("clientMgmt(")) { - IRainbowOperation op = entry.getValue (); - Map pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], "0"); - ops.add (op); - params.add (pMap); - } - } - - issueCommands (ops, params); - } - } - -} +package org.sa.rainbow.translator.znn.gauges; + +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Sets whether authentication has been enabled in ZNN. This information is reported by an authentication probe. The + * gauge issues the appropriate model command. + * + *

+ * The command that is issued on the model is named "clientMgmt" and is mapped to the setAuthenticationResponse command. + * + *

+ * The gauge type is as follows: + * + *

+ *  AuthenticationEnablementGaugeT:
+ *     commands:
+ *       clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int)
+ *     setupParams:
+ *       targetIP:
+ *         type: String
+ *         default: "localhost"
+ *       beaconPeriod:
+ *         type: long
+ *         default: 5000
+ *       javaClass:
+ *         type: String
+ *         default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge"
+ *     configParams:
+ *       targetProbeType:
+ *         type: String
+ *         default: ~
+ * 
+ * + * @author Bradley Schmerl: schmerl + * + */ +public class AuthenticationEnablementGauge extends RegularPatternGauge { + + public static final String NAME = "G - Authentication Enablement"; + + private static final String OFF = "off"; + private static final String ON = "on"; + + public AuthenticationEnablementGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, + TypedAttribute modelDesc, List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern (ON, Pattern.compile ("^on$")); + addPattern (OFF, Pattern.compile ("^off$")); + } + + @Override + protected void doMatch (String matchName, Matcher m) { + boolean authenticationOff = OFF.equals (matchName); + if (authenticationOff) { + // Reset everything to unknown + List ops = new LinkedList<> (); + List> params = new LinkedList<> (); + + for (Entry entry : m_commands.entrySet ()) { + if (entry.getKey ().startsWith ("clientMgmt(")) { + IRainbowOperation op = entry.getValue (); + Map pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], "0"); + ops.add (op); + params.add (pMap); + } + } + + issueCommands (ops, params); + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/CaptchaGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/CaptchaGauge.java index 41ce3b2a5..506692deb 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/CaptchaGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/CaptchaGauge.java @@ -1,87 +1,87 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class CaptchaGauge extends RegularPatternGauge { - public static final String NAME = "G - Captcha Enablement"; - - private static final String OFF = "off"; - private static final String ON = "on"; - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { "enablement" }; - - public CaptchaGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern (ON, Pattern.compile ("^on$")); - addPattern (OFF, Pattern.compile ("^off$")); - } - - @Override - protected void doMatch (String matchName, Matcher m) { - boolean captchaOn = ON.equals (matchName); - IRainbowOperation cmd = m_commands.get (valueNames[0]); - Map pMap = new HashMap<> (); - pMap.put (cmd.getParameters ()[0], Boolean.toString (captchaOn)); - if (captchaOn) { - issueCommand (cmd, pMap); - } - else { - List ops = new LinkedList<> (); - List> params = new LinkedList<> (); - - ops.add (cmd); - params.add (pMap); - - for (Entry entry : m_commands.entrySet ()) { - if (entry.getKey ().startsWith ("clientMgmt(")) { - IRainbowOperation op = entry.getValue (); - pMap = new HashMap<> (); - pMap.put (op.getParameters ()[0], "0"); - ops.add (op); - params.add (pMap); - } - } - - issueCommands (ops, params); - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class CaptchaGauge extends RegularPatternGauge { + public static final String NAME = "G - Captcha Enablement"; + + private static final String OFF = "off"; + private static final String ON = "on"; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { "enablement" }; + + public CaptchaGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern (ON, Pattern.compile ("^on$")); + addPattern (OFF, Pattern.compile ("^off$")); + } + + @Override + protected void doMatch (String matchName, Matcher m) { + boolean captchaOn = ON.equals (matchName); + IRainbowOperation cmd = m_commands.get (valueNames[0]); + Map pMap = new HashMap<> (); + pMap.put (cmd.getParameters ()[0], Boolean.toString (captchaOn)); + if (captchaOn) { + issueCommand (cmd, pMap); + } + else { + List ops = new LinkedList<> (); + List> params = new LinkedList<> (); + + ops.add (cmd); + params.add (pMap); + + for (Entry entry : m_commands.entrySet ()) { + if (entry.getKey ().startsWith ("clientMgmt(")) { + IRainbowOperation op = entry.getValue (); + pMap = new HashMap<> (); + pMap.put (op.getParameters ()[0], "0"); + ops.add (op); + params.add (pMap); + } + } + + issueCommands (ops, params); + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ClientGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ClientGauge.java index 1adf76faf..7bfb2af18 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ClientGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ClientGauge.java @@ -1,397 +1,397 @@ -package org.sa.rainbow.translator.znn.gauges; - -import com.google.common.collect.TreeMultiset; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.model.event.AcmeModelEventType; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IModelChangeBusPort; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; -import org.sa.rainbow.core.ports.IModelsManagerPort; -import org.sa.rainbow.core.ports.RainbowPortFactory; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.model.acme.AcmeModelInstance; -import org.sa.rainbow.model.acme.AcmeModelOperation; - -import java.text.MessageFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ClientGauge extends RegularPatternGauge { - - private RequestRater m_requestRater; - - public class NewClientWatcher implements IRainbowModelChangeCallback { - - @Override - public void onEvent (ModelReference reference, IRainbowMessage message) { - IModelInstance m = m_modelPort.getModelInstance (reference); - if (m instanceof AcmeModelInstance) { - AcmeModelInstance model = (AcmeModelInstance) m; - String bearer = (String) message.getProperty (AcmeModelOperation.BEARER_PROP); - try { - IAcmeComponent client = model.resolveInModel (bearer, IAcmeComponent.class); - if (client.declaresType ("ClientT")) { - String ip = (String) message.getProperty (AcmeModelOperation.VALUE_PROP); - // Strip out starting and ending quotes - ip = ip.replaceAll ("^\"", ""); - ip = ip.replaceAll ("\"$", ""); - m_IP2Client.put (ip, client); - m_ipsToProcess.remove (ip); - } - } catch (RainbowModelException e) { - e.printStackTrace (); - } - } - } - - } - - public static final String NAME = "G - Client Manager"; - - private static final String[] commandNames = {"addClient", "removeClient", "setClientRequestRate"}; - - private static final String DEFAULT = "CLIENT_REQUEST"; - - private static final long RR_INTERVAL = 2000; - - private static SimpleDateFormat SDF = new SimpleDateFormat ("dd/MMM/yyyy:HH:mm:ss Z"); - - private IModelsManagerPort m_modelPort; - private IModelChangeBusSubscriberPort m_modelChanges; - - Map m_IP2Client = new HashMap<> (); - TreeMap m_lastSeen2IP = new TreeMap<> (); - Map m_IP2LastSeen = new HashMap<> (); - Map> m_IP2Accesses = new HashMap<> (); - - Set m_ipsToProcess = Collections.synchronizedSet (new HashSet ()); - - private long m_clientWindow = 30000; /* 30 seconds */ - - private boolean m_someAccess; - - private boolean m_doHousekeeping = true; - - private long m_discardWindow = 1800000; /* 30 minutes */ - - private long m_lastRRUpdates = 0; - - private boolean m_housekeeping = false; - - public ClientGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern (DEFAULT, Pattern.compile ("^([\\d.]+) - - \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}).*$")); - - // Handle setup parameters - Long window = getSetupValue ("window", Long.class); - if (window != null) { - m_clientWindow = window; - } - - Long discardWindow = getSetupValue ("dsicardAfter", Long.class); - if (discardWindow != null) { - m_discardWindow = discardWindow; - } - - m_modelPort = RainbowPortFactory.createModelsManagerRequirerPort (); - m_modelChanges = RainbowPortFactory.createModelChangeBusSubscriptionPort (); - - // Register for new clients, so that we can update the maps - m_modelChanges.subscribe (new IRainbowChangeBusSubscription () { - - @Override - public boolean matches (IRainbowMessage message) { - boolean b = message.getPropertyNames ().contains (IModelChangeBusPort.MODEL_NAME_PROP) - && message.getProperty (IModelChangeBusPort.MODEL_NAME_PROP).equals (m_modelDesc.getName ()); - if (b) { - b = message.getPropertyNames ().contains (IModelChangeBusPort.EVENT_TYPE_PROP) - && message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP) - .equals (AcmeModelEventType.ADD_PROPERTY.name ()); - if (b) { - b = message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) - && ((String) message.getProperty (AcmeModelOperation.PROPERTY_PROP)) - .endsWith ("deploymentLocation"); - } - } - return b; - } - }, new NewClientWatcher ()); - } - - @Override - protected void doMatch (String matchName, Matcher m) { - if (DEFAULT.equals (matchName)) { - String ip = m.group (1); - String lastSeen = m.group (2); - try { - Date lastSeenDate = SDF.parse (lastSeen); - Date now = new Date (); - m_someAccess = true; - if (now.getTime () - m_clientWindow > lastSeenDate.getTime ()) return; - boolean b = !m_ipsToProcess.contains (ip) && m_IP2Client.get (ip) == null; - if (b) { - // This is from a new client - m_ipsToProcess.add (ip); - IRainbowOperation cmd = getCommand (commandNames[0]); - Map pm = new HashMap<> (); - pm.put (cmd.getParameters ()[1], ip); - issueCommand (cmd, pm); - } - // update the last seen data - m_lastSeen2IP.put (lastSeenDate.getTime (), ip); - m_IP2LastSeen.put (ip, lastSeenDate.getTime ()); - if (m_requestRater != null) - m_requestRater.tick (ip); -// TreeMultiset accesses = m_IP2Accesses.get (ip); -// if (accesses == null) { -// accesses = TreeMultiset.create (); -// m_IP2Accesses.put (ip, accesses); -// } -// accesses.add (lastSeenDate.getTime ()); - } catch (ParseException e) { - e.printStackTrace (); - } - } - } - - @Override - protected void runAction () { - super.runAction (); -// if (m_someAccess) { -// m_someAccess = false; -// doHousekeeping (); -// } - } - - void doHousekeeping () { - synchronized (this) { - if (m_housekeeping) return; - } - m_housekeeping = true; - cleanOutOldClients (); -// updateRequestRates (); - m_housekeeping = false; - } - - // Request rate calculation has been replaced with RequestRater below -// private float getRequestRate (TreeMultiset accesses, long maxInterval, long now) { -// Iterator iterator = accesses.iterator (); -// while (iterator.hasNext ()) { -// if (now - iterator.next () > maxInterval) { -// iterator.remove (); -// } -// } -// -// com.google.common.collect.Multiset.Entry lastEntry = accesses.lastEntry (); -// if (lastEntry != null) { -// Long oldest = lastEntry.getElement (); -// -// long seconds = (maxInterval/*now - maxInterval*/) / 1000; -// -// float size = accesses.size (); -// float rr = size / seconds; -// return rr; -// } else -// return 0; -// -// } -// -// private void updateRequestRates () { -// long now = new Date ().getTime (); -// if (now - m_lastRRUpdates < RR_INTERVAL) return; -// List cmds = new LinkedList<> (); -// List> pms = new LinkedList<> (); -// for (Entry> entry : m_IP2Accesses.entrySet ()) { -// String key = entry.getKey (); -// IAcmeComponent client = m_IP2Client.get (key); -// if (client != null) { -// float reqRate = getRequestRate (entry.getValue (), m_clientWindow, now); -// String format = MessageFormat.format ( -// "Client ''{0}'' made {1} requests in the last {2} seconds for a request rate of {3,number,###.######} req/sec", -// client.getQualifiedName (), entry.getValue ().size (), m_clientWindow / 1000, reqRate); -// log (format); -// System.out.println (format); -// IRainbowOperation cmd = getCommand (commandNames[2]); -// Map pm = new HashMap<> (); -// pm.put (cmd.getTarget (), client.getQualifiedName ()); -// pm.put (cmd.getParameters ()[0], Double.toString (reqRate)); -// cmds.add (cmd); -// pms.add (pm); -// } -// } -// if (!cmds.isEmpty ()) { -// issueCommands (cmds, pms); -// } -// m_lastRRUpdates = new Date ().getTime (); -// } - - // Removes clients that have not been seen in the last "clientWindow" ms. - private void cleanOutOldClients () { - if (m_lastSeen2IP.isEmpty ()) return; - Date now = new Date (); - Long oldest = m_lastSeen2IP.firstKey (); - List cmds = new LinkedList<> (); - List> pms = new LinkedList<> (); - while (oldest != null && now.getTime () - oldest > m_discardWindow) { - String ip = m_lastSeen2IP.get (oldest); - IAcmeComponent oldClient = m_IP2Client.get (ip); - if (oldClient != null) { - IRainbowOperation cmd = getCommand (commandNames[1]); - cmds.add (cmd); - Map pm = new HashMap<> (); - pm.put (cmd.getTarget (), oldClient.getQualifiedName ()); - pms.add (pm); - - m_IP2Client.remove (ip); - } - m_lastSeen2IP.remove (oldest); - m_IP2LastSeen.remove (ip); - oldest = m_lastSeen2IP.firstKey (); - } - if (!cmds.isEmpty ()) { - issueCommands (cmds, pms); - } - } - - @Override - protected void handleConfigParam (TypedAttributeWithValue tav) { - super.handleConfigParam (tav); - - if (tav.getName ().equals ("windpw")) { - m_clientWindow = (long) tav.getValue (); - } else if (tav.getName ().equals ("discardAfter")) { - m_discardWindow = (long) tav.getValue (); - } - } - - @Override - public void start () { - super.start (); - m_doHousekeeping = true; - Thread housekeep = new Thread (new Runnable () { - - @Override - public void run () { - while (m_doHousekeeping) { - try { - Thread.sleep (m_discardWindow); - } catch (InterruptedException e) { - } - doHousekeeping (); - } - } - }); - housekeep.start (); - - m_requestRater = new RequestRater (m_clientWindow); - m_requestRater.start (); - } - - @Override - public void stop () { - m_doHousekeeping = false; - super.stop (); - } - - @Override - public void terminate () { - super.terminate (); - m_doHousekeeping = false; - } - - protected class RequestRater extends Thread { - - - private long m_sleepTime; - - public RequestRater (long sleepTime) { - super (); - - m_sleepTime = sleepTime; - } - - Map m_requestTracker = new HashMap<> (); - long m_timestamp = new Date ().getTime (); - - public synchronized void tick (String ip) { - Integer ticks = m_requestTracker.get (ip); - if (ticks == null) m_requestTracker.put (ip, 1); - else m_requestTracker.put (ip, ticks + 1); - } - - @Override - public void run () { - while (!isTerminated () && m_doHousekeeping) { - try { - sleep (m_sleepTime); - } catch (InterruptedException ignore) { - } - Map rrs = markRequestRates (); - List ops = new ArrayList<> (rrs.size ()); - List> pms = new ArrayList<> (rrs.size ()); - for (Entry e : rrs.entrySet ()) { - IAcmeComponent client = m_IP2Client.get (e.getKey ()); - - String format = MessageFormat.format ( - "Client ''{0}'' has a request rate of {1,number,###.######} req/sec", - client.getQualifiedName (), e.getValue ()); - log (format); - IRainbowOperation op = getCommand (commandNames[2]); - Map pm = new HashMap<> (); - pm.put (op.getTarget (), client.getQualifiedName ()); - pm.put (op.getParameters ()[0], Double.toString (e.getValue ())); - ops.add (op); - pms.add (pm); - } - if (!ops.isEmpty ()) { - issueCommands (ops, pms); - } - - } - } - - public Map markRequestRates () { - long from = 0; - Map ticks; - synchronized (this) { - ticks = m_requestTracker; - from = m_timestamp; - m_requestTracker = new HashMap<> (); - m_timestamp = new Date ().getTime (); - } - Map ret = new HashMap<> (); - String format = ""; - for (Entry entry : ticks.entrySet ()) { - double rr = entry.getValue ().doubleValue () / ((m_timestamp - from)) * 1000; - - IAcmeComponent client = m_IP2Client.get (entry.getKey ()); - if (client != null) { - format += MessageFormat.format ( - "Client ''{0}'' made {1} requests in the last {2} seconds for a request rate of {3,number,###.######} req/sec\n", - client.getQualifiedName (), entry.getValue (), (m_timestamp - from) / 1000, rr); - ret.put (entry.getKey (), rr); - } - } - log (format); - return ret; - } - - - } - -} +package org.sa.rainbow.translator.znn.gauges; + +import com.google.common.collect.TreeMultiset; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.model.event.AcmeModelEventType; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.model.acme.AcmeModelInstance; +import org.sa.rainbow.model.acme.AcmeModelOperation; + +import java.text.MessageFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ClientGauge extends RegularPatternGauge { + + private RequestRater m_requestRater; + + public class NewClientWatcher implements IRainbowModelChangeCallback { + + @Override + public void onEvent (ModelReference reference, IRainbowMessage message) { + IModelInstance m = m_modelPort.getModelInstance (reference); + if (m instanceof AcmeModelInstance) { + AcmeModelInstance model = (AcmeModelInstance) m; + String bearer = (String) message.getProperty (AcmeModelOperation.BEARER_PROP); + try { + IAcmeComponent client = model.resolveInModel (bearer, IAcmeComponent.class); + if (client.declaresType ("ClientT")) { + String ip = (String) message.getProperty (AcmeModelOperation.VALUE_PROP); + // Strip out starting and ending quotes + ip = ip.replaceAll ("^\"", ""); + ip = ip.replaceAll ("\"$", ""); + m_IP2Client.put (ip, client); + m_ipsToProcess.remove (ip); + } + } catch (RainbowModelException e) { + e.printStackTrace (); + } + } + } + + } + + public static final String NAME = "G - Client Manager"; + + private static final String[] commandNames = {"addClient", "removeClient", "setClientRequestRate"}; + + private static final String DEFAULT = "CLIENT_REQUEST"; + + private static final long RR_INTERVAL = 2000; + + private static SimpleDateFormat SDF = new SimpleDateFormat ("dd/MMM/yyyy:HH:mm:ss Z"); + + private IModelsManagerPort m_modelPort; + private IModelChangeBusSubscriberPort m_modelChanges; + + Map m_IP2Client = new HashMap<> (); + TreeMap m_lastSeen2IP = new TreeMap<> (); + Map m_IP2LastSeen = new HashMap<> (); + Map> m_IP2Accesses = new HashMap<> (); + + Set m_ipsToProcess = Collections.synchronizedSet (new HashSet ()); + + private long m_clientWindow = 30000; /* 30 seconds */ + + private boolean m_someAccess; + + private boolean m_doHousekeeping = true; + + private long m_discardWindow = 1800000; /* 30 minutes */ + + private long m_lastRRUpdates = 0; + + private boolean m_housekeeping = false; + + public ClientGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern (DEFAULT, Pattern.compile ("^([\\d.]+) - - \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}).*$")); + + // Handle setup parameters + Long window = getSetupValue ("window", Long.class); + if (window != null) { + m_clientWindow = window; + } + + Long discardWindow = getSetupValue ("dsicardAfter", Long.class); + if (discardWindow != null) { + m_discardWindow = discardWindow; + } + + m_modelPort = RainbowPortFactory.createModelsManagerRequirerPort (); + m_modelChanges = RainbowPortFactory.createModelChangeBusSubscriptionPort (); + + // Register for new clients, so that we can update the maps + m_modelChanges.subscribe (new IRainbowChangeBusSubscription () { + + @Override + public boolean matches (IRainbowMessage message) { + boolean b = message.getPropertyNames ().contains (IModelChangeBusPort.MODEL_NAME_PROP) + && message.getProperty (IModelChangeBusPort.MODEL_NAME_PROP).equals (m_modelDesc.getName ()); + if (b) { + b = message.getPropertyNames ().contains (IModelChangeBusPort.EVENT_TYPE_PROP) + && message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP) + .equals (AcmeModelEventType.ADD_PROPERTY.name ()); + if (b) { + b = message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) + && ((String) message.getProperty (AcmeModelOperation.PROPERTY_PROP)) + .endsWith ("deploymentLocation"); + } + } + return b; + } + }, new NewClientWatcher ()); + } + + @Override + protected void doMatch (String matchName, Matcher m) { + if (DEFAULT.equals (matchName)) { + String ip = m.group (1); + String lastSeen = m.group (2); + try { + Date lastSeenDate = SDF.parse (lastSeen); + Date now = new Date (); + m_someAccess = true; + if (now.getTime () - m_clientWindow > lastSeenDate.getTime ()) return; + boolean b = !m_ipsToProcess.contains (ip) && m_IP2Client.get (ip) == null; + if (b) { + // This is from a new client + m_ipsToProcess.add (ip); + IRainbowOperation cmd = getCommand (commandNames[0]); + Map pm = new HashMap<> (); + pm.put (cmd.getParameters ()[1], ip); + issueCommand (cmd, pm); + } + // update the last seen data + m_lastSeen2IP.put (lastSeenDate.getTime (), ip); + m_IP2LastSeen.put (ip, lastSeenDate.getTime ()); + if (m_requestRater != null) + m_requestRater.tick (ip); +// TreeMultiset accesses = m_IP2Accesses.get (ip); +// if (accesses == null) { +// accesses = TreeMultiset.create (); +// m_IP2Accesses.put (ip, accesses); +// } +// accesses.add (lastSeenDate.getTime ()); + } catch (ParseException e) { + e.printStackTrace (); + } + } + } + + @Override + protected void runAction () { + super.runAction (); +// if (m_someAccess) { +// m_someAccess = false; +// doHousekeeping (); +// } + } + + void doHousekeeping () { + synchronized (this) { + if (m_housekeeping) return; + } + m_housekeeping = true; + cleanOutOldClients (); +// updateRequestRates (); + m_housekeeping = false; + } + + // Request rate calculation has been replaced with RequestRater below +// private float getRequestRate (TreeMultiset accesses, long maxInterval, long now) { +// Iterator iterator = accesses.iterator (); +// while (iterator.hasNext ()) { +// if (now - iterator.next () > maxInterval) { +// iterator.remove (); +// } +// } +// +// com.google.common.collect.Multiset.Entry lastEntry = accesses.lastEntry (); +// if (lastEntry != null) { +// Long oldest = lastEntry.getElement (); +// +// long seconds = (maxInterval/*now - maxInterval*/) / 1000; +// +// float size = accesses.size (); +// float rr = size / seconds; +// return rr; +// } else +// return 0; +// +// } +// +// private void updateRequestRates () { +// long now = new Date ().getTime (); +// if (now - m_lastRRUpdates < RR_INTERVAL) return; +// List cmds = new LinkedList<> (); +// List> pms = new LinkedList<> (); +// for (Entry> entry : m_IP2Accesses.entrySet ()) { +// String key = entry.getKey (); +// IAcmeComponent client = m_IP2Client.get (key); +// if (client != null) { +// float reqRate = getRequestRate (entry.getValue (), m_clientWindow, now); +// String format = MessageFormat.format ( +// "Client ''{0}'' made {1} requests in the last {2} seconds for a request rate of {3,number,###.######} req/sec", +// client.getQualifiedName (), entry.getValue ().size (), m_clientWindow / 1000, reqRate); +// log (format); +// System.out.println (format); +// IRainbowOperation cmd = getCommand (commandNames[2]); +// Map pm = new HashMap<> (); +// pm.put (cmd.getTarget (), client.getQualifiedName ()); +// pm.put (cmd.getParameters ()[0], Double.toString (reqRate)); +// cmds.add (cmd); +// pms.add (pm); +// } +// } +// if (!cmds.isEmpty ()) { +// issueCommands (cmds, pms); +// } +// m_lastRRUpdates = new Date ().getTime (); +// } + + // Removes clients that have not been seen in the last "clientWindow" ms. + private void cleanOutOldClients () { + if (m_lastSeen2IP.isEmpty ()) return; + Date now = new Date (); + Long oldest = m_lastSeen2IP.firstKey (); + List cmds = new LinkedList<> (); + List> pms = new LinkedList<> (); + while (oldest != null && now.getTime () - oldest > m_discardWindow) { + String ip = m_lastSeen2IP.get (oldest); + IAcmeComponent oldClient = m_IP2Client.get (ip); + if (oldClient != null) { + IRainbowOperation cmd = getCommand (commandNames[1]); + cmds.add (cmd); + Map pm = new HashMap<> (); + pm.put (cmd.getTarget (), oldClient.getQualifiedName ()); + pms.add (pm); + + m_IP2Client.remove (ip); + } + m_lastSeen2IP.remove (oldest); + m_IP2LastSeen.remove (ip); + oldest = m_lastSeen2IP.firstKey (); + } + if (!cmds.isEmpty ()) { + issueCommands (cmds, pms); + } + } + + @Override + protected void handleConfigParam (TypedAttributeWithValue tav) { + super.handleConfigParam (tav); + + if (tav.getName ().equals ("windpw")) { + m_clientWindow = (long) tav.getValue (); + } else if (tav.getName ().equals ("discardAfter")) { + m_discardWindow = (long) tav.getValue (); + } + } + + @Override + public void start () { + super.start (); + m_doHousekeeping = true; + Thread housekeep = new Thread (new Runnable () { + + @Override + public void run () { + while (m_doHousekeeping) { + try { + Thread.sleep (m_discardWindow); + } catch (InterruptedException e) { + } + doHousekeeping (); + } + } + }); + housekeep.start (); + + m_requestRater = new RequestRater (m_clientWindow); + m_requestRater.start (); + } + + @Override + public void stop () { + m_doHousekeeping = false; + super.stop (); + } + + @Override + public void terminate () { + super.terminate (); + m_doHousekeeping = false; + } + + protected class RequestRater extends Thread { + + + private long m_sleepTime; + + public RequestRater (long sleepTime) { + super (); + + m_sleepTime = sleepTime; + } + + Map m_requestTracker = new HashMap<> (); + long m_timestamp = new Date ().getTime (); + + public synchronized void tick (String ip) { + Integer ticks = m_requestTracker.get (ip); + if (ticks == null) m_requestTracker.put (ip, 1); + else m_requestTracker.put (ip, ticks + 1); + } + + @Override + public void run () { + while (!isTerminated () && m_doHousekeeping) { + try { + sleep (m_sleepTime); + } catch (InterruptedException ignore) { + } + Map rrs = markRequestRates (); + List ops = new ArrayList<> (rrs.size ()); + List> pms = new ArrayList<> (rrs.size ()); + for (Entry e : rrs.entrySet ()) { + IAcmeComponent client = m_IP2Client.get (e.getKey ()); + + String format = MessageFormat.format ( + "Client ''{0}'' has a request rate of {1,number,###.######} req/sec", + client.getQualifiedName (), e.getValue ()); + log (format); + IRainbowOperation op = getCommand (commandNames[2]); + Map pm = new HashMap<> (); + pm.put (op.getTarget (), client.getQualifiedName ()); + pm.put (op.getParameters ()[0], Double.toString (e.getValue ())); + ops.add (op); + pms.add (pm); + } + if (!ops.isEmpty ()) { + issueCommands (ops, pms); + } + + } + } + + public Map markRequestRates () { + long from = 0; + Map ticks; + synchronized (this) { + ticks = m_requestTracker; + from = m_timestamp; + m_requestTracker = new HashMap<> (); + m_timestamp = new Date ().getTime (); + } + Map ret = new HashMap<> (); + String format = ""; + for (Entry entry : ticks.entrySet ()) { + double rr = entry.getValue ().doubleValue () / ((m_timestamp - from)) * 1000; + + IAcmeComponent client = m_IP2Client.get (entry.getKey ()); + if (client != null) { + format += MessageFormat.format ( + "Client ''{0}'' made {1} requests in the last {2} seconds for a request rate of {3,number,###.######} req/sec\n", + client.getQualifiedName (), entry.getValue (), (m_timestamp - from) / 1000, rr); + ret.put (entry.getKey (), rr); + } + } + log (format); + return ret; + } + + + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ClientResponseTimeGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ClientResponseTimeGauge.java index d8f658628..b3c533852 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ClientResponseTimeGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ClientResponseTimeGauge.java @@ -1,256 +1,256 @@ -package org.sa.rainbow.translator.znn.gauges; - -import org.acmestudio.acme.model.event.AcmeModelEventType; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IModelChangeBusPort; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; -import org.sa.rainbow.core.ports.RainbowPortFactory; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.model.acme.AcmeModelOperation; -import org.sa.rainbow.model.acme.AcmeRainbowOperationEvent.CommandEventT; - -import java.text.MessageFormat; -import java.util.*; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Gauge monitors Apache log information for the %D log entry (response time in microseconds) - * - * @author Bradley Schmerl: schmerl - * - */ -public class ClientResponseTimeGauge extends RegularPatternGauge { - - /** - * Forgets any information about clients that are removed from the system - * - */ - public class ForgetDeletedClient implements IRainbowModelChangeCallback { - - @Override - public void onEvent (ModelReference reference, IRainbowMessage message) { - synchronized (ClientResponseTimeGauge.this) { - String client = (String )message.getProperty (IModelChangeBusPort.TARGET_PROP); - Iterator> iterator = m_IP2ClientName.entrySet ().iterator (); - boolean found = false; - while (iterator.hasNext () && !found) { - Entry next = iterator.next (); - if (next.getValue ().equals (client)) { - iterator.remove (); - found = true; - } - } - } - } - - } - - /** - * - * Issues response time reports for new clients. This could happen, for example, when a client is created based on a - * log entry that has also been read by this gauge. - */ - public class ReportResponseForNewClient implements IRainbowModelChangeCallback { - - @Override - public void onEvent (ModelReference reference, IRainbowMessage message) { - synchronized (ClientResponseTimeGauge.this) { - String client = (String )message.getProperty (AcmeModelOperation.BEARER_PROP); - // Ignore events that aren't associated with clients - if (!client.contains ("Client")) return; - String ip = (String )message.getProperty (AcmeModelOperation.VALUE_PROP); - // Remove trailing and leading " - ip = ip.replaceAll ("^\"", ""); - ip = ip.replaceAll ("\"$", ""); - if (ip != null) { - m_IP2ClientName.put (ip, client); - issueResponseTimeCommand (client, m_historyMap.get (ip), m_cumulationMap.get (ip), true); - } - } - } - - } - - /** A subscription that matches any event in a given model **/ - public static class ModelBasedSubscription implements IRainbowChangeBusSubscription { - - private String m_modelName; - private String m_modelType; - - public ModelBasedSubscription (String modelName, String modelType) { - m_modelName = modelName; - m_modelType = modelType; - } - - @Override - public boolean matches (IRainbowMessage message) { - boolean b = message.getPropertyNames ().contains (IModelChangeBusPort.MODEL_NAME_PROP) - && message.getProperty (IModelChangeBusPort.MODEL_NAME_PROP).equals (m_modelName); - b &= message.getPropertyNames ().contains (IModelChangeBusPort.MODEL_TYPE_PROP) - && message.getProperty (IModelChangeBusPort.MODEL_TYPE_PROP).equals (m_modelType); - return b; - } - } - - public class MatchAddClientSubscription extends ModelBasedSubscription { - - public MatchAddClientSubscription (String modelName, String modelType) { - super (modelName, modelType); - } - - /** - * Match on ADD_PROPERTY of deploymentLocation, meaning that a client has been created - */ - @Override - public boolean matches (IRainbowMessage message) { - boolean b = super.matches (message); - String type = (String )message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); - b &= AcmeModelEventType.ADD_PROPERTY.name ().equals (type) - && message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) - && ((String )message.getProperty (AcmeModelOperation.PROPERTY_PROP)) - .endsWith ("deploymentLocation"); - return b; - } - - } - - public class MatchDeleteClientSubscription extends ModelBasedSubscription { - - public MatchDeleteClientSubscription (String modelName, String modelType) { - super (modelName, modelType); - } - - @Override - public boolean matches (IRainbowMessage message) { - boolean b = super.matches (message); - String type = (String )message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); - if (type != null) { - try { - CommandEventT ct = CommandEventT.valueOf (type); - b &= ct.isEnd () && message.getProperty (IModelChangeBusPort.COMMAND_PROP).equals ("deleteClient"); - return b; - } - catch (Exception e) { - } - } - return false; - - } - - } - - public static String NAME = "G - Client Response Time"; - private static final String DEFAULT = "CLIENT_REQUEST"; - private static final int AVG_SAMPLE_WINDOW = 5; - private static final int INTERVAL = 2000; - - private static final String[] commandNames = { "responseTime" }; - - private IModelChangeBusSubscriberPort m_modelChanges; - - Map m_IP2ClientName = new HashMap<> (); - Map> m_historyMap = new HashMap<> (); - Map m_cumulationMap = new HashMap<> (); - Map m_lastReport = new HashMap<> (); - - final Queue m_ops = new LinkedList<> (); - Queue> m_params = new LinkedList<> (); - - public ClientResponseTimeGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern (DEFAULT, - Pattern.compile ("^([\\d.]+) - - \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" \\d{3}.*\\s(\\d+)$")); - - m_modelChanges = RainbowPortFactory.createModelChangeBusSubscriptionPort (); - m_modelChanges.subscribe (new MatchAddClientSubscription (m_modelDesc.getName (), m_modelDesc.getType ()), - new ReportResponseForNewClient ()); - m_modelChanges.subscribe (new MatchDeleteClientSubscription (m_modelDesc.getName (), m_modelDesc.getType ()), - new ForgetDeletedClient ()); - } - - @Override - protected synchronized void doMatch (String matchName, Matcher m) { - if (DEFAULT.equals (matchName)) { - String ip = m.group (1); - Long last = m_lastReport.get (ip); - if (last == null || new Date ().getTime () - last > INTERVAL) { - String rtMicro = m.group (4); - Double rtms = Double.parseDouble (rtMicro) / 1000; // response time in ms - if (!m_historyMap.containsKey (ip)) { - m_historyMap.put (ip, new LinkedList ()); - m_cumulationMap.put (ip, 0.0); - } - Queue history = m_historyMap.get (ip); - double cumulation = m_cumulationMap.get (ip); - - // add value to cumulation and enquue - cumulation += rtms; - history.offer (rtms); - if (history.size () > AVG_SAMPLE_WINDOW) { - // if queue size reached window size then dequeue and delete olderst value and report average - cumulation -= history.poll (); - } - m_cumulationMap.put (ip, cumulation); - String client = m_IP2ClientName.get (ip); - if (client != null) { - // update client with latency - issueResponseTimeCommand (client, history, cumulation, false); - } - else { - // Client has not yet been registered with the model. Defer this to a component creation end - } - m_lastReport.put (ip, new Date ().getTime ()); - } - - } - } - - @Override - protected void runAction () { - IRainbowOperation cmd = null; - Map params = null; - synchronized (m_ops) { - cmd = m_ops.poll (); - if (cmd != null) { - params = m_params.poll (); - } - } - if (cmd != null) { - issueCommand (cmd, params); - } - super.runAction (); - } - - void issueResponseTimeCommand (String client, Queue history, double cumulation, boolean enqueue) { - double avgRTms = cumulation / history.size (); - - m_reportingPort.trace (getComponentType (), - MessageFormat.format ("{0}: {1}, hist{2}", id (), cumulation, Arrays.toString (history.toArray ()))); - IRainbowOperation command = getCommand (commandNames[0]); - Map pm = new HashMap<> (); - pm.put (command.getTarget (), client); - pm.put (command.getParameters ()[0], Double.toString (avgRTms)); - if (enqueue) { - synchronized (m_ops) { - m_ops.offer (command); - m_params.offer (pm); - } - } - else { - issueCommand (command, pm); - } - } - -} +package org.sa.rainbow.translator.znn.gauges; + +import org.acmestudio.acme.model.event.AcmeModelEventType; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.model.acme.AcmeModelOperation; +import org.sa.rainbow.model.acme.AcmeRainbowOperationEvent.CommandEventT; + +import java.text.MessageFormat; +import java.util.*; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Gauge monitors Apache log information for the %D log entry (response time in microseconds) + * + * @author Bradley Schmerl: schmerl + * + */ +public class ClientResponseTimeGauge extends RegularPatternGauge { + + /** + * Forgets any information about clients that are removed from the system + * + */ + public class ForgetDeletedClient implements IRainbowModelChangeCallback { + + @Override + public void onEvent (ModelReference reference, IRainbowMessage message) { + synchronized (ClientResponseTimeGauge.this) { + String client = (String )message.getProperty (IModelChangeBusPort.TARGET_PROP); + Iterator> iterator = m_IP2ClientName.entrySet ().iterator (); + boolean found = false; + while (iterator.hasNext () && !found) { + Entry next = iterator.next (); + if (next.getValue ().equals (client)) { + iterator.remove (); + found = true; + } + } + } + } + + } + + /** + * + * Issues response time reports for new clients. This could happen, for example, when a client is created based on a + * log entry that has also been read by this gauge. + */ + public class ReportResponseForNewClient implements IRainbowModelChangeCallback { + + @Override + public void onEvent (ModelReference reference, IRainbowMessage message) { + synchronized (ClientResponseTimeGauge.this) { + String client = (String )message.getProperty (AcmeModelOperation.BEARER_PROP); + // Ignore events that aren't associated with clients + if (!client.contains ("Client")) return; + String ip = (String )message.getProperty (AcmeModelOperation.VALUE_PROP); + // Remove trailing and leading " + ip = ip.replaceAll ("^\"", ""); + ip = ip.replaceAll ("\"$", ""); + if (ip != null) { + m_IP2ClientName.put (ip, client); + issueResponseTimeCommand (client, m_historyMap.get (ip), m_cumulationMap.get (ip), true); + } + } + } + + } + + /** A subscription that matches any event in a given model **/ + public static class ModelBasedSubscription implements IRainbowChangeBusSubscription { + + private String m_modelName; + private String m_modelType; + + public ModelBasedSubscription (String modelName, String modelType) { + m_modelName = modelName; + m_modelType = modelType; + } + + @Override + public boolean matches (IRainbowMessage message) { + boolean b = message.getPropertyNames ().contains (IModelChangeBusPort.MODEL_NAME_PROP) + && message.getProperty (IModelChangeBusPort.MODEL_NAME_PROP).equals (m_modelName); + b &= message.getPropertyNames ().contains (IModelChangeBusPort.MODEL_TYPE_PROP) + && message.getProperty (IModelChangeBusPort.MODEL_TYPE_PROP).equals (m_modelType); + return b; + } + } + + public class MatchAddClientSubscription extends ModelBasedSubscription { + + public MatchAddClientSubscription (String modelName, String modelType) { + super (modelName, modelType); + } + + /** + * Match on ADD_PROPERTY of deploymentLocation, meaning that a client has been created + */ + @Override + public boolean matches (IRainbowMessage message) { + boolean b = super.matches (message); + String type = (String )message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); + b &= AcmeModelEventType.ADD_PROPERTY.name ().equals (type) + && message.getPropertyNames ().contains (AcmeModelOperation.PROPERTY_PROP) + && ((String )message.getProperty (AcmeModelOperation.PROPERTY_PROP)) + .endsWith ("deploymentLocation"); + return b; + } + + } + + public class MatchDeleteClientSubscription extends ModelBasedSubscription { + + public MatchDeleteClientSubscription (String modelName, String modelType) { + super (modelName, modelType); + } + + @Override + public boolean matches (IRainbowMessage message) { + boolean b = super.matches (message); + String type = (String )message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); + if (type != null) { + try { + CommandEventT ct = CommandEventT.valueOf (type); + b &= ct.isEnd () && message.getProperty (IModelChangeBusPort.COMMAND_PROP).equals ("deleteClient"); + return b; + } + catch (Exception e) { + } + } + return false; + + } + + } + + public static String NAME = "G - Client Response Time"; + private static final String DEFAULT = "CLIENT_REQUEST"; + private static final int AVG_SAMPLE_WINDOW = 5; + private static final int INTERVAL = 2000; + + private static final String[] commandNames = { "responseTime" }; + + private IModelChangeBusSubscriberPort m_modelChanges; + + Map m_IP2ClientName = new HashMap<> (); + Map> m_historyMap = new HashMap<> (); + Map m_cumulationMap = new HashMap<> (); + Map m_lastReport = new HashMap<> (); + + final Queue m_ops = new LinkedList<> (); + Queue> m_params = new LinkedList<> (); + + public ClientResponseTimeGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, + Pattern.compile ("^([\\d.]+) - - \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" \\d{3}.*\\s(\\d+)$")); + + m_modelChanges = RainbowPortFactory.createModelChangeBusSubscriptionPort (); + m_modelChanges.subscribe (new MatchAddClientSubscription (m_modelDesc.getName (), m_modelDesc.getType ()), + new ReportResponseForNewClient ()); + m_modelChanges.subscribe (new MatchDeleteClientSubscription (m_modelDesc.getName (), m_modelDesc.getType ()), + new ForgetDeletedClient ()); + } + + @Override + protected synchronized void doMatch (String matchName, Matcher m) { + if (DEFAULT.equals (matchName)) { + String ip = m.group (1); + Long last = m_lastReport.get (ip); + if (last == null || new Date ().getTime () - last > INTERVAL) { + String rtMicro = m.group (4); + Double rtms = Double.parseDouble (rtMicro) / 1000; // response time in ms + if (!m_historyMap.containsKey (ip)) { + m_historyMap.put (ip, new LinkedList ()); + m_cumulationMap.put (ip, 0.0); + } + Queue history = m_historyMap.get (ip); + double cumulation = m_cumulationMap.get (ip); + + // add value to cumulation and enquue + cumulation += rtms; + history.offer (rtms); + if (history.size () > AVG_SAMPLE_WINDOW) { + // if queue size reached window size then dequeue and delete olderst value and report average + cumulation -= history.poll (); + } + m_cumulationMap.put (ip, cumulation); + String client = m_IP2ClientName.get (ip); + if (client != null) { + // update client with latency + issueResponseTimeCommand (client, history, cumulation, false); + } + else { + // Client has not yet been registered with the model. Defer this to a component creation end + } + m_lastReport.put (ip, new Date ().getTime ()); + } + + } + } + + @Override + protected void runAction () { + IRainbowOperation cmd = null; + Map params = null; + synchronized (m_ops) { + cmd = m_ops.poll (); + if (cmd != null) { + params = m_params.poll (); + } + } + if (cmd != null) { + issueCommand (cmd, params); + } + super.runAction (); + } + + void issueResponseTimeCommand (String client, Queue history, double cumulation, boolean enqueue) { + double avgRTms = cumulation / history.size (); + + m_reportingPort.trace (getComponentType (), + MessageFormat.format ("{0}: {1}, hist{2}", id (), cumulation, Arrays.toString (history.toArray ()))); + IRainbowOperation command = getCommand (commandNames[0]); + Map pm = new HashMap<> (); + pm.put (command.getTarget (), client); + pm.put (command.getParameters ()[0], Double.toString (avgRTms)); + if (enqueue) { + synchronized (m_ops) { + m_ops.offer (command); + m_params.offer (pm); + } + } + else { + issueCommand (command, pm); + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/CpuLoadGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/CpuLoadGauge.java index 92fada0d4..dffb67d76 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/CpuLoadGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/CpuLoadGauge.java @@ -1,123 +1,123 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created November 1, 2006. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Gauge for consuming CPU load monitoring output. - * - * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) - */ -public class CpuLoadGauge extends RegularPatternGauge { - - public static final String NAME = "G - CPU Load"; - /** Sample window to compute an average load */ - public static final int AVG_SAMPLE_WINDOW = 10; - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "load" - }; - private static final String DEFAULT = "DEFAULT"; - - private Queue m_history = null; - private double m_cumulation = 0; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public CpuLoadGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - m_history = new LinkedList<> (); - - addPattern(DEFAULT, Pattern.compile("\\[(.+)\\]\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)(\\s+([0-9.]+))?")); - - Double initialLoad = getSetupValue ("initialLoad", Double.class); - if (initialLoad != null) { - m_cumulation = initialLoad; - m_history.offer (initialLoad); - } - } - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - // acquire the recent CPU load data -// String tstamp = m.group(1); - double userT = Double.parseDouble(m.group(2)); - double niceT = Double.parseDouble(m.group(3)); - double sysT = Double.parseDouble(m.group(4)); - double idleT = Double.parseDouble(m.group(5)); - double iowaitT = 0.0; - if (m.group(7) != null) { // optional iowait element is present - iowaitT = Double.parseDouble(m.group(7)); - } - double tLoad = userT + niceT + sysT + iowaitT; - // add value to cumulation and enqueue - m_cumulation += tLoad; - m_history.offer(tLoad); - if (m_history.size() > AVG_SAMPLE_WINDOW) { - // if queue size reached window size, then - // dequeue and delete oldest value and report average - m_cumulation -= m_history.poll(); - } - tLoad = m_cumulation / m_history.size(); - if (idleT < 1.0) { - // update server comp in model with requests per sec - m_reportingPort.trace (getComponentType (), "Updating server prop using load = " + tLoad); - // ZNewsSys.s0.load - IRainbowOperation cmd = getCommand (valueNames[0]); - Map pMap = new HashMap<> (); - pMap.put (cmd.getParameters ()[0], Double.toString (tLoad)); - issueCommand (cmd, pMap); - } - } - } - - @Override - protected void runAction () { - super.runAction (); - } -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Gauge for consuming CPU load monitoring output. + * + * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) + */ +public class CpuLoadGauge extends RegularPatternGauge { + + public static final String NAME = "G - CPU Load"; + /** Sample window to compute an average load */ + public static final int AVG_SAMPLE_WINDOW = 10; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "load" + }; + private static final String DEFAULT = "DEFAULT"; + + private Queue m_history = null; + private double m_cumulation = 0; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public CpuLoadGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + m_history = new LinkedList<> (); + + addPattern(DEFAULT, Pattern.compile("\\[(.+)\\]\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)(\\s+([0-9.]+))?")); + + Double initialLoad = getSetupValue ("initialLoad", Double.class); + if (initialLoad != null) { + m_cumulation = initialLoad; + m_history.offer (initialLoad); + } + } + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + // acquire the recent CPU load data +// String tstamp = m.group(1); + double userT = Double.parseDouble(m.group(2)); + double niceT = Double.parseDouble(m.group(3)); + double sysT = Double.parseDouble(m.group(4)); + double idleT = Double.parseDouble(m.group(5)); + double iowaitT = 0.0; + if (m.group(7) != null) { // optional iowait element is present + iowaitT = Double.parseDouble(m.group(7)); + } + double tLoad = userT + niceT + sysT + iowaitT; + // add value to cumulation and enqueue + m_cumulation += tLoad; + m_history.offer(tLoad); + if (m_history.size() > AVG_SAMPLE_WINDOW) { + // if queue size reached window size, then + // dequeue and delete oldest value and report average + m_cumulation -= m_history.poll(); + } + tLoad = m_cumulation / m_history.size(); + if (idleT < 1.0) { + // update server comp in model with requests per sec + m_reportingPort.trace (getComponentType (), "Updating server prop using load = " + tLoad); + // ZNewsSys.s0.load + IRainbowOperation cmd = getCommand (valueNames[0]); + Map pMap = new HashMap<> (); + pMap.put (cmd.getParameters ()[0], Double.toString (tLoad)); + issueCommand (cmd, pMap); + } + } + } + + @Override + protected void runAction () { + super.runAction (); + } +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/DiskIOGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/DiskIOGauge.java index 6b71c1452..1af94fd35 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/DiskIOGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/DiskIOGauge.java @@ -1,190 +1,190 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created November 1, 2006. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Gauge for aggregating Disk IO probe monitoring output. This gauge keeps a - * rolling historical window of size AVG_SAMPLE_WINDOW to compute average. - *

- * When there are multiple readings (e.g., multiple disks) per cycle, we - * combine those readings into a single reading. Assuming that the readings - * are simultaneous, then the number CPU ticks that elapsed would be equivalent, - * allowing us to simply add the reading values across the disks (since the - * factions essentially have the same denominators). - * - * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) - */ -public class DiskIOGauge extends RegularPatternGauge { - - public static final String NAME = "G - Disk IO"; - /** Sample window to compute an average load */ - public static final int AVG_SAMPLE_WINDOW = 10; - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "transferRate", - "readRate", - "writeRate", - "readSize", - "writeSize" - }; - private static final String DEFAULT = "DEFAULT"; - - private Queue m_history = null; - private Double[] m_cumulations = null; - private SimpleDateFormat m_dateFormat = null; - /** The lastTstamp and lastReading should be set together */ - private Date m_lastTstamp = null; - private Double[] m_lastReading = null; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public DiskIOGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - m_history = new LinkedList<> (); - m_cumulations = new Double[valueNames.length]; - for (int i=0; i < valueNames.length; ++i) { - m_cumulations[i] = 0.0; - } - m_dateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy"); - - addPattern(DEFAULT, Pattern.compile("\\[(.+)\\]\\s+(\\w+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)")); - - for (int i = 0; i < valueNames.length; ++i) { - Double val = getSetupValue (valueNames[i], Double.class); - if (val != null) { - if (m_cumulations == null) { - m_cumulations = new Double[valueNames.length]; - } - m_cumulations[i] = val; - Double[] values = m_history.peek (); - if (values == null) { - values = new Double[valueNames.length]; - m_history.offer (values); - } - values[i] = val; - } - } - } - - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - // acquire the recent disk IO data and add values to cumulation - Date tstamp = null; - try { - tstamp = m_dateFormat.parse(m.group(1)); - } catch (ParseException e) { - m_reportingPort.error (getComponentType (), id () + ": Date parsing error!", e); - } -// String devName = m.group(2); - Double[] values = new Double[valueNames.length]; - for (int i=0; i < valueNames.length; ++i) { - values[i] = Double.parseDouble(m.group(i+3)); - } - - if (m_lastTstamp != null && tstamp != null) { // determine timestamp difference - long diff = tstamp.getTime() - m_lastTstamp.getTime(); - if (diff <= 1000) { // within 1 second, treat as one reading - // merge results with previous reading, by addition of values - for (int i=0; i < values.length; ++i) { - m_lastReading[i] += values[i]; - } - } else { - // add lastReading to cumulation and enqueue lastReading - for (int i=0; i < valueNames.length; ++i) { - m_cumulations[i] += m_lastReading[i]; - } - m_history.offer(m_lastReading); - // save new array of values as lastReading - m_lastReading = values; - if (m_history.size() > AVG_SAMPLE_WINDOW) { - // if queue size reached window size, then dequeue and deduct oldest values - // NOTE: "values" reused below for oldest values - values = m_history.poll(); - for (int i=0; i < valueNames.length; ++i) { - m_cumulations[i] -= values[i]; - } - } - } - m_lastTstamp = tstamp; // store new timestamp - } else { - // store first-time new values to lastReading - m_lastReading = values; - if (tstamp != null) { - m_lastTstamp = tstamp; // store first timestamp - } - } - - // compute average - int size = m_history.size(); - if (size > 0) { - // NOTE: "values" declared anew to compute average values - values = new Double[valueNames.length]; - for (int i=0; i < valueNames.length; ++i) { - values[i] = m_cumulations[i] / size; - } - - // update server comp in model with requests per sec - m_reportingPort.trace (getComponentType (), "Updating server prop using values = " + values); - for (int i=0; i < valueNames.length; ++i) { - if (m_commands.containsKey (valueNames[i])) { - // ZNewsSys.s0., if "vName" exists in mapping - IRainbowOperation cmd = getCommand (valueNames[i]); - Map pMap = new HashMap<> (); - pMap.put (cmd.getParameters ()[0], Double.toString (values[i])); - issueCommand (cmd, pMap); - } - } - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Gauge for aggregating Disk IO probe monitoring output. This gauge keeps a + * rolling historical window of size AVG_SAMPLE_WINDOW to compute average. + *

+ * When there are multiple readings (e.g., multiple disks) per cycle, we + * combine those readings into a single reading. Assuming that the readings + * are simultaneous, then the number CPU ticks that elapsed would be equivalent, + * allowing us to simply add the reading values across the disks (since the + * factions essentially have the same denominators). + * + * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) + */ +public class DiskIOGauge extends RegularPatternGauge { + + public static final String NAME = "G - Disk IO"; + /** Sample window to compute an average load */ + public static final int AVG_SAMPLE_WINDOW = 10; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "transferRate", + "readRate", + "writeRate", + "readSize", + "writeSize" + }; + private static final String DEFAULT = "DEFAULT"; + + private Queue m_history = null; + private Double[] m_cumulations = null; + private SimpleDateFormat m_dateFormat = null; + /** The lastTstamp and lastReading should be set together */ + private Date m_lastTstamp = null; + private Double[] m_lastReading = null; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public DiskIOGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + m_history = new LinkedList<> (); + m_cumulations = new Double[valueNames.length]; + for (int i=0; i < valueNames.length; ++i) { + m_cumulations[i] = 0.0; + } + m_dateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy"); + + addPattern(DEFAULT, Pattern.compile("\\[(.+)\\]\\s+(\\w+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)")); + + for (int i = 0; i < valueNames.length; ++i) { + Double val = getSetupValue (valueNames[i], Double.class); + if (val != null) { + if (m_cumulations == null) { + m_cumulations = new Double[valueNames.length]; + } + m_cumulations[i] = val; + Double[] values = m_history.peek (); + if (values == null) { + values = new Double[valueNames.length]; + m_history.offer (values); + } + values[i] = val; + } + } + } + + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + // acquire the recent disk IO data and add values to cumulation + Date tstamp = null; + try { + tstamp = m_dateFormat.parse(m.group(1)); + } catch (ParseException e) { + m_reportingPort.error (getComponentType (), id () + ": Date parsing error!", e); + } +// String devName = m.group(2); + Double[] values = new Double[valueNames.length]; + for (int i=0; i < valueNames.length; ++i) { + values[i] = Double.parseDouble(m.group(i+3)); + } + + if (m_lastTstamp != null && tstamp != null) { // determine timestamp difference + long diff = tstamp.getTime() - m_lastTstamp.getTime(); + if (diff <= 1000) { // within 1 second, treat as one reading + // merge results with previous reading, by addition of values + for (int i=0; i < values.length; ++i) { + m_lastReading[i] += values[i]; + } + } else { + // add lastReading to cumulation and enqueue lastReading + for (int i=0; i < valueNames.length; ++i) { + m_cumulations[i] += m_lastReading[i]; + } + m_history.offer(m_lastReading); + // save new array of values as lastReading + m_lastReading = values; + if (m_history.size() > AVG_SAMPLE_WINDOW) { + // if queue size reached window size, then dequeue and deduct oldest values + // NOTE: "values" reused below for oldest values + values = m_history.poll(); + for (int i=0; i < valueNames.length; ++i) { + m_cumulations[i] -= values[i]; + } + } + } + m_lastTstamp = tstamp; // store new timestamp + } else { + // store first-time new values to lastReading + m_lastReading = values; + if (tstamp != null) { + m_lastTstamp = tstamp; // store first timestamp + } + } + + // compute average + int size = m_history.size(); + if (size > 0) { + // NOTE: "values" declared anew to compute average values + values = new Double[valueNames.length]; + for (int i=0; i < valueNames.length; ++i) { + values[i] = m_cumulations[i] / size; + } + + // update server comp in model with requests per sec + m_reportingPort.trace (getComponentType (), "Updating server prop using values = " + values); + for (int i=0; i < valueNames.length; ++i) { + if (m_commands.containsKey (valueNames[i])) { + // ZNewsSys.s0., if "vName" exists in mapping + IRainbowOperation cmd = getCommand (valueNames[i]); + Map pMap = new HashMap<> (); + pMap.put (cmd.getParameters ()[0], Double.toString (values[i])); + issueCommand (cmd, pMap); + } + } + } + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/DummyDiagnosisGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/DummyDiagnosisGauge.java index de6bffa25..9250ed834 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/DummyDiagnosisGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/DummyDiagnosisGauge.java @@ -1,224 +1,224 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IModelChangeBusPort; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; -import org.sa.rainbow.core.ports.IModelsManagerPort; -import org.sa.rainbow.core.ports.RainbowPortFactory; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class DummyDiagnosisGauge extends RegularPatternGauge { - - IModelsManagerPort m_modelPort; - - private final class CaptchaWatcher implements IRainbowModelChangeCallback { - @Override - public void onEvent (ModelReference mr, IRainbowMessage message) { - Object property = message.getProperty (IModelChangeBusPort.PARAMETER_PROP + "0"); - Object target = message.getProperty (IModelChangeBusPort.TARGET_PROP); - if (target instanceof String && property instanceof String) { - Boolean captchaEnabled = Boolean.valueOf ((String )property); - IModelInstance model = m_modelPort.getModelInstance (mr); - IAcmeSystem system = model.getModelInstance (); - Set components = system.getComponents (); - Set maliciousComponents = new HashSet<> (); - for (IAcmeComponent c : components) { - if (c.declaresType ("ClientT") && c.getProperty ("maliciousness") != null) { - IAcmeProperty m = c.getProperty ("maliciousness"); - float maliciousness = (float )PropertyHelper.toJavaVal (m.getValue ()); - if (maliciousness >= 0.9) { - maliciousComponents.add (c); - } - } - } - getReportingPort ().info (RainbowComponentT.GAUGE, "Dummy gauge responding to captcha enablement"); - for (IAcmeComponent m : maliciousComponents) { - Map pm = new HashMap<> (); - List ops = new ArrayList<> (2); - List> params = new ArrayList<> (2); - IRainbowOperation cmd = getCommand (valueNames[1]); - pm = new HashMap<> (); - pm.put (cmd.getParameters ()[0], captchaEnabled ? "-1" : "0"); - pm.put (cmd.getTarget (), m.getQualifiedName ()); - ops.add (cmd); - params.add (pm); - - cmd = getCommand (valueNames[2]); - pm = new HashMap<> (); - pm.put (cmd.getParameters ()[0], captchaEnabled ? "-1" : "0"); - pm.put (cmd.getTarget (), m.getQualifiedName ()); - ops.add (cmd); - params.add (pm); - - issueCommands (ops, params); - } - } - } - } - - private static final String NAME = "G - Dummy Diagnosis Gauge"; - private static final String DEFAULT = "default"; - private static final String[] valueNames = { "maliciousness(x)", "captcha(x)", "authenticate(x)" }; - private static final String AUTHENTICATION_ON = "AUTH_ON"; - private static final String AUTHENTICATION_OFF = "AUTH_OFF"; - - IModelChangeBusSubscriberPort m_modelChanges; - private boolean m_authenticationEnabled = false; - - public DummyDiagnosisGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern (DEFAULT, Pattern.compile ("([\\w_]+)=([\\d]+(\\.[\\d]*))")); - addPattern (AUTHENTICATION_ON, Pattern.compile ("^on$")); - addPattern (AUTHENTICATION_OFF, Pattern.compile ("^off$")); - - m_modelPort = RainbowPortFactory.createModelsManagerRequirerPort (); - - m_modelChanges = RainbowPortFactory.createModelChangeBusSubscriptionPort (); - - m_modelChanges.subscribe (new IRainbowChangeBusSubscription () { - - @Override - public boolean matches (IRainbowMessage message) { - return message.getPropertyNames ().contains (IModelChangeBusPort.COMMAND_PROP) - && message.getProperty (IModelChangeBusPort.COMMAND_PROP).equals ("setCaptchaEnabled"); - } - - }, new CaptchaWatcher ()); - - } - - @Override - protected void doMatch (String matchName, Matcher m) { - if (DEFAULT.equals (matchName)) { - String LB = m.group (1); - IRainbowOperation cmd = getCommand (valueNames[0]); - Map pm = new HashMap<> (); - pm.put (cmd.getParameters ()[0], m.group (2)); - pm.put (cmd.getTarget (), LB); - issueCommand (cmd, pm); - - // Issue the command that sets the captcha and authentication properties, in lieu of an actual gauge to do this - // ClientX.maliciousness >= 0.9 -> ClientX.captcha = ClientX.authenticate = -1 - // ClientX.maliciousness >= 0.5 -> ClientX.captcha = ClientX.authentica = rand () - String mal = m.group (2); - float maliciousness = Float.valueOf (mal); -// if (maliciousness >= 0.9f) { -// boolean captchaEnabled = false; -// ModelsManager modelsManager = Rainbow.instance ().getRainbowMaster ().modelsManager (); -// IModelInstance modelInstance = modelsManager. getModelInstance (modelDesc () -// .getType (), modelDesc ().getName ()); -// if (modelInstance != null) { -// IAcmeProperty cProp = modelInstance.getModelInstance ().getComponent ("LB0") -// .getProperty ("captchaEnabled"); -// if (cProp != null && cProp.getValue () != null -// && PropertyHelper.toJavaVal (cProp.getValue ()) == Boolean.TRUE) { -// captchaEnabled = true; -// } -// } -// if (captchaEnabled) { -// List ops = new ArrayList<> (2); -// List> params = new ArrayList<> (2); -// cmd = m_commands.get (valueNames[1]); -// pm = new HashMap<> (); -// pm.put (cmd.getParameters ()[0], "-1"); -// pm.put (cmd.getTarget (), LB); -// ops.add (cmd); -// params.add (pm); -// -// cmd = m_commands.get (valueNames[2]); -// pm = new HashMap<> (); -// pm.put (cmd.getParameters ()[0], "-1"); -// pm.put (cmd.getTarget (), LB); -// ops.add (cmd); -// params.add (pm); -// -// issueCommands (ops, params); -// } -// } -// else if (maliciousness >= 0.5f) { -// -// if (m_authenticationEnabled) { -// -// List ops = new ArrayList<> (2); -// List> params = new ArrayList<> (2); -// cmd = m_commands.get (valueNames[1]); -// pm = new HashMap<> (); -// String response = "-1"; -// if (Math.random () < 0.5) { -// response = "1"; -// } -// pm.put (cmd.getParameters ()[0], response); -// pm.put (cmd.getTarget (), LB); -// ops.add (cmd); -// params.add (pm); -// -// cmd = m_commands.get (valueNames[2]); -// pm = new HashMap<> (); -// response = "-1"; -// if (Math.random () < 0.5) { -// response = "1"; -// } -// pm.put (cmd.getParameters ()[0], response); -// pm.put (cmd.getTarget (), LB); -// ops.add (cmd); -// params.add (pm); -// -// issueCommands (ops, params); -// } -// } - -// String pClient = m_modelDesc.getName () + Util.DOT + m.group (1) + Util.DOT + "maliciousness"; -// eventHandler ().reportValue (new AttributeValueTriple (pClient, valueNames[0], m.group (2))); - } - else if (AUTHENTICATION_ON.equals (matchName)) { - m_authenticationEnabled = true; - } - else if (AUTHENTICATION_OFF.equals (matchName)) { - m_authenticationEnabled = false; - } - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class DummyDiagnosisGauge extends RegularPatternGauge { + + IModelsManagerPort m_modelPort; + + private final class CaptchaWatcher implements IRainbowModelChangeCallback { + @Override + public void onEvent (ModelReference mr, IRainbowMessage message) { + Object property = message.getProperty (IModelChangeBusPort.PARAMETER_PROP + "0"); + Object target = message.getProperty (IModelChangeBusPort.TARGET_PROP); + if (target instanceof String && property instanceof String) { + Boolean captchaEnabled = Boolean.valueOf ((String )property); + IModelInstance model = m_modelPort.getModelInstance (mr); + IAcmeSystem system = model.getModelInstance (); + Set components = system.getComponents (); + Set maliciousComponents = new HashSet<> (); + for (IAcmeComponent c : components) { + if (c.declaresType ("ClientT") && c.getProperty ("maliciousness") != null) { + IAcmeProperty m = c.getProperty ("maliciousness"); + float maliciousness = (float )PropertyHelper.toJavaVal (m.getValue ()); + if (maliciousness >= 0.9) { + maliciousComponents.add (c); + } + } + } + getReportingPort ().info (RainbowComponentT.GAUGE, "Dummy gauge responding to captcha enablement"); + for (IAcmeComponent m : maliciousComponents) { + Map pm = new HashMap<> (); + List ops = new ArrayList<> (2); + List> params = new ArrayList<> (2); + IRainbowOperation cmd = getCommand (valueNames[1]); + pm = new HashMap<> (); + pm.put (cmd.getParameters ()[0], captchaEnabled ? "-1" : "0"); + pm.put (cmd.getTarget (), m.getQualifiedName ()); + ops.add (cmd); + params.add (pm); + + cmd = getCommand (valueNames[2]); + pm = new HashMap<> (); + pm.put (cmd.getParameters ()[0], captchaEnabled ? "-1" : "0"); + pm.put (cmd.getTarget (), m.getQualifiedName ()); + ops.add (cmd); + params.add (pm); + + issueCommands (ops, params); + } + } + } + } + + private static final String NAME = "G - Dummy Diagnosis Gauge"; + private static final String DEFAULT = "default"; + private static final String[] valueNames = { "maliciousness(x)", "captcha(x)", "authenticate(x)" }; + private static final String AUTHENTICATION_ON = "AUTH_ON"; + private static final String AUTHENTICATION_OFF = "AUTH_OFF"; + + IModelChangeBusSubscriberPort m_modelChanges; + private boolean m_authenticationEnabled = false; + + public DummyDiagnosisGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile ("([\\w_]+)=([\\d]+(\\.[\\d]*))")); + addPattern (AUTHENTICATION_ON, Pattern.compile ("^on$")); + addPattern (AUTHENTICATION_OFF, Pattern.compile ("^off$")); + + m_modelPort = RainbowPortFactory.createModelsManagerRequirerPort (); + + m_modelChanges = RainbowPortFactory.createModelChangeBusSubscriptionPort (); + + m_modelChanges.subscribe (new IRainbowChangeBusSubscription () { + + @Override + public boolean matches (IRainbowMessage message) { + return message.getPropertyNames ().contains (IModelChangeBusPort.COMMAND_PROP) + && message.getProperty (IModelChangeBusPort.COMMAND_PROP).equals ("setCaptchaEnabled"); + } + + }, new CaptchaWatcher ()); + + } + + @Override + protected void doMatch (String matchName, Matcher m) { + if (DEFAULT.equals (matchName)) { + String LB = m.group (1); + IRainbowOperation cmd = getCommand (valueNames[0]); + Map pm = new HashMap<> (); + pm.put (cmd.getParameters ()[0], m.group (2)); + pm.put (cmd.getTarget (), LB); + issueCommand (cmd, pm); + + // Issue the command that sets the captcha and authentication properties, in lieu of an actual gauge to do this + // ClientX.maliciousness >= 0.9 -> ClientX.captcha = ClientX.authenticate = -1 + // ClientX.maliciousness >= 0.5 -> ClientX.captcha = ClientX.authentica = rand () + String mal = m.group (2); + float maliciousness = Float.valueOf (mal); +// if (maliciousness >= 0.9f) { +// boolean captchaEnabled = false; +// ModelsManager modelsManager = Rainbow.instance ().getRainbowMaster ().modelsManager (); +// IModelInstance modelInstance = modelsManager. getModelInstance (modelDesc () +// .getType (), modelDesc ().getName ()); +// if (modelInstance != null) { +// IAcmeProperty cProp = modelInstance.getModelInstance ().getComponent ("LB0") +// .getProperty ("captchaEnabled"); +// if (cProp != null && cProp.getValue () != null +// && PropertyHelper.toJavaVal (cProp.getValue ()) == Boolean.TRUE) { +// captchaEnabled = true; +// } +// } +// if (captchaEnabled) { +// List ops = new ArrayList<> (2); +// List> params = new ArrayList<> (2); +// cmd = m_commands.get (valueNames[1]); +// pm = new HashMap<> (); +// pm.put (cmd.getParameters ()[0], "-1"); +// pm.put (cmd.getTarget (), LB); +// ops.add (cmd); +// params.add (pm); +// +// cmd = m_commands.get (valueNames[2]); +// pm = new HashMap<> (); +// pm.put (cmd.getParameters ()[0], "-1"); +// pm.put (cmd.getTarget (), LB); +// ops.add (cmd); +// params.add (pm); +// +// issueCommands (ops, params); +// } +// } +// else if (maliciousness >= 0.5f) { +// +// if (m_authenticationEnabled) { +// +// List ops = new ArrayList<> (2); +// List> params = new ArrayList<> (2); +// cmd = m_commands.get (valueNames[1]); +// pm = new HashMap<> (); +// String response = "-1"; +// if (Math.random () < 0.5) { +// response = "1"; +// } +// pm.put (cmd.getParameters ()[0], response); +// pm.put (cmd.getTarget (), LB); +// ops.add (cmd); +// params.add (pm); +// +// cmd = m_commands.get (valueNames[2]); +// pm = new HashMap<> (); +// response = "-1"; +// if (Math.random () < 0.5) { +// response = "1"; +// } +// pm.put (cmd.getParameters ()[0], response); +// pm.put (cmd.getTarget (), LB); +// ops.add (cmd); +// params.add (pm); +// +// issueCommands (ops, params); +// } +// } + +// String pClient = m_modelDesc.getName () + Util.DOT + m.group (1) + Util.DOT + "maliciousness"; +// eventHandler ().reportValue (new AttributeValueTriple (pClient, valueNames[0], m.group (2))); + } + else if (AUTHENTICATION_ON.equals (matchName)) { + m_authenticationEnabled = true; + } + else if (AUTHENTICATION_OFF.equals (matchName)) { + m_authenticationEnabled = false; + } + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/End2EndRespTimeGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/End2EndRespTimeGauge.java index 93a13ca56..6c3918119 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/End2EndRespTimeGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/End2EndRespTimeGauge.java @@ -1,124 +1,124 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created April 11, 2007. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Gauge for estimating end-to-end response time of a server request, as - * experienced by a proxy client. - * - * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) - */ -public class End2EndRespTimeGauge extends RegularPatternGauge { - - public static final String NAME = "G - End-End Resp Time"; - /** Sample window to compute an average latency */ - public static final int AVG_SAMPLE_WINDOW = 5; - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "end2endRespTime(*)" - }; - private static final String DEFAULT = "DEFAULT"; - - private Map> m_historyMap = null; - private Map m_cumulationMap = null; - - /** - * Main constructor. - */ - public End2EndRespTimeGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, - TypedAttribute modelDesc, List setupParams, - Map mappings) throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - m_historyMap = new HashMap<> (); - m_cumulationMap = new HashMap<> (); - - addPattern (DEFAULT, Pattern.compile ("\\[(.+)\\]<(.+)>\\s+(.+?):([0-9.]+)ms")); - } - - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - // acquire the next set of ping RTT data, we care for the average -// String tstamp = m.group(1); - String id = m.group (2); - String host = id.split ("@")[1]; -// String host = m.group(3); - if (host.equals("")) return; - double dur = Double.parseDouble(m.group(4)); - - // setup data struct for host if new - if (! m_historyMap.containsKey(host)) { - m_historyMap.put(host, new LinkedList()); - m_cumulationMap.put(host, 0.0); - } - Queue history = m_historyMap.get(host); - double cumulation = m_cumulationMap.get(host); - // add value to cumulation and enqueue - cumulation += dur; - history.offer(dur); - if (history.size() > AVG_SAMPLE_WINDOW) { - // if queue size reached window size, then - // dequeue and delete oldest value and report average - cumulation -= history.poll(); - } - m_cumulationMap.put(host, cumulation); // store updated cumulation - dur = cumulation / history.size(); - m_reportingPort.trace (getComponentType (), - id () + ": " + cumulation + ", hist" + Arrays.toString (history.toArray ())); - - // update connection in model with latency in seconds - for (String valueName : valueNames) { - // massage value name for mapping purposes - valueName = valueName.replace("*", host); - if (m_commands.containsKey (valueName)) { - // ZNewsSys.c0.experRespTime - IRainbowOperation cmd = getCommand (valueName); - Map parameterMap = new HashMap<> (); - parameterMap.put (cmd.getParameters ()[0], Double.toString (dur)); - issueCommand (cmd, parameterMap); - } - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created April 11, 2007. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Gauge for estimating end-to-end response time of a server request, as + * experienced by a proxy client. + * + * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) + */ +public class End2EndRespTimeGauge extends RegularPatternGauge { + + public static final String NAME = "G - End-End Resp Time"; + /** Sample window to compute an average latency */ + public static final int AVG_SAMPLE_WINDOW = 5; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "end2endRespTime(*)" + }; + private static final String DEFAULT = "DEFAULT"; + + private Map> m_historyMap = null; + private Map m_cumulationMap = null; + + /** + * Main constructor. + */ + public End2EndRespTimeGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, + TypedAttribute modelDesc, List setupParams, + Map mappings) throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + m_historyMap = new HashMap<> (); + m_cumulationMap = new HashMap<> (); + + addPattern (DEFAULT, Pattern.compile ("\\[(.+)\\]<(.+)>\\s+(.+?):([0-9.]+)ms")); + } + + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + // acquire the next set of ping RTT data, we care for the average +// String tstamp = m.group(1); + String id = m.group (2); + String host = id.split ("@")[1]; +// String host = m.group(3); + if (host.equals("")) return; + double dur = Double.parseDouble(m.group(4)); + + // setup data struct for host if new + if (! m_historyMap.containsKey(host)) { + m_historyMap.put(host, new LinkedList()); + m_cumulationMap.put(host, 0.0); + } + Queue history = m_historyMap.get(host); + double cumulation = m_cumulationMap.get(host); + // add value to cumulation and enqueue + cumulation += dur; + history.offer(dur); + if (history.size() > AVG_SAMPLE_WINDOW) { + // if queue size reached window size, then + // dequeue and delete oldest value and report average + cumulation -= history.poll(); + } + m_cumulationMap.put(host, cumulation); // store updated cumulation + dur = cumulation / history.size(); + m_reportingPort.trace (getComponentType (), + id () + ": " + cumulation + ", hist" + Arrays.toString (history.toArray ())); + + // update connection in model with latency in seconds + for (String valueName : valueNames) { + // massage value name for mapping purposes + valueName = valueName.replace("*", host); + if (m_commands.containsKey (valueName)) { + // ZNewsSys.c0.experRespTime + IRainbowOperation cmd = getCommand (valueName); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], Double.toString (dur)); + issueCommand (cmd, parameterMap); + } + } + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/FidelityGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/FidelityGauge.java index b2f80b778..c6580aaf6 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/FidelityGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/FidelityGauge.java @@ -1,103 +1,103 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created November 1, 2006. - */ -package org.sa.rainbow.translator.znn.gauges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -/** - * Gauge for consuming Apache Top's monitoring output. - * - * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) - */ -public class FidelityGauge extends RegularPatternGauge { - - public static final String NAME = "G - Server Fidelity"; - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "fidelity" - }; - private static final String DEFAULT = "DEFAULT"; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public FidelityGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern (DEFAULT, Pattern.compile ("\\[(.+)\\] (\\w+)")); - } - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - // acquire the recent CPU load data -// String tstamp = m.group(1); - String fidelity = m.group(2); - - // update server comp in model with requests per sec - m_reportingPort.trace (getComponentType (), "Updating server prop using fidelity = " + fidelity); - // ZNewsSys.s0.fidelity - if (m_commands.containsKey (valueNames[0])) { - // ZNewsSys.conn0.latency - IRainbowOperation cmd = getCommand (valueNames[0]); - Map parameterMap = new HashMap<> (); - String acmeFidelity = "5"; - switch (fidelity) { - case "low": - acmeFidelity = "1"; - break; - case "text": - acmeFidelity = "3"; - break; - - } - parameterMap.put (cmd.getParameters ()[0], acmeFidelity); - issueCommand (cmd, parameterMap); - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created November 1, 2006. + */ +package org.sa.rainbow.translator.znn.gauges; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +/** + * Gauge for consuming Apache Top's monitoring output. + * + * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) + */ +public class FidelityGauge extends RegularPatternGauge { + + public static final String NAME = "G - Server Fidelity"; + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "fidelity" + }; + private static final String DEFAULT = "DEFAULT"; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public FidelityGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile ("\\[(.+)\\] (\\w+)")); + } + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.AbstractGauge#initProperty(java.lang.String, java.lang.Object) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + // acquire the recent CPU load data +// String tstamp = m.group(1); + String fidelity = m.group(2); + + // update server comp in model with requests per sec + m_reportingPort.trace (getComponentType (), "Updating server prop using fidelity = " + fidelity); + // ZNewsSys.s0.fidelity + if (m_commands.containsKey (valueNames[0])) { + // ZNewsSys.conn0.latency + IRainbowOperation cmd = getCommand (valueNames[0]); + Map parameterMap = new HashMap<> (); + String acmeFidelity = "5"; + switch (fidelity) { + case "low": + acmeFidelity = "1"; + break; + case "text": + acmeFidelity = "3"; + break; + + } + parameterMap.put (cmd.getParameters ()[0], acmeFidelity); + issueCommand (cmd, parameterMap); + } + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RequestRateBasedMaliciousnessGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RequestRateBasedMaliciousnessGauge.java index 6b8460ffd..23c9000bb 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RequestRateBasedMaliciousnessGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RequestRateBasedMaliciousnessGauge.java @@ -1,144 +1,144 @@ -package org.sa.rainbow.translator.znn.gauges; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.gauges.AbstractGauge; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IModelChangeBusPort; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; -import org.sa.rainbow.core.ports.RainbowPortFactory; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.model.acme.AcmeRainbowOperationEvent.CommandEventT; -import org.sa.rainbow.translator.znn.gauges.ClientResponseTimeGauge.ModelBasedSubscription; - -import java.util.*; - -public class RequestRateBasedMaliciousnessGauge extends AbstractGauge { - - /** Matches a setClientRequestRate operation ending on the model manager **/ - public class RequestRatePropertySubscription extends ModelBasedSubscription { - - public RequestRatePropertySubscription (String modelName, String modelType) { - super (modelName, modelType); - } - - @Override - public boolean matches (IRainbowMessage message) { - boolean b = super.matches (message); - String type = (String )message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); - if (type != null) { - try { - CommandEventT ct = CommandEventT.valueOf (type); - b &= ct.isEnd () - && message.getProperty (IModelChangeBusPort.COMMAND_PROP).equals ("setClientRequestRate"); - return b; - } - catch (Exception e) { - } - } - return false; - } - - } - - private static final String NAME = "G - RR Based Maliciousness"; - - private Map m_maliciousnessMap = new HashMap<> (); - private float m_maliciousRequestRate = 10.0f; - private String m_reqRateProperty = "reqRate"; - - private IModelChangeBusSubscriberPort m_modelChanges; - - static final String[] commandNames = { "setMaliciousness" }; - - /* Both these queues should be synchronized */ - final Queue m_ops = new LinkedList<> (); - Queue> m_parameters = new LinkedList<> (); - - public RequestRateBasedMaliciousnessGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, - TypedAttribute modelDesc, List setupParams, - Map mappings) throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - m_modelChanges = RainbowPortFactory.createModelChangeBusSubscriptionPort (); - m_modelChanges.subscribe (new RequestRatePropertySubscription (modelDesc.getName (), modelDesc.getType ()), - new ProcessRequestRate ()); - } - - @Override - protected void handleConfigParam (TypedAttributeWithValue cfp) { - super.handleConfigParam (cfp); - if ("maliciousRequestRate".equals (cfp.getName ())) { - m_maliciousRequestRate = (Float )cfp.getValue (); - } - if ("requestRateProperty".equals (cfp.getName ())) { - m_reqRateProperty = (String )cfp.getValue (); - } - } - - @Override - protected void runAction () { - super.runAction (); - IRainbowOperation cmd = null; - Map params = null; - List cmds = new LinkedList<> (); - List> pms = new LinkedList<> (); - synchronized (m_ops) { - cmd = m_ops.poll (); - if (cmd != null) { - cmds.add (cmd); - pms.add (m_parameters.poll ()); - while ((cmd = m_ops.poll ()) != null) { - cmds.add (cmd); - pms.add (m_parameters.poll ()); - } - } - } - if (!cmds.isEmpty ()) { - issueCommands (cmds, pms); - } - - } - - // This gauge listens to changes to the property request rate on clients - public class ProcessRequestRate implements IRainbowModelChangeCallback { - - @Override - public void onEvent (ModelReference reference, IRainbowMessage message) { - if (!isTerminated ()) { - String client = (String )message.getProperty (IModelChangeBusPort.TARGET_PROP); - String reqRateString = (String )message.getProperty (IModelChangeBusPort.PARAMETER_PROP + "0"); - Float reqRate = Float.valueOf (reqRateString); - - Float currentMaliciousness = m_maliciousnessMap.get (client); - if (currentMaliciousness == null) { - // set the current value to the opposite of what it should be to force a command - currentMaliciousness = isMaliciousRate (reqRate) ? 0f : 1f; - m_maliciousnessMap.put (client, currentMaliciousness); - } - - IRainbowOperation cmd = getCommand (commandNames[0]); - Map pm = new HashMap<> (); - pm.put (cmd.getTarget (), client); - currentMaliciousness = isMaliciousRate (reqRate) ? 1.0f : 0.0f; - - if (!m_maliciousnessMap.get (client).equals (currentMaliciousness)) { - pm.put (cmd.getParameters ()[0], currentMaliciousness.toString ()); - m_maliciousnessMap.put (client, currentMaliciousness); - synchronized (m_ops) { - m_ops.offer (cmd); - m_parameters.offer (pm); - } - } - } - } - - } - - boolean isMaliciousRate (Float reqRate) { - return reqRate >= m_maliciousRequestRate; - } -} +package org.sa.rainbow.translator.znn.gauges; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.gauges.AbstractGauge; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.model.acme.AcmeRainbowOperationEvent.CommandEventT; +import org.sa.rainbow.translator.znn.gauges.ClientResponseTimeGauge.ModelBasedSubscription; + +import java.util.*; + +public class RequestRateBasedMaliciousnessGauge extends AbstractGauge { + + /** Matches a setClientRequestRate operation ending on the model manager **/ + public class RequestRatePropertySubscription extends ModelBasedSubscription { + + public RequestRatePropertySubscription (String modelName, String modelType) { + super (modelName, modelType); + } + + @Override + public boolean matches (IRainbowMessage message) { + boolean b = super.matches (message); + String type = (String )message.getProperty (IModelChangeBusPort.EVENT_TYPE_PROP); + if (type != null) { + try { + CommandEventT ct = CommandEventT.valueOf (type); + b &= ct.isEnd () + && message.getProperty (IModelChangeBusPort.COMMAND_PROP).equals ("setClientRequestRate"); + return b; + } + catch (Exception e) { + } + } + return false; + } + + } + + private static final String NAME = "G - RR Based Maliciousness"; + + private Map m_maliciousnessMap = new HashMap<> (); + private float m_maliciousRequestRate = 10.0f; + private String m_reqRateProperty = "reqRate"; + + private IModelChangeBusSubscriberPort m_modelChanges; + + static final String[] commandNames = { "setMaliciousness" }; + + /* Both these queues should be synchronized */ + final Queue m_ops = new LinkedList<> (); + Queue> m_parameters = new LinkedList<> (); + + public RequestRateBasedMaliciousnessGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, + TypedAttribute modelDesc, List setupParams, + Map mappings) throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + m_modelChanges = RainbowPortFactory.createModelChangeBusSubscriptionPort (); + m_modelChanges.subscribe (new RequestRatePropertySubscription (modelDesc.getName (), modelDesc.getType ()), + new ProcessRequestRate ()); + } + + @Override + protected void handleConfigParam (TypedAttributeWithValue cfp) { + super.handleConfigParam (cfp); + if ("maliciousRequestRate".equals (cfp.getName ())) { + m_maliciousRequestRate = (Float )cfp.getValue (); + } + if ("requestRateProperty".equals (cfp.getName ())) { + m_reqRateProperty = (String )cfp.getValue (); + } + } + + @Override + protected void runAction () { + super.runAction (); + IRainbowOperation cmd = null; + Map params = null; + List cmds = new LinkedList<> (); + List> pms = new LinkedList<> (); + synchronized (m_ops) { + cmd = m_ops.poll (); + if (cmd != null) { + cmds.add (cmd); + pms.add (m_parameters.poll ()); + while ((cmd = m_ops.poll ()) != null) { + cmds.add (cmd); + pms.add (m_parameters.poll ()); + } + } + } + if (!cmds.isEmpty ()) { + issueCommands (cmds, pms); + } + + } + + // This gauge listens to changes to the property request rate on clients + public class ProcessRequestRate implements IRainbowModelChangeCallback { + + @Override + public void onEvent (ModelReference reference, IRainbowMessage message) { + if (!isTerminated ()) { + String client = (String )message.getProperty (IModelChangeBusPort.TARGET_PROP); + String reqRateString = (String )message.getProperty (IModelChangeBusPort.PARAMETER_PROP + "0"); + Float reqRate = Float.valueOf (reqRateString); + + Float currentMaliciousness = m_maliciousnessMap.get (client); + if (currentMaliciousness == null) { + // set the current value to the opposite of what it should be to force a command + currentMaliciousness = isMaliciousRate (reqRate) ? 0f : 1f; + m_maliciousnessMap.put (client, currentMaliciousness); + } + + IRainbowOperation cmd = getCommand (commandNames[0]); + Map pm = new HashMap<> (); + pm.put (cmd.getTarget (), client); + currentMaliciousness = isMaliciousRate (reqRate) ? 1.0f : 0.0f; + + if (!m_maliciousnessMap.get (client).equals (currentMaliciousness)) { + pm.put (cmd.getParameters ()[0], currentMaliciousness.toString ()); + m_maliciousnessMap.put (client, currentMaliciousness); + synchronized (m_ops) { + m_ops.offer (cmd); + m_parameters.offer (pm); + } + } + } + } + + } + + boolean isMaliciousRate (Float reqRate) { + return reqRate >= m_maliciousRequestRate; + } +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyGauge.java index 9056c8c44..4c11d2312 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyGauge.java @@ -1,118 +1,118 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created March 18, 2007. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.translator.znn.probes.PingRTTProbe; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Gauge for computing roundtrip latency of N KB data using Ping RTT data (PingRTTProbe). - * - * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) - */ -public class RtLatencyGauge extends RegularPatternGauge { - - public static final String NAME = "G - Latency"; - /** Sample window to compute an average latency */ - public static final int AVG_SAMPLE_WINDOW = 5; - /** Standard Ping request size */ - public static final int PING_SIZE = PingRTTProbe.PING_REQ_SIZE; - /** The estimated size of data we'll use to compute roundtrip latency */ - public static final int LATENCY_DATA_SIZE = 1024; // one KB - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "latency" - }; - private static final String DEFAULT = "DEFAULT"; - - private Queue m_history = null; - private double m_cumulation = 0; - - /** - * Main constructor. - */ - public RtLatencyGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - m_history = new LinkedList<> (); - - addPattern (DEFAULT, Pattern.compile ("\\[(.+)\\]\\s+(.+?):([0-9.]+)[/]([0-9.]+)[/]([0-9.]+)")); - - Double initalLatency = getSetupValue (valueNames[0], Double.class); - if (initalLatency != null) { - m_cumulation = initalLatency; - m_history.offer (initalLatency); - } - } - - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - // acquire the next set of ping RTT data, we care for the average -// String tstamp = m.group(1); -// String host = m.group(2); -// double msMin = Double.parseDouble(m.group(3)); - double msAvg = Double.parseDouble(m.group(4)); -// double msMax = Double.parseDouble(m.group(5)); - double bwBPS = PING_SIZE /*B*/ * 1000 /*ms/s*/ / msAvg /*ms*/; - double latency = LATENCY_DATA_SIZE / bwBPS; - // add value to cumulation and enqueue - m_cumulation += latency; - m_history.offer(latency); - if (m_history.size() > AVG_SAMPLE_WINDOW) { - // if queue size reached window size, then - // dequeue and delete oldest value and report average - m_cumulation -= m_history.poll(); - } - latency = m_cumulation / m_history.size(); - // update connection in model with latency in seconds - if (m_commands.containsKey (valueNames[0])) { - // ZNewsSys.conn0.latency - IRainbowOperation cmd = getCommand (valueNames[0]); - Map parameterMap = new HashMap<> (); - parameterMap.put (cmd.getParameters ()[0], Double.toString (latency)); - issueCommand (cmd, parameterMap); - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created March 18, 2007. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.translator.znn.probes.PingRTTProbe; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Gauge for computing roundtrip latency of N KB data using Ping RTT data (PingRTTProbe). + * + * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) + */ +public class RtLatencyGauge extends RegularPatternGauge { + + public static final String NAME = "G - Latency"; + /** Sample window to compute an average latency */ + public static final int AVG_SAMPLE_WINDOW = 5; + /** Standard Ping request size */ + public static final int PING_SIZE = PingRTTProbe.PING_REQ_SIZE; + /** The estimated size of data we'll use to compute roundtrip latency */ + public static final int LATENCY_DATA_SIZE = 1024; // one KB + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "latency" + }; + private static final String DEFAULT = "DEFAULT"; + + private Queue m_history = null; + private double m_cumulation = 0; + + /** + * Main constructor. + */ + public RtLatencyGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + m_history = new LinkedList<> (); + + addPattern (DEFAULT, Pattern.compile ("\\[(.+)\\]\\s+(.+?):([0-9.]+)[/]([0-9.]+)[/]([0-9.]+)")); + + Double initalLatency = getSetupValue (valueNames[0], Double.class); + if (initalLatency != null) { + m_cumulation = initalLatency; + m_history.offer (initalLatency); + } + } + + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + // acquire the next set of ping RTT data, we care for the average +// String tstamp = m.group(1); +// String host = m.group(2); +// double msMin = Double.parseDouble(m.group(3)); + double msAvg = Double.parseDouble(m.group(4)); +// double msMax = Double.parseDouble(m.group(5)); + double bwBPS = PING_SIZE /*B*/ * 1000 /*ms/s*/ / msAvg /*ms*/; + double latency = LATENCY_DATA_SIZE / bwBPS; + // add value to cumulation and enqueue + m_cumulation += latency; + m_history.offer(latency); + if (m_history.size() > AVG_SAMPLE_WINDOW) { + // if queue size reached window size, then + // dequeue and delete oldest value and report average + m_cumulation -= m_history.poll(); + } + latency = m_cumulation / m_history.size(); + // update connection in model with latency in seconds + if (m_commands.containsKey (valueNames[0])) { + // ZNewsSys.conn0.latency + IRainbowOperation cmd = getCommand (valueNames[0]); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], Double.toString (latency)); + issueCommand (cmd, parameterMap); + } + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyMultiHostGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyMultiHostGauge.java index af909d66f..8dc2c1290 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyMultiHostGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyMultiHostGauge.java @@ -1,134 +1,134 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created April 9, 2007. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.translator.znn.probes.PingRTTProbe; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Gauge for computing roundtrip latency of N KB data using Ping RTT data - * (PingRTTProbe) between Gauge's host and a list of target hosts. - * - * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) - */ -public class RtLatencyMultiHostGauge extends RegularPatternGauge { - - public static final String NAME = "G - Latency"; - /** Sample window to compute an average latency */ - public static final int AVG_SAMPLE_WINDOW = 5; - /** Standard Ping request size */ - public static final int PING_SIZE = PingRTTProbe.PING_REQ_SIZE; - /** The estimated size of data we'll use to compute roundtrip latency */ - public static final int LATENCY_DATA_SIZE = 1024; // one KB - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "latency(*)" - }; - private static final String DEFAULT = "DEFAULT"; - - private Map> m_historyMap = null; - private Map m_cumulationMap = null; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public RtLatencyMultiHostGauge (String threadName, String id, long beaconPeriod, TypedAttribute gaugeDesc, - TypedAttribute modelDesc, List setupParams, - Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - m_historyMap = new HashMap<> (); - m_cumulationMap = new HashMap<> (); - - addPattern(DEFAULT, Pattern.compile("\\[(.+)\\]\\s+(.+?):([0-9.]+)[/]([0-9.]+)[/]([0-9.]+)")); - } - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - // acquire the next set of ping RTT data, we care for the average -// String tstamp = m.group(1); - String host = m.group(2); - if (host.equals("")) return; -// double msMin = Double.parseDouble(m.group(3)); - double msAvg = Double.parseDouble(m.group(4)); -// double msMax = Double.parseDouble(m.group(5)); - double bwBPS = PING_SIZE /*B*/ * 1000 /*ms/s*/ / msAvg /*ms*/; - double latency = LATENCY_DATA_SIZE / bwBPS; - - // setup data struct for host if new - if (! m_historyMap.containsKey(host)) { - m_historyMap.put(host, new LinkedList()); - m_cumulationMap.put(host, 0.0); - } - Queue history = m_historyMap.get(host); - double cumulation = m_cumulationMap.get(host); - // add value to cumulation and enqueue - cumulation += latency; - history.offer(latency); - if (history.size() > AVG_SAMPLE_WINDOW) { - // if queue size reached window size, then - // dequeue and delete oldest value and report average - cumulation -= history.poll(); - } - m_cumulationMap.put(host, cumulation); // store updated cumulation - latency = cumulation / history.size(); - m_reportingPort.trace (getComponentType (), - id () + ": " + cumulation + ", hist" + Arrays.toString (history.toArray ())); - - // update connection in model with latency in seconds - for (String valueName : valueNames) { - // massage value name for mapping purposes - valueName = valueName.replace("*", host); - if (m_commands.containsKey (valueName)) { - // ZNewsSys.conn0.latency - IRainbowOperation cmd = getCommand (valueName); - Map parameterMap = new HashMap<> (); - parameterMap.put (cmd.getParameters ()[0], Double.toString (latency)); - issueCommand (cmd, parameterMap); - } - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created April 9, 2007. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.translator.znn.probes.PingRTTProbe; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Gauge for computing roundtrip latency of N KB data using Ping RTT data + * (PingRTTProbe) between Gauge's host and a list of target hosts. + * + * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) + */ +public class RtLatencyMultiHostGauge extends RegularPatternGauge { + + public static final String NAME = "G - Latency"; + /** Sample window to compute an average latency */ + public static final int AVG_SAMPLE_WINDOW = 5; + /** Standard Ping request size */ + public static final int PING_SIZE = PingRTTProbe.PING_REQ_SIZE; + /** The estimated size of data we'll use to compute roundtrip latency */ + public static final int LATENCY_DATA_SIZE = 1024; // one KB + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "latency(*)" + }; + private static final String DEFAULT = "DEFAULT"; + + private Map> m_historyMap = null; + private Map m_cumulationMap = null; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public RtLatencyMultiHostGauge (String threadName, String id, long beaconPeriod, TypedAttribute gaugeDesc, + TypedAttribute modelDesc, List setupParams, + Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + m_historyMap = new HashMap<> (); + m_cumulationMap = new HashMap<> (); + + addPattern(DEFAULT, Pattern.compile("\\[(.+)\\]\\s+(.+?):([0-9.]+)[/]([0-9.]+)[/]([0-9.]+)")); + } + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + // acquire the next set of ping RTT data, we care for the average +// String tstamp = m.group(1); + String host = m.group(2); + if (host.equals("")) return; +// double msMin = Double.parseDouble(m.group(3)); + double msAvg = Double.parseDouble(m.group(4)); +// double msMax = Double.parseDouble(m.group(5)); + double bwBPS = PING_SIZE /*B*/ * 1000 /*ms/s*/ / msAvg /*ms*/; + double latency = LATENCY_DATA_SIZE / bwBPS; + + // setup data struct for host if new + if (! m_historyMap.containsKey(host)) { + m_historyMap.put(host, new LinkedList()); + m_cumulationMap.put(host, 0.0); + } + Queue history = m_historyMap.get(host); + double cumulation = m_cumulationMap.get(host); + // add value to cumulation and enqueue + cumulation += latency; + history.offer(latency); + if (history.size() > AVG_SAMPLE_WINDOW) { + // if queue size reached window size, then + // dequeue and delete oldest value and report average + cumulation -= history.poll(); + } + m_cumulationMap.put(host, cumulation); // store updated cumulation + latency = cumulation / history.size(); + m_reportingPort.trace (getComponentType (), + id () + ": " + cumulation + ", hist" + Arrays.toString (history.toArray ())); + + // update connection in model with latency in seconds + for (String valueName : valueNames) { + // massage value name for mapping purposes + valueName = valueName.replace("*", host); + if (m_commands.containsKey (valueName)) { + // ZNewsSys.conn0.latency + IRainbowOperation cmd = getCommand (valueName); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], Double.toString (latency)); + issueCommand (cmd, parameterMap); + } + } + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyRateMultiHostGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyRateMultiHostGauge.java index deb253c20..383e1775a 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyRateMultiHostGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/RtLatencyRateMultiHostGauge.java @@ -1,160 +1,160 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -/** - * Created April 10, 2007. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.translator.znn.probes.PingRTTProbe; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Gauge for computing rate of change of roundtrip latency for N KB data using - * Ping RTT data (PingRTTProbe) between Gauge's host and a list of target hosts. - * - * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) - */ -public class RtLatencyRateMultiHostGauge extends RegularPatternGauge { - - public static final String NAME = "G - Latency Rate-of-Change"; - /** Sample window to compute an average latency */ - public static final int AVG_SAMPLE_WINDOW = 5; - /** Sample window to compute latency rate, roughly half of window for average */ - public static final int RATE_SAMPLE_WINDOW = 3; - /** Standard Ping request size */ - public static final int PING_SIZE = PingRTTProbe.PING_REQ_SIZE; - /** The estimated size of data we'll use to compute roundtrip latency */ - public static final int LATENCY_DATA_SIZE = 1024; // one KB - - /** List of values reported by this Gauge */ - private static final String[] valueNames = { - "latencyRate(*)" - }; - private static final String DEFAULT = "DEFAULT"; - - private Map> m_historyMap = null; - private Map m_cumulationMap = null; - private Map m_offsetCumulationMap = null; - private Map> m_rateHistMap = null; - private Map m_rateCumuMap = null; - - /** - * Main constructor. - * - * @throws RainbowException - */ - public RtLatencyRateMultiHostGauge (String threadName, String id, long beaconPeriod, TypedAttribute gaugeDesc, - TypedAttribute modelDesc, List setupParams, - Map mappings) - throws RainbowException { - - super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - m_historyMap = new HashMap<> (); - m_cumulationMap = new HashMap<> (); - m_offsetCumulationMap = new HashMap<> (); - m_rateHistMap = new HashMap<> (); - m_rateCumuMap = new HashMap<> (); - - addPattern(DEFAULT, Pattern.compile("\\[(.+)\\]\\s+(.+?):([0-9.]+)[/]([0-9.]+)[/]([0-9.]+)")); - } - - /* (non-Javadoc) - * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) - */ - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - // acquire the next set of ping RTT data, we care for the average -// String tstamp = m.group(1); - String host = m.group(2); - if (host.equals("")) return; -// double msMin = Double.parseDouble(m.group(3)); - double msAvg = Double.parseDouble(m.group(4)); -// double msMax = Double.parseDouble(m.group(5)); - double bwBPS = PING_SIZE /*B*/ * 1000 /*ms/s*/ / msAvg /*ms*/; - double latency = LATENCY_DATA_SIZE / bwBPS; - - // setup data struct for host if new - if (! m_historyMap.containsKey(host)) { - m_historyMap.put(host, new LinkedList()); - m_cumulationMap.put(host, 0.0); - m_offsetCumulationMap.put(host, 0.0); - m_rateHistMap.put(host, new LinkedList()); - m_rateCumuMap.put(host, 0.0); - } - Queue history = m_historyMap.get(host); - double cumulation = m_cumulationMap.get(host); - double offsetCumulation = m_offsetCumulationMap.get(host); - // add latency value to cumulation and enqueue - m_offsetCumulationMap.put(host, cumulation); // store previous as offset - cumulation += latency; - history.offer(latency); - if (history.size() > AVG_SAMPLE_WINDOW) { - // if queue size reached window size, then - // dequeue and delete oldest value and report average - cumulation -= history.poll(); - } - m_cumulationMap.put(host, cumulation); // store updated cumulation - if (offsetCumulation == 0) return; // most likely no history yet - - double rateOfChange = (cumulation - offsetCumulation) / offsetCumulation; - Queue rateHist = m_rateHistMap.get(host); - double rateCumu = m_rateCumuMap.get(host); - rateCumu += rateOfChange; - rateHist.offer(rateOfChange); - if (rateHist.size() > RATE_SAMPLE_WINDOW) { - rateCumu -= rateHist.poll(); - } - m_rateCumuMap.put(host, rateCumu); - rateOfChange = rateCumu / rateHist.size(); - m_reportingPort.trace (getComponentType (), - id () + ": " + cumulation + ", hist" + Arrays.toString (history.toArray ())); - m_reportingPort.trace (getComponentType (), - id () + ": " + rateCumu + ", hist" + Arrays.toString (rateHist.toArray ())); - - // update connection in model with latency in seconds - for (String valueName : valueNames) { - // massage value name for mapping purposes - valueName = valueName.replace("*", host); - if (m_commands.containsKey (valueName)) { - // ZNewsSys.conn0.latency - IRainbowOperation cmd = getCommand (valueName); - Map parameterMap = new HashMap<> (); - parameterMap.put (cmd.getParameters ()[0], Double.toString (rateOfChange)); - issueCommand (cmd, parameterMap); - } - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * Created April 10, 2007. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.translator.znn.probes.PingRTTProbe; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Gauge for computing rate of change of roundtrip latency for N KB data using + * Ping RTT data (PingRTTProbe) between Gauge's host and a list of target hosts. + * + * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) + */ +public class RtLatencyRateMultiHostGauge extends RegularPatternGauge { + + public static final String NAME = "G - Latency Rate-of-Change"; + /** Sample window to compute an average latency */ + public static final int AVG_SAMPLE_WINDOW = 5; + /** Sample window to compute latency rate, roughly half of window for average */ + public static final int RATE_SAMPLE_WINDOW = 3; + /** Standard Ping request size */ + public static final int PING_SIZE = PingRTTProbe.PING_REQ_SIZE; + /** The estimated size of data we'll use to compute roundtrip latency */ + public static final int LATENCY_DATA_SIZE = 1024; // one KB + + /** List of values reported by this Gauge */ + private static final String[] valueNames = { + "latencyRate(*)" + }; + private static final String DEFAULT = "DEFAULT"; + + private Map> m_historyMap = null; + private Map m_cumulationMap = null; + private Map m_offsetCumulationMap = null; + private Map> m_rateHistMap = null; + private Map m_rateCumuMap = null; + + /** + * Main constructor. + * + * @throws RainbowException + */ + public RtLatencyRateMultiHostGauge (String threadName, String id, long beaconPeriod, TypedAttribute gaugeDesc, + TypedAttribute modelDesc, List setupParams, + Map mappings) + throws RainbowException { + + super(NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + m_historyMap = new HashMap<> (); + m_cumulationMap = new HashMap<> (); + m_offsetCumulationMap = new HashMap<> (); + m_rateHistMap = new HashMap<> (); + m_rateCumuMap = new HashMap<> (); + + addPattern(DEFAULT, Pattern.compile("\\[(.+)\\]\\s+(.+?):([0-9.]+)[/]([0-9.]+)[/]([0-9.]+)")); + } + + /* (non-Javadoc) + * @see org.sa.rainbow.translator.gauges.RegularPatternGauge#doMatch(java.lang.String, java.util.regex.Matcher) + */ + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + // acquire the next set of ping RTT data, we care for the average +// String tstamp = m.group(1); + String host = m.group(2); + if (host.equals("")) return; +// double msMin = Double.parseDouble(m.group(3)); + double msAvg = Double.parseDouble(m.group(4)); +// double msMax = Double.parseDouble(m.group(5)); + double bwBPS = PING_SIZE /*B*/ * 1000 /*ms/s*/ / msAvg /*ms*/; + double latency = LATENCY_DATA_SIZE / bwBPS; + + // setup data struct for host if new + if (! m_historyMap.containsKey(host)) { + m_historyMap.put(host, new LinkedList()); + m_cumulationMap.put(host, 0.0); + m_offsetCumulationMap.put(host, 0.0); + m_rateHistMap.put(host, new LinkedList()); + m_rateCumuMap.put(host, 0.0); + } + Queue history = m_historyMap.get(host); + double cumulation = m_cumulationMap.get(host); + double offsetCumulation = m_offsetCumulationMap.get(host); + // add latency value to cumulation and enqueue + m_offsetCumulationMap.put(host, cumulation); // store previous as offset + cumulation += latency; + history.offer(latency); + if (history.size() > AVG_SAMPLE_WINDOW) { + // if queue size reached window size, then + // dequeue and delete oldest value and report average + cumulation -= history.poll(); + } + m_cumulationMap.put(host, cumulation); // store updated cumulation + if (offsetCumulation == 0) return; // most likely no history yet + + double rateOfChange = (cumulation - offsetCumulation) / offsetCumulation; + Queue rateHist = m_rateHistMap.get(host); + double rateCumu = m_rateCumuMap.get(host); + rateCumu += rateOfChange; + rateHist.offer(rateOfChange); + if (rateHist.size() > RATE_SAMPLE_WINDOW) { + rateCumu -= rateHist.poll(); + } + m_rateCumuMap.put(host, rateCumu); + rateOfChange = rateCumu / rateHist.size(); + m_reportingPort.trace (getComponentType (), + id () + ": " + cumulation + ", hist" + Arrays.toString (history.toArray ())); + m_reportingPort.trace (getComponentType (), + id () + ": " + rateCumu + ", hist" + Arrays.toString (rateHist.toArray ())); + + // update connection in model with latency in seconds + for (String valueName : valueNames) { + // massage value name for mapping purposes + valueName = valueName.replace("*", host); + if (m_commands.containsKey (valueName)) { + // ZNewsSys.conn0.latency + IRainbowOperation cmd = getCommand (valueName); + Map parameterMap = new HashMap<> (); + parameterMap.put (cmd.getParameters ()[0], Double.toString (rateOfChange)); + issueCommand (cmd, parameterMap); + } + } + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ServerEnablementGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ServerEnablementGauge.java index 5f76812e7..4f0950aa1 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ServerEnablementGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ServerEnablementGauge.java @@ -1,227 +1,227 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.acmestudio.acme.core.type.IAcmeBooleanValue; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.IAcmeSystem; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.ModelReference; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.ports.IModelsManagerPort; -import org.sa.rainbow.core.ports.RainbowPortFactory; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * This gauge reports on enablement/disablement of servers. If the setup parameter "mode" is "enabled", then the - * commands issued will be enabling/disabling servers by property. If the "mode" is "new" then the commands issues will - * delete/add new servers to the model. - *

- * Note that this gauge needs access to the mode, through the model port. For now, it should be run on the same machine - * as the rainbow master. - * - * @author Bradley Schmerl: schmerl - */ -public class ServerEnablementGauge extends RegularPatternGauge { - - /** Uses existing back up servers as new servers, and just enables them in the model **/ - private static final String ENABLE_MODE = "enable"; - /** Finds disconnected servers in the model and connects them to the right load balancer and db **/ - private static final String CONNECT_MODE = "connect"; - /** adding a server means a new server was created, so issue the create server command **/ - private static final String CREATE_MODE = "create"; - - private static final String MODE_PARAM = "mode"; - private static final String OFF = "f"; - private static final String ON = "o"; - private static final String INIT_ON = "i"; - public static final String NAME = "G - Server Enablement"; - public static final String DEFAULT = "DEFAULT"; - public static final Pattern PATTERN = Pattern - .compile ("(([o,f,i]) ((?:\\d{1,3}\\.){3}\\d{1,3}:\\d{1,4}))" -/*"(([o,f]) ((?:\\d{1,3}\\.){3}\\d{1,3}:\\d{1,4}))(?:\\s(([o,f]) ((?:\\d{1,3}\\.){3}\\d{1,3}:\\d{1,4})))*"*/); - - private IModelsManagerPort m_modelsPort; - private AcmeModelInstance m_model; - - public ServerEnablementGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - addPattern (DEFAULT, PATTERN); - m_modelsPort = RainbowPortFactory.createModelsManagerRequirerPort (); - } - - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - Set enabled = new HashSet<> (); - Set disabled = new HashSet<> (); - int groupCount = m.groupCount (); - int c = groupCount / 3; -// String group = m.group (0); -// group = m.group (1); -// group = m.group (2); -// group = m.group (3); - for (int i = 1; i < c + 1; i++) { - String enablement = m.group (i * 3 - 1); - String ip = m.group (i * 3); - if (ON.equals (enablement) || INIT_ON.equals (enablement)) { - enabled.add (ip); - } else if (OFF.equals (enablement)) { - disabled.add (ip); - } - } - - switch ((String )m_configParams.get (MODE_PARAM).getValue ()) { - case ENABLE_MODE: - enableOrDisableServers (enabled, disabled); - break; - case CONNECT_MODE: - connectOrRemoveServers (enabled, disabled); - break; - case CREATE_MODE: - createOrRemoveServers (enabled, disabled); - break; - - } - } - } - - private void createOrRemoveServers (Set enabled, Set disabled) { - IRainbowOperation addOp = getCommand ("newServer"); - IRainbowOperation delOp = getCommand ("removeServer"); - IRainbowOperation connOp = getCommand ("connectServer"); - List ops = new ArrayList<> (enabled.size () + disabled.size ()); - List> params = new ArrayList<> (ops.size ()); - for (String ip : enabled) { - String [] location = ip.split (":"); - final IAcmeComponent server = getServerCompForIP (location[0]); - if (server != null) { - if (((IAcmeBooleanValue )server.getProperty ("isArchEnabled").getValue ()).getValue ()) - continue; - ops.add (connOp); - Map p = new HashMap<> (); - p.put (connOp.getParameters ()[0], server.getQualifiedName ()); - p.put (connOp.getParameters ()[1], location[0]); - p.put (connOp.getParameters ()[2], location[1]); - params.add (p); - } - else { - ops.add (addOp); - Map p = new HashMap<> (); - p.put (addOp.getParameters ()[0], "Server"); - p.put (addOp.getParameters ()[1], location[0]); - p.put (addOp.getParameters ()[2], location[1]); - params.add (p); - } - } - for (String ip : disabled) { - ops.add (delOp); - Map p = new HashMap<> (); - p.put (delOp.getTarget (), getServerForIP (ip)); - params.add (p); - } - if (ops.size () > 0) - issueCommands(ops, params); - } - - private void connectOrRemoveServers (Set enabled, Set disabled) { - IRainbowOperation addOp = getCommand ("connectServer"); - IRainbowOperation delOp = getCommand ("removeServer"); - List ops = new ArrayList<> (enabled.size () + disabled.size ()); - List> params = new ArrayList<> (ops.size ()); - for (String ip : enabled) { - String[] location = ip.split (":"); - - ops.add (addOp); - Map p = new HashMap<> (); -// p.put (addOp.getParameter, getServerForIP (ip)); - p.put (addOp.getParameters ()[1], location[0]); - p.put (addOp.getParameters ()[2], location[1]); - params.add (p); - } - for (String ip : disabled) { - ops.add (delOp); - Map p = new HashMap<> (); - p.put (delOp.getTarget (), getServerForIP (ip)); - params.add (p); - } - log ("-----> Server Enablement Gauge reporting commands"); - issueCommands (ops, params); - } - - private void enableOrDisableServers (Set enabled, Set disabled) { - IRainbowOperation op = getCommand ("enableServer"); - List ops = new ArrayList<> (enabled.size () + disabled.size ()); - List> params = new ArrayList<> (ops.size ()); - for (String ip : enabled) { - ops.add (op); - Map p = new HashMap<> (); - p.put (op.getParameters ()[0], getServerForIP (ip)); - p.put (op.getParameters ()[1], "true"); - p.put (op.getTarget (), "LB0"); - params.add (p); - } - for (String ip : disabled) { - ops.add (op); - Map p = new HashMap<> (); - p.put (op.getParameters ()[0], getServerForIP (ip)); - p.put (op.getParameters ()[1], "false"); - p.put (op.getTarget (), "LB0"); - params.add (p); - } - issueCommands (ops, params); - } - - - - private AcmeModelInstance getModel () { - if (m_model == null) { - m_model = (AcmeModelInstance) m_modelsPort.getModelInstance (new ModelReference (m_modelDesc - .getName (), m_modelDesc.getType ())); - } - return m_model; - } - - private String getServerForIP (String ip) { - IAcmeComponent server = getModel ().getElementForLocation (ip, "ServerT"); - if (server != null) return server.getQualifiedName (); - return null; - } - - private IAcmeComponent getServerCompForIP (String ip) { - IAcmeComponent server = getModel ().getElementForLocation (ip, "ServerT"); - return server; - } - - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.acmestudio.acme.core.type.IAcmeBooleanValue; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.IAcmeSystem; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.ModelReference; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.ports.IModelsManagerPort; +import org.sa.rainbow.core.ports.RainbowPortFactory; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * This gauge reports on enablement/disablement of servers. If the setup parameter "mode" is "enabled", then the + * commands issued will be enabling/disabling servers by property. If the "mode" is "new" then the commands issues will + * delete/add new servers to the model. + *

+ * Note that this gauge needs access to the mode, through the model port. For now, it should be run on the same machine + * as the rainbow master. + * + * @author Bradley Schmerl: schmerl + */ +public class ServerEnablementGauge extends RegularPatternGauge { + + /** Uses existing back up servers as new servers, and just enables them in the model **/ + private static final String ENABLE_MODE = "enable"; + /** Finds disconnected servers in the model and connects them to the right load balancer and db **/ + private static final String CONNECT_MODE = "connect"; + /** adding a server means a new server was created, so issue the create server command **/ + private static final String CREATE_MODE = "create"; + + private static final String MODE_PARAM = "mode"; + private static final String OFF = "f"; + private static final String ON = "o"; + private static final String INIT_ON = "i"; + public static final String NAME = "G - Server Enablement"; + public static final String DEFAULT = "DEFAULT"; + public static final Pattern PATTERN = Pattern + .compile ("(([o,f,i]) ((?:\\d{1,3}\\.){3}\\d{1,3}:\\d{1,4}))" +/*"(([o,f]) ((?:\\d{1,3}\\.){3}\\d{1,3}:\\d{1,4}))(?:\\s(([o,f]) ((?:\\d{1,3}\\.){3}\\d{1,3}:\\d{1,4})))*"*/); + + private IModelsManagerPort m_modelsPort; + private AcmeModelInstance m_model; + + public ServerEnablementGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + addPattern (DEFAULT, PATTERN); + m_modelsPort = RainbowPortFactory.createModelsManagerRequirerPort (); + } + + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + Set enabled = new HashSet<> (); + Set disabled = new HashSet<> (); + int groupCount = m.groupCount (); + int c = groupCount / 3; +// String group = m.group (0); +// group = m.group (1); +// group = m.group (2); +// group = m.group (3); + for (int i = 1; i < c + 1; i++) { + String enablement = m.group (i * 3 - 1); + String ip = m.group (i * 3); + if (ON.equals (enablement) || INIT_ON.equals (enablement)) { + enabled.add (ip); + } else if (OFF.equals (enablement)) { + disabled.add (ip); + } + } + + switch ((String )m_configParams.get (MODE_PARAM).getValue ()) { + case ENABLE_MODE: + enableOrDisableServers (enabled, disabled); + break; + case CONNECT_MODE: + connectOrRemoveServers (enabled, disabled); + break; + case CREATE_MODE: + createOrRemoveServers (enabled, disabled); + break; + + } + } + } + + private void createOrRemoveServers (Set enabled, Set disabled) { + IRainbowOperation addOp = getCommand ("newServer"); + IRainbowOperation delOp = getCommand ("removeServer"); + IRainbowOperation connOp = getCommand ("connectServer"); + List ops = new ArrayList<> (enabled.size () + disabled.size ()); + List> params = new ArrayList<> (ops.size ()); + for (String ip : enabled) { + String [] location = ip.split (":"); + final IAcmeComponent server = getServerCompForIP (location[0]); + if (server != null) { + if (((IAcmeBooleanValue )server.getProperty ("isArchEnabled").getValue ()).getValue ()) + continue; + ops.add (connOp); + Map p = new HashMap<> (); + p.put (connOp.getParameters ()[0], server.getQualifiedName ()); + p.put (connOp.getParameters ()[1], location[0]); + p.put (connOp.getParameters ()[2], location[1]); + params.add (p); + } + else { + ops.add (addOp); + Map p = new HashMap<> (); + p.put (addOp.getParameters ()[0], "Server"); + p.put (addOp.getParameters ()[1], location[0]); + p.put (addOp.getParameters ()[2], location[1]); + params.add (p); + } + } + for (String ip : disabled) { + ops.add (delOp); + Map p = new HashMap<> (); + p.put (delOp.getTarget (), getServerForIP (ip)); + params.add (p); + } + if (ops.size () > 0) + issueCommands(ops, params); + } + + private void connectOrRemoveServers (Set enabled, Set disabled) { + IRainbowOperation addOp = getCommand ("connectServer"); + IRainbowOperation delOp = getCommand ("removeServer"); + List ops = new ArrayList<> (enabled.size () + disabled.size ()); + List> params = new ArrayList<> (ops.size ()); + for (String ip : enabled) { + String[] location = ip.split (":"); + + ops.add (addOp); + Map p = new HashMap<> (); +// p.put (addOp.getParameter, getServerForIP (ip)); + p.put (addOp.getParameters ()[1], location[0]); + p.put (addOp.getParameters ()[2], location[1]); + params.add (p); + } + for (String ip : disabled) { + ops.add (delOp); + Map p = new HashMap<> (); + p.put (delOp.getTarget (), getServerForIP (ip)); + params.add (p); + } + log ("-----> Server Enablement Gauge reporting commands"); + issueCommands (ops, params); + } + + private void enableOrDisableServers (Set enabled, Set disabled) { + IRainbowOperation op = getCommand ("enableServer"); + List ops = new ArrayList<> (enabled.size () + disabled.size ()); + List> params = new ArrayList<> (ops.size ()); + for (String ip : enabled) { + ops.add (op); + Map p = new HashMap<> (); + p.put (op.getParameters ()[0], getServerForIP (ip)); + p.put (op.getParameters ()[1], "true"); + p.put (op.getTarget (), "LB0"); + params.add (p); + } + for (String ip : disabled) { + ops.add (op); + Map p = new HashMap<> (); + p.put (op.getParameters ()[0], getServerForIP (ip)); + p.put (op.getParameters ()[1], "false"); + p.put (op.getTarget (), "LB0"); + params.add (p); + } + issueCommands (ops, params); + } + + + + private AcmeModelInstance getModel () { + if (m_model == null) { + m_model = (AcmeModelInstance) m_modelsPort.getModelInstance (new ModelReference (m_modelDesc + .getName (), m_modelDesc.getType ())); + } + return m_model; + } + + private String getServerForIP (String ip) { + IAcmeComponent server = getModel ().getElementForLocation (ip, "ServerT"); + if (server != null) return server.getQualifiedName (); + return null; + } + + private IAcmeComponent getServerCompForIP (String ip) { + IAcmeComponent server = getModel ().getElementForLocation (ip, "ServerT"); + return server; + } + + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ThrottleGauge.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ThrottleGauge.java index abb7231fa..7771e1737 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ThrottleGauge.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/gauges/ThrottleGauge.java @@ -1,106 +1,106 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.gauges; - -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.gauges.RegularPatternGauge; -import org.sa.rainbow.core.models.commands.IRainbowOperation; -import org.sa.rainbow.core.util.TypedAttribute; -import org.sa.rainbow.core.util.TypedAttributeWithValue; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ThrottleGauge extends RegularPatternGauge { - - public static final String NAME = "G - Throttled Clients"; - public static final String NONE = "NOTHROTTLE"; - - public String lastReport = ""; - - private static final String[] commandNames = { "setThrottled" }; - private static final String DEFAULT = "DEFAULT"; - - public ThrottleGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, - List setupParams, Map mappings) - throws RainbowException { - super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); - - addPattern (DEFAULT, Pattern.compile ("((?:\\d{1,3}\\.){3}\\d{1,3})(?:,\\s*((?:\\d{1,3}\\.){3}\\d{1,3}))*")); - addPattern (NONE, Pattern.compile ("^none$")); - } - - @Override - protected void doMatch (String matchName, Matcher m) { - if (matchName == DEFAULT) { - - // Send the list of attackers - int c = m.groupCount (); - StringBuilder ips = new StringBuilder (); -// String[] ips = new String[c]; - for (int i = 0; i < c; i++) { -// ips[i] = m.group(i + 1); - ips.append (m.group (i + 1)); - ips.append (","); - } - ips.deleteCharAt (ips.length () - 1); - - if (doReport (ips.toString ())) { - recordLastReport (ips.toString ()); - IRainbowOperation cmd = m_commands.values ().iterator ().next (); - Map pm = new HashMap<> (); - pm.put (cmd.getParameters ()[0], ips.toString ()); - issueCommand (cmd, pm); - - } - } - else if (matchName == NONE) { - // The probe reported "none" meaning that there is nothing blackholed - if (doReport ("")) { - recordLastReport (""); - IRainbowOperation cmd = m_commands.values ().iterator ().next (); - Map pm = new HashMap<> (); - pm.put (cmd.getParameters ()[0], ""); - issueCommand (cmd, pm); - } - } - } - - private void recordLastReport (String report) { - lastReport = report; - } - - private boolean doReport (String report) { - boolean doReport; - synchronized (lastReport) { - doReport = !lastReport.equals (report); - } -// return doReport; - return true; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.gauges; + +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.gauges.RegularPatternGauge; +import org.sa.rainbow.core.models.commands.IRainbowOperation; +import org.sa.rainbow.core.util.TypedAttribute; +import org.sa.rainbow.core.util.TypedAttributeWithValue; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ThrottleGauge extends RegularPatternGauge { + + public static final String NAME = "G - Throttled Clients"; + public static final String NONE = "NOTHROTTLE"; + + public String lastReport = ""; + + private static final String[] commandNames = { "setThrottled" }; + private static final String DEFAULT = "DEFAULT"; + + public ThrottleGauge (String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, + List setupParams, Map mappings) + throws RainbowException { + super (NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + + addPattern (DEFAULT, Pattern.compile ("((?:\\d{1,3}\\.){3}\\d{1,3})(?:,\\s*((?:\\d{1,3}\\.){3}\\d{1,3}))*")); + addPattern (NONE, Pattern.compile ("^none$")); + } + + @Override + protected void doMatch (String matchName, Matcher m) { + if (matchName == DEFAULT) { + + // Send the list of attackers + int c = m.groupCount (); + StringBuilder ips = new StringBuilder (); +// String[] ips = new String[c]; + for (int i = 0; i < c; i++) { +// ips[i] = m.group(i + 1); + ips.append (m.group (i + 1)); + ips.append (","); + } + ips.deleteCharAt (ips.length () - 1); + + if (doReport (ips.toString ())) { + recordLastReport (ips.toString ()); + IRainbowOperation cmd = m_commands.values ().iterator ().next (); + Map pm = new HashMap<> (); + pm.put (cmd.getParameters ()[0], ips.toString ()); + issueCommand (cmd, pm); + + } + } + else if (matchName == NONE) { + // The probe reported "none" meaning that there is nothing blackholed + if (doReport ("")) { + recordLastReport (""); + IRainbowOperation cmd = m_commands.values ().iterator ().next (); + Map pm = new HashMap<> (); + pm.put (cmd.getParameters ()[0], ""); + issueCommand (cmd, pm); + } + } + } + + private void recordLastReport (String report) { + lastReport = report; + } + + private boolean doReport (String report) { + boolean doReport; + synchronized (lastReport) { + doReport = !lastReport.equals (report); + } +// return doReport; + return true; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/AuthenticationProbe.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/AuthenticationProbe.java index 8f29c8ca9..65fee1c0e 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/AuthenticationProbe.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/AuthenticationProbe.java @@ -1,110 +1,110 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.probes; - -import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; -import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; -import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; -import static java.nio.file.StandardWatchEventKinds.OVERFLOW; - -import java.io.File; -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Path; -import java.nio.file.WatchEvent; -import java.nio.file.WatchKey; -import java.nio.file.WatchService; - -import org.sa.rainbow.translator.probes.AbstractRunnableProbe; - -public class AuthenticationProbe extends AbstractRunnableProbe { - - private static final String PROBE_TYPE = "authenticationprobe"; - private String m_authenticationFile; - - public AuthenticationProbe (String id, long sleepTime) { - super (id, PROBE_TYPE, Kind.JAVA, sleepTime); - } - - public AuthenticationProbe (String id, long sleepTime, String[] args) { - this (id, sleepTime); - if (args.length == 1) { - m_authenticationFile = args [0]; - } - } - - @Override - public void run () { - Path filePath = new File (m_authenticationFile).toPath (); - Path dir = filePath.getParent (); - if (!dir.toFile ().exists ()) { - LOGGER.error ("The directory to watch for the authentication file '" + m_authenticationFile + "' does not exist!"); - tallyError (); - } - WatchService watcher = null; - WatchKey key = null; - try { - watcher = FileSystems.getDefault ().newWatchService (); - - key = dir.register (watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); - Thread currentThread = Thread.currentThread (); - - while (thread () == currentThread && isActive ()) { - try { - Thread.sleep (sleepTime ()); - } - catch (InterruptedException e) { - } - key = watcher.poll (); - if (key != null) { - for (WatchEvent event : key.pollEvents ()) { - WatchEvent.Kind kind = event.kind (); - if (kind == OVERFLOW) { - continue; - } - WatchEvent ev = (WatchEvent )event; - Path filename = ev.context (); - if (filename.equals (filePath)) { - if (kind == ENTRY_DELETE) { - reportData ("off"); - - } - else { - reportData ("on"); - - } - } - } - } - } - } - catch (IOException e1) { - LOGGER.error ("Could not create a watcher for the authentication file '" + m_authenticationFile + "'.", e1); - tallyError (); - } - - - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.probes; + +import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; +import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; +import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; +import static java.nio.file.StandardWatchEventKinds.OVERFLOW; + +import java.io.File; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; + +import org.sa.rainbow.translator.probes.AbstractRunnableProbe; + +public class AuthenticationProbe extends AbstractRunnableProbe { + + private static final String PROBE_TYPE = "authenticationprobe"; + private String m_authenticationFile; + + public AuthenticationProbe (String id, long sleepTime) { + super (id, PROBE_TYPE, Kind.JAVA, sleepTime); + } + + public AuthenticationProbe (String id, long sleepTime, String[] args) { + this (id, sleepTime); + if (args.length == 1) { + m_authenticationFile = args [0]; + } + } + + @Override + public void run () { + Path filePath = new File (m_authenticationFile).toPath (); + Path dir = filePath.getParent (); + if (!dir.toFile ().exists ()) { + LOGGER.error ("The directory to watch for the authentication file '" + m_authenticationFile + "' does not exist!"); + tallyError (); + } + WatchService watcher = null; + WatchKey key = null; + try { + watcher = FileSystems.getDefault ().newWatchService (); + + key = dir.register (watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); + Thread currentThread = Thread.currentThread (); + + while (thread () == currentThread && isActive ()) { + try { + Thread.sleep (sleepTime ()); + } + catch (InterruptedException e) { + } + key = watcher.poll (); + if (key != null) { + for (WatchEvent event : key.pollEvents ()) { + WatchEvent.Kind kind = event.kind (); + if (kind == OVERFLOW) { + continue; + } + WatchEvent ev = (WatchEvent )event; + Path filename = ev.context (); + if (filename.equals (filePath)) { + if (kind == ENTRY_DELETE) { + reportData ("off"); + + } + else { + reportData ("on"); + + } + } + } + } + } + } + catch (IOException e1) { + LOGGER.error ("Could not create a watcher for the authentication file '" + m_authenticationFile + "'.", e1); + tallyError (); + } + + + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/CaptchaProbe.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/CaptchaProbe.java index a308f404e..8465c04d4 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/CaptchaProbe.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/CaptchaProbe.java @@ -1,69 +1,69 @@ -/* - * The MIT License - * - * Copyright 2014 CMUimport java.io.File; - -import org.sa.rainbow.translator.probes.AbstractRunnableProbe; -import org.sa.rainbow.util.Util; - associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.probes; - -import java.io.File; - -import org.sa.rainbow.translator.probes.AbstractRunnableProbe; -import org.sa.rainbow.util.Util; - -public class CaptchaProbe extends AbstractRunnableProbe { - - private static final String PROBE_TYPE = "captchaprobe"; - private String m_captchaFile; - - public CaptchaProbe (String id, long sleepTime) { - super (id, PROBE_TYPE, Kind.JAVA, sleepTime); - } - - public CaptchaProbe (String id, long sleepTime, String[] args) { - this (id, sleepTime); - if (args.length == 1) { - m_captchaFile = args[0]; - } - } - - @Override - public void run () { - Thread currentThread = Thread.currentThread (); - if (m_captchaFile == null) { - LOGGER.error ("No captcha file specified"); - tallyError (); - } - while (thread () == currentThread && isActive ()) { - try { - Thread.sleep (sleepTime ()); - } - catch (InterruptedException e) { - } - File f = new File (m_captchaFile); - boolean captchaOn = f.exists (); - String rpt = captchaOn ? "on" : "off"; - reportData (rpt); - Util.dataLogger ().info (rpt); - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMUimport java.io.File; + +import org.sa.rainbow.translator.probes.AbstractRunnableProbe; +import org.sa.rainbow.util.Util; + associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.probes; + +import java.io.File; + +import org.sa.rainbow.translator.probes.AbstractRunnableProbe; +import org.sa.rainbow.util.Util; + +public class CaptchaProbe extends AbstractRunnableProbe { + + private static final String PROBE_TYPE = "captchaprobe"; + private String m_captchaFile; + + public CaptchaProbe (String id, long sleepTime) { + super (id, PROBE_TYPE, Kind.JAVA, sleepTime); + } + + public CaptchaProbe (String id, long sleepTime, String[] args) { + this (id, sleepTime); + if (args.length == 1) { + m_captchaFile = args[0]; + } + } + + @Override + public void run () { + Thread currentThread = Thread.currentThread (); + if (m_captchaFile == null) { + LOGGER.error ("No captcha file specified"); + tallyError (); + } + while (thread () == currentThread && isActive ()) { + try { + Thread.sleep (sleepTime ()); + } + catch (InterruptedException e) { + } + File f = new File (m_captchaFile); + boolean captchaOn = f.exists (); + String rpt = captchaOn ? "on" : "off"; + reportData (rpt); + Util.dataLogger ().info (rpt); + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ClientProxyProbe.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ClientProxyProbe.java index 2e5c10ea6..c16e2e3a2 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ClientProxyProbe.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ClientProxyProbe.java @@ -1,151 +1,151 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.probes; - -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; - -import org.apache.log4j.Logger; -import org.sa.rainbow.core.IRainbowRunnable; -import org.sa.rainbow.translator.probes.AbstractRunnableProbe; -import org.sa.rainbow.util.Beacon; -import org.sa.rainbow.util.Util; - -/** - * A probe that acts like an end-user client connecting to the newssite, to help determine client's experienced response - * time. - * - * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) - */ -public class ClientProxyProbe extends AbstractRunnableProbe { - - public static final String PROBE_TYPE = "clientproxy"; - - private String[] m_tgtUrls = {}; - - /** - * Default Constructor, setting ID and sleep time - * - * @param id - * the unique name@location identifier of the IProbe - * @param sleepTime - * milliseconds to sleep per cycle - */ - public ClientProxyProbe (String id, long sleepTime) { - super (id, PROBE_TYPE, Kind.JAVA, sleepTime); - LOGGER = Logger.getLogger (getClass ()); - - } - - /** - * Constructor to supply with array of target URLs. - * - * @param id - * the unique name@location identifier of the IProbe - * @param sleepTime - * milliseconds to sleep per cycle - * @param args - * String array of target URLs against which to check time - */ - public ClientProxyProbe (String id, long sleepTime, String[] args) { - this (id, sleepTime); - m_tgtUrls = args; - } - - @Override - public void run () { - byte[] bytes = new byte[Util.MAX_BYTES]; - - /* Repeatedly execute until probe is deactivated (which means it may - * still be reactivated later) or destroyed by unsetting the thread. - */ - Beacon timer = new Beacon (IRainbowRunnable.LONG_SLEEP_TIME); // use this to determine to report - Thread currentThread = Thread.currentThread (); - while (thread () == currentThread && isActive ()) { - for (String urlStr : m_tgtUrls) { - timer.mark (); - try { - URL url = new URL (urlStr); - HttpURLConnection httpConn = (HttpURLConnection )url.openConnection (); - ByteArrayOutputStream baos = new ByteArrayOutputStream (); - int cnter = 0; - long startTime = System.currentTimeMillis (); - int length = httpConn.getContentLength (); - BufferedInputStream in = new BufferedInputStream (httpConn.getInputStream ()); - while (in.available () > 0 || cnter < length) { - int cnt = in.read (bytes); - baos.write (bytes, 0, cnt); - cnter += cnt; - if (cnter < length) { - if (timer.periodElapsed ()) { // make an intermediate report - String rpt = "[" + Util.probeLogTimestamp () + "] " + url.getHost () + ":" - + (System.currentTimeMillis () - startTime) + "ms"; - reportData (rpt); - Util.dataLogger ().info (rpt); - timer.mark (); // reset timer - } - try { // sleep just a little as to not saturate CPU - Thread.sleep (IRainbowRunnable.SHORT_SLEEP_TIME); - } - catch (InterruptedException e) { - // intentional ignore - } - } - } - long endTime = System.currentTimeMillis (); - String rpt = "[" + Util.probeLogTimestamp () + "]<" + id () + "> " + url.getHost () + ":" - + (endTime - startTime) + "ms"; - reportData (rpt); - Util.dataLogger ().info (rpt); - if (LOGGER.isTraceEnabled ()) { - LOGGER.trace ("Content-type: " + httpConn.getContentType ()); - LOGGER.trace ("Content-length: " + httpConn.getContentLength ()); - LOGGER.trace (baos.toString ()); - LOGGER.trace ("ClientProxyProbe " + id () + " queues \"" + rpt + "\""); - } - httpConn.disconnect (); - } - catch (MalformedURLException e) { - LOGGER.error ("Bad URL provided in Probe Spec?", e); - tallyError (); - } - catch (IOException e) { - LOGGER.error ("HTTP connection error!", e); - tallyError (); - } - } - try { - Thread.sleep (sleepTime ()); - } - catch (InterruptedException e) { - // intentional ignore - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.probes; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + +import org.apache.log4j.Logger; +import org.sa.rainbow.core.IRainbowRunnable; +import org.sa.rainbow.translator.probes.AbstractRunnableProbe; +import org.sa.rainbow.util.Beacon; +import org.sa.rainbow.util.Util; + +/** + * A probe that acts like an end-user client connecting to the newssite, to help determine client's experienced response + * time. + * + * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) + */ +public class ClientProxyProbe extends AbstractRunnableProbe { + + public static final String PROBE_TYPE = "clientproxy"; + + private String[] m_tgtUrls = {}; + + /** + * Default Constructor, setting ID and sleep time + * + * @param id + * the unique name@location identifier of the IProbe + * @param sleepTime + * milliseconds to sleep per cycle + */ + public ClientProxyProbe (String id, long sleepTime) { + super (id, PROBE_TYPE, Kind.JAVA, sleepTime); + LOGGER = Logger.getLogger (getClass ()); + + } + + /** + * Constructor to supply with array of target URLs. + * + * @param id + * the unique name@location identifier of the IProbe + * @param sleepTime + * milliseconds to sleep per cycle + * @param args + * String array of target URLs against which to check time + */ + public ClientProxyProbe (String id, long sleepTime, String[] args) { + this (id, sleepTime); + m_tgtUrls = args; + } + + @Override + public void run () { + byte[] bytes = new byte[Util.MAX_BYTES]; + + /* Repeatedly execute until probe is deactivated (which means it may + * still be reactivated later) or destroyed by unsetting the thread. + */ + Beacon timer = new Beacon (IRainbowRunnable.LONG_SLEEP_TIME); // use this to determine to report + Thread currentThread = Thread.currentThread (); + while (thread () == currentThread && isActive ()) { + for (String urlStr : m_tgtUrls) { + timer.mark (); + try { + URL url = new URL (urlStr); + HttpURLConnection httpConn = (HttpURLConnection )url.openConnection (); + ByteArrayOutputStream baos = new ByteArrayOutputStream (); + int cnter = 0; + long startTime = System.currentTimeMillis (); + int length = httpConn.getContentLength (); + BufferedInputStream in = new BufferedInputStream (httpConn.getInputStream ()); + while (in.available () > 0 || cnter < length) { + int cnt = in.read (bytes); + baos.write (bytes, 0, cnt); + cnter += cnt; + if (cnter < length) { + if (timer.periodElapsed ()) { // make an intermediate report + String rpt = "[" + Util.probeLogTimestamp () + "] " + url.getHost () + ":" + + (System.currentTimeMillis () - startTime) + "ms"; + reportData (rpt); + Util.dataLogger ().info (rpt); + timer.mark (); // reset timer + } + try { // sleep just a little as to not saturate CPU + Thread.sleep (IRainbowRunnable.SHORT_SLEEP_TIME); + } + catch (InterruptedException e) { + // intentional ignore + } + } + } + long endTime = System.currentTimeMillis (); + String rpt = "[" + Util.probeLogTimestamp () + "]<" + id () + "> " + url.getHost () + ":" + + (endTime - startTime) + "ms"; + reportData (rpt); + Util.dataLogger ().info (rpt); + if (LOGGER.isTraceEnabled ()) { + LOGGER.trace ("Content-type: " + httpConn.getContentType ()); + LOGGER.trace ("Content-length: " + httpConn.getContentLength ()); + LOGGER.trace (baos.toString ()); + LOGGER.trace ("ClientProxyProbe " + id () + " queues \"" + rpt + "\""); + } + httpConn.disconnect (); + } + catch (MalformedURLException e) { + LOGGER.error ("Bad URL provided in Probe Spec?", e); + tallyError (); + } + catch (IOException e) { + LOGGER.error ("HTTP connection error!", e); + tallyError (); + } + } + try { + Thread.sleep (sleepTime ()); + } + catch (InterruptedException e) { + // intentional ignore + } + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/DummyProbe.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/DummyProbe.java index 866df1c97..ab535b471 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/DummyProbe.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/DummyProbe.java @@ -1,88 +1,88 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.probes; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; - -import org.sa.rainbow.translator.probes.AbstractRunnableProbe; -import org.sa.rainbow.util.Util; - -/** - * This probe takes a file as an argument and every cycle reads the file, announcing each line on the probe bus - * - * @author schmerl - * - */ -public class DummyProbe extends AbstractRunnableProbe { - - private static final String PROBE_TYPE = "dummymaliciousness"; - private String m_probeFile; - - public DummyProbe (String id, long sleepTime) { - super (id, PROBE_TYPE, Kind.JAVA, sleepTime); - } - - public DummyProbe (String id, long sleepTime, String[] args) { - this (id, sleepTime); - if (args.length == 1) { - m_probeFile = args[0]; - } - } - - @Override - public void run () { - Thread currentThread = Thread.currentThread (); - if (m_probeFile == null) { - LOGGER.error ("No probe file specified"); - tallyError (); - } - while (thread () == currentThread && isActive ()) { - try { - Thread.sleep (sleepTime ()); - } - catch (InterruptedException e) { - } - File f = new File (m_probeFile); - if (!f.exists ()) { - continue; - } - BufferedReader reader = null; - try { - reader = Files.newBufferedReader (f.toPath (), Charset.forName ("US-ASCII")); - String line = null; - while ((line = reader.readLine ()) != null) { - reportData (line); - Util.dataLogger ().info (line); - } - } - catch (IOException e) { - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.probes; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; + +import org.sa.rainbow.translator.probes.AbstractRunnableProbe; +import org.sa.rainbow.util.Util; + +/** + * This probe takes a file as an argument and every cycle reads the file, announcing each line on the probe bus + * + * @author schmerl + * + */ +public class DummyProbe extends AbstractRunnableProbe { + + private static final String PROBE_TYPE = "dummymaliciousness"; + private String m_probeFile; + + public DummyProbe (String id, long sleepTime) { + super (id, PROBE_TYPE, Kind.JAVA, sleepTime); + } + + public DummyProbe (String id, long sleepTime, String[] args) { + this (id, sleepTime); + if (args.length == 1) { + m_probeFile = args[0]; + } + } + + @Override + public void run () { + Thread currentThread = Thread.currentThread (); + if (m_probeFile == null) { + LOGGER.error ("No probe file specified"); + tallyError (); + } + while (thread () == currentThread && isActive ()) { + try { + Thread.sleep (sleepTime ()); + } + catch (InterruptedException e) { + } + File f = new File (m_probeFile); + if (!f.exists ()) { + continue; + } + BufferedReader reader = null; + try { + reader = Files.newBufferedReader (f.toPath (), Charset.forName ("US-ASCII")); + String line = null; + while ((line = reader.readLine ()) != null) { + reportData (line); + Util.dataLogger ().info (line); + } + } + catch (IOException e) { + } + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/FidelityProbe.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/FidelityProbe.java index 2d84a8821..16d11a8fa 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/FidelityProbe.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/FidelityProbe.java @@ -1,83 +1,83 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.probes; - -import org.sa.rainbow.translator.probes.AbstractRunnableProbe; -import org.sa.rainbow.util.Util; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; - -public class FidelityProbe extends AbstractRunnableProbe { - - public static final String PROBE_TYPE = "fidelity"; - - private String m_fidelityFile = null; - - public FidelityProbe (String id, long sleepTime) { - super (id, PROBE_TYPE, Kind.JAVA, sleepTime); - - } - - public FidelityProbe (String id, long sleepTime, String[] args) { - this (id, sleepTime); - if (args.length == 1) { - m_fidelityFile = args[0]; - } - } - - @Override - public void run () { - String line = null; - - Thread currentThread = Thread.currentThread (); - if (m_fidelityFile == null) { - LOGGER.error ("No fidelity file specified"); - tallyError (); - } - while (thread () == currentThread && isActive ()) { - try { - Thread.sleep (sleepTime ()); - } - catch (InterruptedException e) { - } - - StringBuilder rpt = new StringBuilder (); - String fidelity = "high"; - try (BufferedReader in = new BufferedReader (new InputStreamReader (new FileInputStream (m_fidelityFile)))) { - line = in.readLine (); - if (line != null) { - fidelity = line.trim (); - } - } - catch (IOException e) { - } - reportData (fidelity); - Util.dataLogger ().info (fidelity); - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.probes; + +import org.sa.rainbow.translator.probes.AbstractRunnableProbe; +import org.sa.rainbow.util.Util; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; + +public class FidelityProbe extends AbstractRunnableProbe { + + public static final String PROBE_TYPE = "fidelity"; + + private String m_fidelityFile = null; + + public FidelityProbe (String id, long sleepTime) { + super (id, PROBE_TYPE, Kind.JAVA, sleepTime); + + } + + public FidelityProbe (String id, long sleepTime, String[] args) { + this (id, sleepTime); + if (args.length == 1) { + m_fidelityFile = args[0]; + } + } + + @Override + public void run () { + String line = null; + + Thread currentThread = Thread.currentThread (); + if (m_fidelityFile == null) { + LOGGER.error ("No fidelity file specified"); + tallyError (); + } + while (thread () == currentThread && isActive ()) { + try { + Thread.sleep (sleepTime ()); + } + catch (InterruptedException e) { + } + + StringBuilder rpt = new StringBuilder (); + String fidelity = "high"; + try (BufferedReader in = new BufferedReader (new InputStreamReader (new FileInputStream (m_fidelityFile)))) { + line = in.readLine (); + if (line != null) { + fidelity = line.trim (); + } + } + catch (IOException e) { + } + reportData (fidelity); + Util.dataLogger ().info (fidelity); + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/PingRTTProbe.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/PingRTTProbe.java index 9658d7305..09a0855f9 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/PingRTTProbe.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/PingRTTProbe.java @@ -1,172 +1,172 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.probes; - -import org.apache.log4j.Logger; -import org.sa.rainbow.core.Rainbow; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.RainbowConstants; -import org.sa.rainbow.core.util.RainbowLogger; -import org.sa.rainbow.translator.probes.AbstractRunnableProbe; -import org.sa.rainbow.util.Util; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.text.MessageFormat; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * A Java Probe that uses the available external "ping" program to compute - * Roundtrip-Time to a target host, using 3 requests and (Linux-only) preloading - * all 3 requests. The default target host is where the Rainbow Master resides. - * The reported values are minimum, average, and maximum rtt in milliseconds. - * Target hosts can be provided in a String array using the 2-parameter contructor. - * - * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) - */ -public class PingRTTProbe extends AbstractRunnableProbe { - - public static final String PROBE_TYPE = "pingrtt"; - public static final int PING_REQ_SIZE = 64; - - /** Invoke Ping on Linux with 56 (64) bytes of data, 3 preloaded requests */ - public static final String[] PING_LINUX = { "ping", "-l", "3", "-c", "3", "-s", String.valueOf(PING_REQ_SIZE-8), "" }; - /** Invoke Ping on Windows with 64 bytes of data, 3 requests */ - public static final String[] PING_WIN32 = { "ping", "-n", "3", "-l", String.valueOf(PING_REQ_SIZE), "" }; - - private String[] m_tgtHosts = {Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MASTER_LOCATION)}; - - /** - * Default Constructor, setting ID and sleep time - * @param id the unique name@location identifier of the IProbe - * @param sleepTime milliseconds to sleep per cycle - */ - public PingRTTProbe (String id, long sleepTime) { - super(id, PROBE_TYPE, Kind.JAVA, sleepTime); - LOGGER = Logger.getLogger (this.getClass ()); - } - - /** - * Constructor to supply with array of target hosts. - * @param id the unique name@location identifier of the IProbe - * @param sleepTime milliseconds to sleep per cycle - * @param args String array of target host against which to check roundtrip latency - */ - public PingRTTProbe (String id, long sleepTime, String[] args) { - this(id, sleepTime); - m_tgtHosts = args; - } - - /* (non-Javadoc) - * @see java.lang.Runnable#run() - */ - @Override - public void run () { - // compose the ping command - boolean isWin = false; - String[] pingCmd = null; - if (System.getProperty ("os.name").contains ("Window")) { - pingCmd = PING_WIN32; - isWin = true; - } else { - pingCmd = PING_LINUX; - } - // build pattern - Pattern pattern = null; - if (isWin) { - pattern = Pattern.compile("Minimum = ([0-9.]+)ms, Maximum = ([0-9.]+)ms, Average = ([0-9.]+)ms", Pattern.CASE_INSENSITIVE); - } else { - pattern = Pattern.compile("rtt min/avg/max/mdev = ([0-9.]+)/([0-9.]+)/([0-9.]+)", Pattern.CASE_INSENSITIVE); - } - String min, max, avg; - - /* Repeatedly execute until probe is deactivated (which means it may - * still be reactivated later) or destroyed by unsetting the thread. - */ - Thread currentThread = Thread.currentThread(); - while (thread() == currentThread && isActive()) { - try { - Thread.sleep(sleepTime()); - } catch (InterruptedException e) { - // intentional ignore - } - for (String target : m_tgtHosts) { - pingCmd[pingCmd.length-1] = target; - // create a process and execute it - ProcessBuilder pb = new ProcessBuilder(pingCmd); - pb.redirectErrorStream(true); - try { - Process p = pb.start(); - try { - p.waitFor(); - } catch (InterruptedException e) { - // intentional ignore - } - if (p.exitValue() > 1) { // NOT GOOD - RainbowLogger.error (RainbowComponentT.PROBE, MessageFormat.format ( - "PING returned a bad error code {0}, aborting! Check Probe Spec?", p.exitValue ()), - getLoggingPort (), LOGGER); - RainbowLogger.info (RainbowComponentT.PROBE, - MessageFormat.format ("- STDOUT+STDERR: ----\n{0}", Util.getProcessOutput (p)), - getLoggingPort (), - LOGGER); - tallyError(); - continue; - } - StringBuilder buf = new StringBuilder (); - byte[] bytes = new byte[Util.MAX_BYTES]; - BufferedInputStream bis = new BufferedInputStream(p.getInputStream()); - while (bis.available() > 0) { - int cnt = bis.read(bytes); - buf.append(new String(bytes, 0, cnt)); - } - Matcher m = pattern.matcher(buf.toString()); - if (m.find()) { // report finding! - if (isWin) { - min = m.group(1); - max = m.group(2); - avg = m.group(3); - } else { - min = m.group(1); - avg = m.group(2); - max = m.group(3); - } - String rpt = "[" + Util.probeLogTimestamp() + "] " + target + ":" + min + "/" + avg + "/" + max; - if (LOGGER.isTraceEnabled ()) { - LOGGER.trace ("PingRTTProbe " + id () + " queues \"" + rpt + "\""); - } - reportData(rpt); - Util.dataLogger().info(rpt); - } - } catch (IOException e) { - RainbowLogger.error (RainbowComponentT.PROBE, "Process execution error!", e, getLoggingPort (), - LOGGER); - tallyError(); - } - } - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.probes; + +import org.apache.log4j.Logger; +import org.sa.rainbow.core.Rainbow; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.RainbowConstants; +import org.sa.rainbow.core.util.RainbowLogger; +import org.sa.rainbow.translator.probes.AbstractRunnableProbe; +import org.sa.rainbow.util.Util; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.text.MessageFormat; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * A Java Probe that uses the available external "ping" program to compute + * Roundtrip-Time to a target host, using 3 requests and (Linux-only) preloading + * all 3 requests. The default target host is where the Rainbow Master resides. + * The reported values are minimum, average, and maximum rtt in milliseconds. + * Target hosts can be provided in a String array using the 2-parameter contructor. + * + * @author Shang-Wen Cheng (zensoul@cs.cmu.edu) + */ +public class PingRTTProbe extends AbstractRunnableProbe { + + public static final String PROBE_TYPE = "pingrtt"; + public static final int PING_REQ_SIZE = 64; + + /** Invoke Ping on Linux with 56 (64) bytes of data, 3 preloaded requests */ + public static final String[] PING_LINUX = { "ping", "-l", "3", "-c", "3", "-s", String.valueOf(PING_REQ_SIZE-8), "" }; + /** Invoke Ping on Windows with 64 bytes of data, 3 requests */ + public static final String[] PING_WIN32 = { "ping", "-n", "3", "-l", String.valueOf(PING_REQ_SIZE), "" }; + + private String[] m_tgtHosts = {Rainbow.instance ().getProperty (RainbowConstants.PROPKEY_MASTER_LOCATION)}; + + /** + * Default Constructor, setting ID and sleep time + * @param id the unique name@location identifier of the IProbe + * @param sleepTime milliseconds to sleep per cycle + */ + public PingRTTProbe (String id, long sleepTime) { + super(id, PROBE_TYPE, Kind.JAVA, sleepTime); + LOGGER = Logger.getLogger (this.getClass ()); + } + + /** + * Constructor to supply with array of target hosts. + * @param id the unique name@location identifier of the IProbe + * @param sleepTime milliseconds to sleep per cycle + * @param args String array of target host against which to check roundtrip latency + */ + public PingRTTProbe (String id, long sleepTime, String[] args) { + this(id, sleepTime); + m_tgtHosts = args; + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run () { + // compose the ping command + boolean isWin = false; + String[] pingCmd = null; + if (System.getProperty ("os.name").contains ("Window")) { + pingCmd = PING_WIN32; + isWin = true; + } else { + pingCmd = PING_LINUX; + } + // build pattern + Pattern pattern = null; + if (isWin) { + pattern = Pattern.compile("Minimum = ([0-9.]+)ms, Maximum = ([0-9.]+)ms, Average = ([0-9.]+)ms", Pattern.CASE_INSENSITIVE); + } else { + pattern = Pattern.compile("rtt min/avg/max/mdev = ([0-9.]+)/([0-9.]+)/([0-9.]+)", Pattern.CASE_INSENSITIVE); + } + String min, max, avg; + + /* Repeatedly execute until probe is deactivated (which means it may + * still be reactivated later) or destroyed by unsetting the thread. + */ + Thread currentThread = Thread.currentThread(); + while (thread() == currentThread && isActive()) { + try { + Thread.sleep(sleepTime()); + } catch (InterruptedException e) { + // intentional ignore + } + for (String target : m_tgtHosts) { + pingCmd[pingCmd.length-1] = target; + // create a process and execute it + ProcessBuilder pb = new ProcessBuilder(pingCmd); + pb.redirectErrorStream(true); + try { + Process p = pb.start(); + try { + p.waitFor(); + } catch (InterruptedException e) { + // intentional ignore + } + if (p.exitValue() > 1) { // NOT GOOD + RainbowLogger.error (RainbowComponentT.PROBE, MessageFormat.format ( + "PING returned a bad error code {0}, aborting! Check Probe Spec?", p.exitValue ()), + getLoggingPort (), LOGGER); + RainbowLogger.info (RainbowComponentT.PROBE, + MessageFormat.format ("- STDOUT+STDERR: ----\n{0}", Util.getProcessOutput (p)), + getLoggingPort (), + LOGGER); + tallyError(); + continue; + } + StringBuilder buf = new StringBuilder (); + byte[] bytes = new byte[Util.MAX_BYTES]; + BufferedInputStream bis = new BufferedInputStream(p.getInputStream()); + while (bis.available() > 0) { + int cnt = bis.read(bytes); + buf.append(new String(bytes, 0, cnt)); + } + Matcher m = pattern.matcher(buf.toString()); + if (m.find()) { // report finding! + if (isWin) { + min = m.group(1); + max = m.group(2); + avg = m.group(3); + } else { + min = m.group(1); + avg = m.group(2); + max = m.group(3); + } + String rpt = "[" + Util.probeLogTimestamp() + "] " + target + ":" + min + "/" + avg + "/" + max; + if (LOGGER.isTraceEnabled ()) { + LOGGER.trace ("PingRTTProbe " + id () + " queues \"" + rpt + "\""); + } + reportData(rpt); + Util.dataLogger().info(rpt); + } + } catch (IOException e) { + RainbowLogger.error (RainbowComponentT.PROBE, "Process execution error!", e, getLoggingPort (), + LOGGER); + tallyError(); + } + } + } + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ServerEnablementProbe.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ServerEnablementProbe.java index 2b38bac67..9f52ff622 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ServerEnablementProbe.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ServerEnablementProbe.java @@ -1,168 +1,168 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.probes; - -import org.sa.rainbow.translator.probes.AbstractRunnableProbe; -import org.sa.rainbow.util.Util; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.*; -import java.text.MessageFormat; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -public class ServerEnablementProbe extends AbstractRunnableProbe { - private static final String PROBE_TYPE = "enablementprobe"; - private String m_configurationFile; - - public ServerEnablementProbe (String id, long sleepTime) { - super (id, PROBE_TYPE, Kind.JAVA, sleepTime); - } - - public ServerEnablementProbe (String id, long sleepTime, String[] args) { - this (id, sleepTime); - if (args.length == 1) { - m_configurationFile = args[0]; - } - } - - @Override - public void run () { - - Path filePath = new File (m_configurationFile).toPath (); - Path dir = filePath.getParent (); - if (!dir.toFile ().exists ()) { - LOGGER.error (MessageFormat.format ( - "The directory to watch for configuration changes: ''{0}'' does not exist", m_configurationFile)); - return; - } - - Set initialIPs = readBalancerFile (filePath); - - // Report initial enablement - StringBuilder initReport = new StringBuilder (); - for (String ip : initialIPs) { - initReport.append ("i "); - initReport.append (ip); - initReport.append (" "); - } - if (initReport.length () > 0) { - initReport.deleteCharAt (initReport.length () - 1); - reportData (initReport.toString ()); - } - - - try { - WatchService watcher = FileSystems.getDefault ().newWatchService (); - WatchKey key = dir.register (watcher, StandardWatchEventKinds.ENTRY_MODIFY, - StandardWatchEventKinds.ENTRY_CREATE); - - Thread currentThread = Thread.currentThread (); - while (thread () == currentThread && isActive ()) { - try { - Thread.sleep (sleepTime ()); - } - catch (InterruptedException e) { - } - key = watcher.poll (); - if (key != null) { - for (WatchEvent event : key.pollEvents ()) { - WatchEvent.Kind kind = event.kind (); - if (kind == StandardWatchEventKinds.ENTRY_MODIFY - || kind == StandardWatchEventKinds.ENTRY_CREATE) { - WatchEvent ev = (WatchEvent )event; - Path filename = ev.context (); - if (filename.equals (filePath.getFileName ())) { - Set oldIPs = new HashSet<> (initialIPs); - initialIPs = readBalancerFile (filePath); - Set ipsInFile = new HashSet<> (initialIPs); - for (Iterator i = ipsInFile.iterator (); i.hasNext ();) { - String ip = (String )i.next (); - if (oldIPs.contains (ip)) { - i.remove (); - oldIPs.remove (ip); - } - } - // oldIPs now contains IPs that are no longer active - // ipsInFile now contains IPs that are new - StringBuilder report = new StringBuilder (); - if (!oldIPs.isEmpty ()) { - for (String ip : oldIPs) { - report.append ("f "); - report.append (ip); - report.append (" "); - } - } - if (!ipsInFile.isEmpty ()) { - for (String ip : ipsInFile) { - report.append ("o "); - report.append (ip); - report.append (" "); - } - } - if (report.length () > 0) { - report.deleteCharAt (report.length () - 1); - reportData (report.toString ()); - Util.dataLogger ().info (report); - - } - } - } - } - watcher = FileSystems.getDefault ().newWatchService (); - key = dir.register (watcher, StandardWatchEventKinds.ENTRY_MODIFY, - StandardWatchEventKinds.ENTRY_CREATE); - } - } - } - catch (IOException e) { - LOGGER.error (MessageFormat.format ("Could not start a watcher on: ''{0}''", m_configurationFile), e); - - } - } - - Set readBalancerFile (Path filePath) { - Set ipsInFile = new HashSet<> (); - try (BufferedReader reader = Files.newBufferedReader (filePath, Charset.forName ("US-ASCII"))) { - String line = null; - while ((line = reader.readLine ()) != null) { - String[] tokens = line.split (" "); - if ("BalancerMember".equals (tokens[0])) { - tokens = tokens[1].split ("/"); - ipsInFile.add (tokens[2]); - } - } - } - catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace (); - } - return ipsInFile; - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.probes; + +import org.sa.rainbow.translator.probes.AbstractRunnableProbe; +import org.sa.rainbow.util.Util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.*; +import java.text.MessageFormat; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +public class ServerEnablementProbe extends AbstractRunnableProbe { + private static final String PROBE_TYPE = "enablementprobe"; + private String m_configurationFile; + + public ServerEnablementProbe (String id, long sleepTime) { + super (id, PROBE_TYPE, Kind.JAVA, sleepTime); + } + + public ServerEnablementProbe (String id, long sleepTime, String[] args) { + this (id, sleepTime); + if (args.length == 1) { + m_configurationFile = args[0]; + } + } + + @Override + public void run () { + + Path filePath = new File (m_configurationFile).toPath (); + Path dir = filePath.getParent (); + if (!dir.toFile ().exists ()) { + LOGGER.error (MessageFormat.format ( + "The directory to watch for configuration changes: ''{0}'' does not exist", m_configurationFile)); + return; + } + + Set initialIPs = readBalancerFile (filePath); + + // Report initial enablement + StringBuilder initReport = new StringBuilder (); + for (String ip : initialIPs) { + initReport.append ("i "); + initReport.append (ip); + initReport.append (" "); + } + if (initReport.length () > 0) { + initReport.deleteCharAt (initReport.length () - 1); + reportData (initReport.toString ()); + } + + + try { + WatchService watcher = FileSystems.getDefault ().newWatchService (); + WatchKey key = dir.register (watcher, StandardWatchEventKinds.ENTRY_MODIFY, + StandardWatchEventKinds.ENTRY_CREATE); + + Thread currentThread = Thread.currentThread (); + while (thread () == currentThread && isActive ()) { + try { + Thread.sleep (sleepTime ()); + } + catch (InterruptedException e) { + } + key = watcher.poll (); + if (key != null) { + for (WatchEvent event : key.pollEvents ()) { + WatchEvent.Kind kind = event.kind (); + if (kind == StandardWatchEventKinds.ENTRY_MODIFY + || kind == StandardWatchEventKinds.ENTRY_CREATE) { + WatchEvent ev = (WatchEvent )event; + Path filename = ev.context (); + if (filename.equals (filePath.getFileName ())) { + Set oldIPs = new HashSet<> (initialIPs); + initialIPs = readBalancerFile (filePath); + Set ipsInFile = new HashSet<> (initialIPs); + for (Iterator i = ipsInFile.iterator (); i.hasNext ();) { + String ip = (String )i.next (); + if (oldIPs.contains (ip)) { + i.remove (); + oldIPs.remove (ip); + } + } + // oldIPs now contains IPs that are no longer active + // ipsInFile now contains IPs that are new + StringBuilder report = new StringBuilder (); + if (!oldIPs.isEmpty ()) { + for (String ip : oldIPs) { + report.append ("f "); + report.append (ip); + report.append (" "); + } + } + if (!ipsInFile.isEmpty ()) { + for (String ip : ipsInFile) { + report.append ("o "); + report.append (ip); + report.append (" "); + } + } + if (report.length () > 0) { + report.deleteCharAt (report.length () - 1); + reportData (report.toString ()); + Util.dataLogger ().info (report); + + } + } + } + } + watcher = FileSystems.getDefault ().newWatchService (); + key = dir.register (watcher, StandardWatchEventKinds.ENTRY_MODIFY, + StandardWatchEventKinds.ENTRY_CREATE); + } + } + } + catch (IOException e) { + LOGGER.error (MessageFormat.format ("Could not start a watcher on: ''{0}''", m_configurationFile), e); + + } + } + + Set readBalancerFile (Path filePath) { + Set ipsInFile = new HashSet<> (); + try (BufferedReader reader = Files.newBufferedReader (filePath, Charset.forName ("US-ASCII"))) { + String line = null; + while ((line = reader.readLine ()) != null) { + String[] tokens = line.split (" "); + if ("BalancerMember".equals (tokens[0])) { + tokens = tokens[1].split ("/"); + ipsInFile.add (tokens[2]); + } + } + } + catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace (); + } + return ipsInFile; + } + +} diff --git a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ThrottleProbe.java b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ThrottleProbe.java index 7be975d18..6cced433e 100644 --- a/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ThrottleProbe.java +++ b/deployments/rainbow-znn/src/main/java/org/sa/rainbow/translator/znn/probes/ThrottleProbe.java @@ -1,119 +1,119 @@ -/* - * The MIT License - * - * Copyright 2014 CMU ABLE Group. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.sa.rainbow.translator.znn.probes; - -import org.apache.log4j.Logger; -import org.sa.rainbow.core.RainbowComponentT; -import org.sa.rainbow.core.util.RainbowLogger; -import org.sa.rainbow.translator.probes.AbstractRunnableProbe; -import org.sa.rainbow.util.Util; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ThrottleProbe extends AbstractRunnableProbe { - - public final static String PROBE_TYPE = "throttle"; - - private String m_throttleConfFile = null; - - public ThrottleProbe (String id, long sleepTime) { - super (id, PROBE_TYPE, Kind.JAVA, sleepTime); - LOGGER = Logger.getLogger (this.getClass ()); - } - - /** - * Constructor to supply with array of target hosts. - * - * @param id - * the unique name@location identifier of the IProbe - * @param sleepTime - * milliseconds to sleep per cycle - * @param args - * the log file that contains a list of black-holed clients - */ - public ThrottleProbe (String id, long sleepTime, String[] args) { - this (id, sleepTime); - if (args.length == 1) { - m_throttleConfFile = args[0]; - } - } - - @Override - public void run () { - Pattern pattern = Pattern - .compile ("SecRule REMOTE_ADDR \\\"\\^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\\""); - String line = null; - Thread currentThread = Thread.currentThread (); - - if (m_throttleConfFile == null) { - LOGGER.error ("No throttle conf file specified"); - tallyError (); - } - while (thread () == currentThread && isActive ()) { - try { - Thread.sleep (sleepTime ()); - } - catch (InterruptedException e) { - - } - StringBuilder rpt = new StringBuilder (); - boolean reportingThrottle = false; - if (new File (m_throttleConfFile).exists ()) { - try (BufferedReader in = new BufferedReader (new InputStreamReader (new FileInputStream ( - m_throttleConfFile)))) { - StringBuilder clients = new StringBuilder (); - while ((line = in.readLine ()) != null) { - Matcher m = pattern.matcher (line); - if (m.find ()) { - reportingThrottle = true; - if (clients.length () != 0) { - clients.append (", "); - } - clients.append (m.group (1)); - } - } - rpt.append (clients); - } - catch (Exception e) { - RainbowLogger.error (RainbowComponentT.PROBE, "Process execution error!", e, getLoggingPort (), - LOGGER); - tallyError (); - } - } - if (!reportingThrottle) { - reportData ("none"); - } - else { - reportData (rpt.toString ()); - } - Util.dataLogger ().info (rpt.toString ()); - } - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU ABLE Group. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.sa.rainbow.translator.znn.probes; + +import org.apache.log4j.Logger; +import org.sa.rainbow.core.RainbowComponentT; +import org.sa.rainbow.core.util.RainbowLogger; +import org.sa.rainbow.translator.probes.AbstractRunnableProbe; +import org.sa.rainbow.util.Util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ThrottleProbe extends AbstractRunnableProbe { + + public final static String PROBE_TYPE = "throttle"; + + private String m_throttleConfFile = null; + + public ThrottleProbe (String id, long sleepTime) { + super (id, PROBE_TYPE, Kind.JAVA, sleepTime); + LOGGER = Logger.getLogger (this.getClass ()); + } + + /** + * Constructor to supply with array of target hosts. + * + * @param id + * the unique name@location identifier of the IProbe + * @param sleepTime + * milliseconds to sleep per cycle + * @param args + * the log file that contains a list of black-holed clients + */ + public ThrottleProbe (String id, long sleepTime, String[] args) { + this (id, sleepTime); + if (args.length == 1) { + m_throttleConfFile = args[0]; + } + } + + @Override + public void run () { + Pattern pattern = Pattern + .compile ("SecRule REMOTE_ADDR \\\"\\^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\\""); + String line = null; + Thread currentThread = Thread.currentThread (); + + if (m_throttleConfFile == null) { + LOGGER.error ("No throttle conf file specified"); + tallyError (); + } + while (thread () == currentThread && isActive ()) { + try { + Thread.sleep (sleepTime ()); + } + catch (InterruptedException e) { + + } + StringBuilder rpt = new StringBuilder (); + boolean reportingThrottle = false; + if (new File (m_throttleConfFile).exists ()) { + try (BufferedReader in = new BufferedReader (new InputStreamReader (new FileInputStream ( + m_throttleConfFile)))) { + StringBuilder clients = new StringBuilder (); + while ((line = in.readLine ()) != null) { + Matcher m = pattern.matcher (line); + if (m.find ()) { + reportingThrottle = true; + if (clients.length () != 0) { + clients.append (", "); + } + clients.append (m.group (1)); + } + } + rpt.append (clients); + } + catch (Exception e) { + RainbowLogger.error (RainbowComponentT.PROBE, "Process execution error!", e, getLoggingPort (), + LOGGER); + tallyError (); + } + } + if (!reportingThrottle) { + reportData ("none"); + } + else { + reportData (rpt.toString ()); + } + Util.dataLogger ().info (rpt.toString ()); + } + } + +} diff --git a/deployments/rainbow-znn/src/test/java/acmetests/TestNewServerCmd.java b/deployments/rainbow-znn/src/test/java/acmetests/TestNewServerCmd.java index d27cb8371..8eb62ec48 100644 --- a/deployments/rainbow-znn/src/test/java/acmetests/TestNewServerCmd.java +++ b/deployments/rainbow-znn/src/test/java/acmetests/TestNewServerCmd.java @@ -1,73 +1,73 @@ -package acmetests; - -import auxtestlib.DefaultTCase; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.standalone.resource.StandaloneResource; -import org.acmestudio.standalone.resource.StandaloneResourceProvider; -import org.junit.Test; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.ports.IModelChangeBusPort; -import org.sa.rainbow.core.ports.eseb.ESEBConstants; -import org.sa.rainbow.model.acme.AcmeModelOperation; -import org.sa.rainbow.model.acme.AcmeRainbowOperationEvent.CommandEventT; -import org.sa.rainbow.model.acme.znn.ZNNModelUpdateOperatorsImpl; - -import java.util.List; - -import static org.sa.rainbow.testing.prepare.utils.EffectorTestingUtil.mockAnnouncePort; - - -public class TestNewServerCmd extends DefaultTCase { - - @Test - public void test() throws Exception { - StandaloneResource resource = StandaloneResourceProvider.instance().acmeResourceForString( - "src/test/resources/acme/znn.acme"); - IAcmeSystem sys = resource.getModel().getSystems().iterator().next(); - assertTrue(sys.getDeclaredTypes().iterator().next().isSatisfied()); - ZNNModelUpdateOperatorsImpl znn = new ZNNModelUpdateOperatorsImpl(sys, "src/test/resources/acme/znn.acme"); - IAcmeComponent proxy = sys.getComponent("lbproxy"); - AcmeModelOperation cns = znn.getCommandFactory().connectNewServerCmd(proxy, "server", - "10.5.6.6", "1080"); - IModelChangeBusPort announcePort = mockAnnouncePort(); - assertTrue(cns.canExecute()); - List generatedEvents = cns.execute(znn, announcePort); - IAcmeComponent server = cns.getResult(); - assertTrue(cns.canUndo()); - assertFalse(cns.canExecute()); - assertFalse(cns.canRedo()); - assertNotNull(server); - assertNotNull(sys.getConnector("proxyconn")); - assertNotNull(sys.getAttachment(server.getPort("http"), sys.getConnector("proxyconn").getRole("rec"))); - assertNotNull(sys.getAttachment(proxy.getPort("fwd"), sys.getConnector("proxyconn").getRole("req"))); - outputMessages(generatedEvents); - checkEventProperties(generatedEvents); - - cns = znn.getCommandFactory().connectNewServerCmd(proxy, "server", "10.5.6.6", "1080"); - - generatedEvents = cns.execute(znn, announcePort); - server = cns.getResult(); - assertNotNull(server); - assertNotNull(sys.getAttachment(proxy.getPort("fwd4"), sys.getConnector("proxyconn4").getRole("req"))); - assertNotNull(sys.getAttachment(server.getPort("http"), sys.getConnector("proxyconn4").getRole("rec"))); - outputMessages(generatedEvents); - checkEventProperties(generatedEvents); - } - - private void checkEventProperties(List generatedEvents) { - assertTrue(generatedEvents.size() > 0); - assertTrue(generatedEvents.iterator().next().getProperty(IModelChangeBusPort.EVENT_TYPE_PROP).equals(CommandEventT.START_COMMAND.name())); - assertTrue(generatedEvents.get(generatedEvents.size() - 1).getProperty(IModelChangeBusPort.EVENT_TYPE_PROP).equals(CommandEventT.FINISH_COMMAND.name())); - for (IRainbowMessage msg : generatedEvents) { - assertTrue(msg.getPropertyNames().contains(ESEBConstants.MSG_TYPE_KEY)); - } - } - - private void outputMessages(List events) { - for (IRainbowMessage msg : events) { - System.out.println(msg.toString()); - } - } - -} +package acmetests; + +import auxtestlib.DefaultTCase; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.standalone.resource.StandaloneResource; +import org.acmestudio.standalone.resource.StandaloneResourceProvider; +import org.junit.Test; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.ports.IModelChangeBusPort; +import org.sa.rainbow.core.ports.eseb.ESEBConstants; +import org.sa.rainbow.model.acme.AcmeModelOperation; +import org.sa.rainbow.model.acme.AcmeRainbowOperationEvent.CommandEventT; +import org.sa.rainbow.model.acme.znn.ZNNModelUpdateOperatorsImpl; + +import java.util.List; + +import static org.sa.rainbow.testing.prepare.utils.EffectorTestingUtil.mockAnnouncePort; + + +public class TestNewServerCmd extends DefaultTCase { + + @Test + public void test() throws Exception { + StandaloneResource resource = StandaloneResourceProvider.instance().acmeResourceForString( + "src/test/resources/acme/znn.acme"); + IAcmeSystem sys = resource.getModel().getSystems().iterator().next(); + assertTrue(sys.getDeclaredTypes().iterator().next().isSatisfied()); + ZNNModelUpdateOperatorsImpl znn = new ZNNModelUpdateOperatorsImpl(sys, "src/test/resources/acme/znn.acme"); + IAcmeComponent proxy = sys.getComponent("lbproxy"); + AcmeModelOperation cns = znn.getCommandFactory().connectNewServerCmd(proxy, "server", + "10.5.6.6", "1080"); + IModelChangeBusPort announcePort = mockAnnouncePort(); + assertTrue(cns.canExecute()); + List generatedEvents = cns.execute(znn, announcePort); + IAcmeComponent server = cns.getResult(); + assertTrue(cns.canUndo()); + assertFalse(cns.canExecute()); + assertFalse(cns.canRedo()); + assertNotNull(server); + assertNotNull(sys.getConnector("proxyconn")); + assertNotNull(sys.getAttachment(server.getPort("http"), sys.getConnector("proxyconn").getRole("rec"))); + assertNotNull(sys.getAttachment(proxy.getPort("fwd"), sys.getConnector("proxyconn").getRole("req"))); + outputMessages(generatedEvents); + checkEventProperties(generatedEvents); + + cns = znn.getCommandFactory().connectNewServerCmd(proxy, "server", "10.5.6.6", "1080"); + + generatedEvents = cns.execute(znn, announcePort); + server = cns.getResult(); + assertNotNull(server); + assertNotNull(sys.getAttachment(proxy.getPort("fwd4"), sys.getConnector("proxyconn4").getRole("req"))); + assertNotNull(sys.getAttachment(server.getPort("http"), sys.getConnector("proxyconn4").getRole("rec"))); + outputMessages(generatedEvents); + checkEventProperties(generatedEvents); + } + + private void checkEventProperties(List generatedEvents) { + assertTrue(generatedEvents.size() > 0); + assertTrue(generatedEvents.iterator().next().getProperty(IModelChangeBusPort.EVENT_TYPE_PROP).equals(CommandEventT.START_COMMAND.name())); + assertTrue(generatedEvents.get(generatedEvents.size() - 1).getProperty(IModelChangeBusPort.EVENT_TYPE_PROP).equals(CommandEventT.FINISH_COMMAND.name())); + for (IRainbowMessage msg : generatedEvents) { + assertTrue(msg.getPropertyNames().contains(ESEBConstants.MSG_TYPE_KEY)); + } + } + + private void outputMessages(List events) { + for (IRainbowMessage msg : events) { + System.out.println(msg.toString()); + } + } + +} diff --git a/deployments/rainbow-znn/src/test/resources/acme/imports.acme b/deployments/rainbow-znn/src/test/resources/acme/imports.acme index 3ac812089..9050035ed 100644 --- a/deployments/rainbow-znn/src/test/resources/acme/imports.acme +++ b/deployments/rainbow-znn/src/test/resources/acme/imports.acme @@ -1,4 +1,4 @@ -import "families/f1.acme"; -system s : f1 = new f1 extended with { - component c : CT = new CT; +import "families/f1.acme"; +system s : f1 = new f1 extended with { + component c : CT = new CT; } \ No newline at end of file diff --git a/deployments/rainbow-znn/src/test/resources/acme/inbuilt-system.acme b/deployments/rainbow-znn/src/test/resources/acme/inbuilt-system.acme index 3898789d8..addb5fe5b 100644 --- a/deployments/rainbow-znn/src/test/resources/acme/inbuilt-system.acme +++ b/deployments/rainbow-znn/src/test/resources/acme/inbuilt-system.acme @@ -1,9 +1,9 @@ -family f1 = { - - component type CT = { - property p : int; - } -} -system s : f1 = new f1 extended with { - component c : CT = new CT; +family f1 = { + + component type CT = { + property p : int; + } +} +system s : f1 = new f1 extended with { + component c : CT = new CT; } \ No newline at end of file diff --git a/deployments/rainbow-znn/src/test/resources/acme/self-contained.acme b/deployments/rainbow-znn/src/test/resources/acme/self-contained.acme index 63362bbe3..a019b82c9 100644 --- a/deployments/rainbow-znn/src/test/resources/acme/self-contained.acme +++ b/deployments/rainbow-znn/src/test/resources/acme/self-contained.acme @@ -1,3 +1,3 @@ -system s = { - component c; +system s = { + component c; } \ No newline at end of file diff --git a/deployments/rainbow-znn/src/test/resources/acme/znn.acme b/deployments/rainbow-znn/src/test/resources/acme/znn.acme index 15511dbfe..5da216500 100644 --- a/deployments/rainbow-znn/src/test/resources/acme/znn.acme +++ b/deployments/rainbow-znn/src/test/resources/acme/znn.acme @@ -1,270 +1,270 @@ -Family ZNewsFam = { - - Port Type HttpPortT = { - - } - Role Type RequestorRoleT = { - - } - Component Type ProxyT = { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - } - Port Type ProxyForwardPortT = { - - } - Component Type ServerT = { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - Property reqServiceRate : float << default : float = 0.0; >> ; - - Property byteServiceRate : float << default : float = 0.0; >> ; - - Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; - - Property cost : float << default : float = 1.0; >> ; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - Role Type ReceiverRoleT = { - - } - Connector Type ProxyConnT = { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - Component Type ClientT = { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property experRespTime : float << default : float = 0.0; >> ; - - Property reqRate : float << default : float = 0.0; >> ; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - Port Type HttpReqPortT = { - - } - Connector Type HttpConnT = { - - Property bandwidth : float << default : float = 0.0; >> ; - - Property latency : float << default : float = 0.0; >> ; - - Property numReqsSuccess : int << default : int = 0; >> ; - - Property numReqsRedirect : int << default : int = 0; >> ; - - Property numReqsClientError : int << default : int = 0; >> ; - - Property numReqsServerError : int << default : int = 0; >> ; - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - - Property MIN_RESPTIME : float; - - Property MAX_RESPTIME : float; - - Property TOLERABLE_PERCENT_UNHAPPY : float; - - Property UNHAPPY_GRADIENT_1 : float; - - Property UNHAPPY_GRADIENT_2 : float; - - Property UNHAPPY_GRADIENT_3 : float; - - Property FRACTION_GRADIENT_1 : float; - - Property FRACTION_GRADIENT_2 : float; - - Property FRACTION_GRADIENT_3 : float; - - Property MIN_UTIL : float; - - Property MAX_UTIL : float; - - Property MAX_FIDELITY_LEVEL : int; - - Property THRESHOLD_FIDELITY : int; - - Property THRESHOLD_COST : float; -} - -System ZNewsSys : ZNewsFam = { - - - Property MIN_RESPTIME : float = 100; - - Property MAX_RESPTIME : float = 2000; - - Property UNHAPPY_GRADIENT_1 : float = 0.1; - - Property UNHAPPY_GRADIENT_2 : float = 0.2; - - Property UNHAPPY_GRADIENT_3 : float = 0.5; - - Property FRACTION_GRADIENT_1 : float = 0.2; - - Property FRACTION_GRADIENT_2 : float = 0.4; - - Property FRACTION_GRADIENT_3 : float = 1.0; - - Property TOLERABLE_PERCENT_UNHAPPY : float = 0.25; - - Property MIN_UTIL : float = 0.1; - - Property MAX_UTIL : float = 0.75; - - Property MAX_FIDELITY_LEVEL : int = 5; - - Property THRESHOLD_FIDELITY : int = 2; - - Property THRESHOLD_COST : float = 6.0; - Component s1 : ServerT = new ServerT extended with { - - Property deploymentLocation = "127.0.0.2"; - Port http0 : HttpPortT = new HttpPortT extended with { - - } - - } - Component lbproxy : ProxyT = new ProxyT extended with { - - Property deploymentLocation = "127.0.0.1"; - Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port http0 : HttpPortT = new HttpPortT extended with { - - } - Port http1 : HttpPortT = new HttpPortT extended with { - - } - Port http2 : HttpPortT = new HttpPortT extended with { - - } - - } - Component s2 : ServerT = new ServerT extended with { - - Property deploymentLocation = "127.0.0.3"; - Port http0 : HttpPortT = new HttpPortT extended with { - - } - - } - Component s3 : ServerT = new ServerT extended with { - - Property deploymentLocation = "127.0.0.4"; - Port http0 : HttpPortT = new HttpPortT extended with { - - } - - } - Component s0 : ServerT = new ServerT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property cost = 1.0; - - Property fidelity = 5; - - Property load = 0.0; - Port http0 : HttpPortT = new HttpPortT extended with { - - } - - } - Component c0 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property experRespTime : float = 50.0; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - } - - } - Component c1 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property experRespTime : float = 50; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - } - - } - Component c2 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property experRespTime : float = 50; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - } - - } - Connector conn0 : HttpConnT = new HttpConnT extended with { - - } - Connector proxyconn0 : ProxyConnT = new ProxyConnT extended with { - - } - Connector proxyconn1 : ProxyConnT = new ProxyConnT extended with { - - } - Connector proxyconn3 : ProxyConnT = new ProxyConnT extended with { - - } - Connector proxyconn2 : ProxyConnT = new ProxyConnT extended with { - - } - Connector conn : HttpConnT = new HttpConnT extended with { - - } - Connector conn1 : HttpConnT = new HttpConnT extended with { - - } - Attachment lbproxy.fwd0 to proxyconn0.req; - Attachment s2.http0 to proxyconn2.rec; - Attachment lbproxy.fwd1 to proxyconn1.req; - Attachment s1.http0 to proxyconn1.rec; - Attachment s0.http0 to proxyconn0.rec; - Attachment c0.p0 to conn0.req; - Attachment lbproxy.http0 to conn0.rec; - Attachment s3.http0 to proxyconn3.rec; - Attachment lbproxy.fwd3 to proxyconn3.req; - Attachment c1.p0 to conn.req; - Attachment c2.p0 to conn1.req; - Attachment lbproxy.http2 to conn1.rec; - Attachment lbproxy.http1 to conn.rec; -} - +Family ZNewsFam = { + + Port Type HttpPortT = { + + } + Role Type RequestorRoleT = { + + } + Component Type ProxyT = { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Port Type ProxyForwardPortT = { + + } + Component Type ServerT = { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + Property reqServiceRate : float << default : float = 0.0; >> ; + + Property byteServiceRate : float << default : float = 0.0; >> ; + + Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; + + Property cost : float << default : float = 1.0; >> ; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + Role Type ReceiverRoleT = { + + } + Connector Type ProxyConnT = { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Component Type ClientT = { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property experRespTime : float << default : float = 0.0; >> ; + + Property reqRate : float << default : float = 0.0; >> ; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + Port Type HttpReqPortT = { + + } + Connector Type HttpConnT = { + + Property bandwidth : float << default : float = 0.0; >> ; + + Property latency : float << default : float = 0.0; >> ; + + Property numReqsSuccess : int << default : int = 0; >> ; + + Property numReqsRedirect : int << default : int = 0; >> ; + + Property numReqsClientError : int << default : int = 0; >> ; + + Property numReqsServerError : int << default : int = 0; >> ; + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + + Property MIN_RESPTIME : float; + + Property MAX_RESPTIME : float; + + Property TOLERABLE_PERCENT_UNHAPPY : float; + + Property UNHAPPY_GRADIENT_1 : float; + + Property UNHAPPY_GRADIENT_2 : float; + + Property UNHAPPY_GRADIENT_3 : float; + + Property FRACTION_GRADIENT_1 : float; + + Property FRACTION_GRADIENT_2 : float; + + Property FRACTION_GRADIENT_3 : float; + + Property MIN_UTIL : float; + + Property MAX_UTIL : float; + + Property MAX_FIDELITY_LEVEL : int; + + Property THRESHOLD_FIDELITY : int; + + Property THRESHOLD_COST : float; +} + +System ZNewsSys : ZNewsFam = { + + + Property MIN_RESPTIME : float = 100; + + Property MAX_RESPTIME : float = 2000; + + Property UNHAPPY_GRADIENT_1 : float = 0.1; + + Property UNHAPPY_GRADIENT_2 : float = 0.2; + + Property UNHAPPY_GRADIENT_3 : float = 0.5; + + Property FRACTION_GRADIENT_1 : float = 0.2; + + Property FRACTION_GRADIENT_2 : float = 0.4; + + Property FRACTION_GRADIENT_3 : float = 1.0; + + Property TOLERABLE_PERCENT_UNHAPPY : float = 0.25; + + Property MIN_UTIL : float = 0.1; + + Property MAX_UTIL : float = 0.75; + + Property MAX_FIDELITY_LEVEL : int = 5; + + Property THRESHOLD_FIDELITY : int = 2; + + Property THRESHOLD_COST : float = 6.0; + Component s1 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.2"; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component lbproxy : ProxyT = new ProxyT extended with { + + Property deploymentLocation = "127.0.0.1"; + Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port http0 : HttpPortT = new HttpPortT extended with { + + } + Port http1 : HttpPortT = new HttpPortT extended with { + + } + Port http2 : HttpPortT = new HttpPortT extended with { + + } + + } + Component s2 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.3"; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component s3 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.4"; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component s0 : ServerT = new ServerT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property cost = 1.0; + + Property fidelity = 5; + + Property load = 0.0; + Port http0 : HttpPortT = new HttpPortT extended with { + + } + + } + Component c0 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50.0; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + } + + } + Component c1 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + } + + } + Component c2 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + } + + } + Connector conn0 : HttpConnT = new HttpConnT extended with { + + } + Connector proxyconn0 : ProxyConnT = new ProxyConnT extended with { + + } + Connector proxyconn1 : ProxyConnT = new ProxyConnT extended with { + + } + Connector proxyconn3 : ProxyConnT = new ProxyConnT extended with { + + } + Connector proxyconn2 : ProxyConnT = new ProxyConnT extended with { + + } + Connector conn : HttpConnT = new HttpConnT extended with { + + } + Connector conn1 : HttpConnT = new HttpConnT extended with { + + } + Attachment lbproxy.fwd0 to proxyconn0.req; + Attachment s2.http0 to proxyconn2.rec; + Attachment lbproxy.fwd1 to proxyconn1.req; + Attachment s1.http0 to proxyconn1.rec; + Attachment s0.http0 to proxyconn0.rec; + Attachment c0.p0 to conn0.req; + Attachment lbproxy.http0 to conn0.rec; + Attachment s3.http0 to proxyconn3.rec; + Attachment lbproxy.fwd3 to proxyconn3.req; + Attachment c1.p0 to conn.req; + Attachment c2.p0 to conn1.req; + Attachment lbproxy.http2 to conn1.rec; + Attachment lbproxy.http1 to conn.rec; +} + diff --git a/deployments/rainbow-znn/src/test/resources/log4j.properties b/deployments/rainbow-znn/src/test/resources/log4j.properties index 6b8797ece..4c0d3a502 100644 --- a/deployments/rainbow-znn/src/test/resources/log4j.properties +++ b/deployments/rainbow-znn/src/test/resources/log4j.properties @@ -1,4 +1,4 @@ -log4j.rootLogger=INFO,CONSOLE -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%-5p $c{1} - %m%n +log4j.rootLogger=INFO,CONSOLE +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%-5p $c{1} - %m%n diff --git a/deployments/rainbow-znn/src/test/resources/log4j.xml b/deployments/rainbow-znn/src/test/resources/log4j.xml index 74d4dcd16..829891348 100644 --- a/deployments/rainbow-znn/src/test/resources/log4j.xml +++ b/deployments/rainbow-znn/src/test/resources/log4j.xml @@ -1,21 +1,21 @@ - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/documents/RCL.md b/documents/RCL.md new file mode 100644 index 000000000..873c78828 --- /dev/null +++ b/documents/RCL.md @@ -0,0 +1,1043 @@ +# Rainbow Configuration Language and Editor + +## Introduction + +The Rainbow Configuration Language (RCL) is a DSL written using the [Xtext framework](https://www.eclipse.org/Xtext) +that allows the definition of language compilation and Eclipse IDE support. RCL works +with files that have the extension `.rbw`, and will attempt to compile these files +into the specification files (YAML, properties) that are required by Rainbow target +definitions. Previously, Rainbow target definitions involved writing these files by +hand which was error prone for various reasons, not the least of which was that there +is no consistency checking between these different files. For example, if a Gauge referred +to a Probe, there was no guarantee that the probe was specified correctly in the target. +These errors went undiscovered until errors occurred when running Rainbow. + +With this new feature, consistency will be checked across the different `.rbw` files +as long as they are imported, including checking references to Java classes that are on the classpath. +This typechecking also happens when building and deploying targets using Maven, as +is discussed in [Building Targets with Maven](#building-targets-with-maven). This document +is organized as follows: + +| Section | Description | +| --- | --- | +| [Target Definition](#target-definition-and-layout) | Describes how to organize the +target | +| [RCL Syntax and Conventions](#features) | The Syntax of RCL | +| [Specifying Properties](#properties-files) | Specifying Rainbow Properties | +| [Model Command Factories](#model-command-factories) | Specifying (and generating) model command factories | +| [Probes](#probe-specifications) | How to define probes in the system | +| [Gauges](#gauge-specification) | How to specify gauges | +| [Effectors](#effector-specifications) | How to specify effectors | +| [Stitch and Utilities](#stitch-and-utility-preferences) | Specifying adaptation with +Stitch and utility preferences | +| [Installing the Eclipse plugin](#installing) | Using with Eclipse | +| [Building targets with Mavem](#building-targets-with-maven) | How to build the target +using Maven | + +## Target Definition and Layout + +To get the most out of the Eclipse plugin, targets should be defined in Eclipse projects +that have the implementation for the deployment (the Java classes implementing commands, +adaptation managers, analyzer etc) on the classpath. This has led to the need to rethink +the layout of target definitions. For target definitions to work inside of Eclipse, +the Java project should be organized as follows: + +``` ++ Java project ++-- src/ + +-- main/ + +-- java/ +``` + Contains the source code for the deployment +``` + +-- resources/ + +-- rbw/ + +-- / +``` + This defines the files used to specify a target. + Can be given any names (and may be multiples) +``` + +-- model/ + +-- gauges.rbw +``` + Defines the gauges that are used for this target +``` + +-- stitch/ +``` + This directory is optional but needed if you are using + Stitch-based adaptation +``` + +-- .s +``` + Any file ending in .s is a Stitch file +``` + +-- utilities.rbw +``` + Specifies the Utility and Impact models for the target +``` + +-- system/ + +-- probes.rbw +``` + Specifies what probes are deployed and where +``` + +-- effectors.rbw +``` + Specifies what effectors are deployed and where +``` + +-- +``` + Defines the properties used to configure Rainbow +``` + +-- acme/ +``` + The Acme files that specify the architecture for the system + of this deployment. (Only needed if Acme is being used.) +``` + +-- .rbw +``` + Used to generate the command factories +``` +``` +If Command Factories are specified as above, then `src/main/java-gen` should be created +and put on the build path in Eclipse. (Java files to be compiled into classes will +be generated here.) + +## Features + +### General Syntax + +A configuration file for the most part follows the conventions laid down by previous +versions of Rainbow. Each file begins with a target name (specifying the name of the target +it belongs to) and a set of import statements, and ending with an export statement saying which file is generated as a result. +For example, the file [properties.rbw](../deployments/rainbow-example/src/main/resources/rbw/rainbow-example/properties.rbw) + +``` +target rainbow-example +import properties "model/gauges.rbw" + +... + +export * to "rainbow-gui.properties" +``` + +The first line indicates that this is a file for the target `rainbow-example`. The second line imports properties defined in the file `model/gauges.rbw`. This means that +gauges defined in that file may be referred to in this file. The final line says to export all (`*`) properties to the file `rainbow-gui.properties`. + +#### Property names and keywords + +Names in RCL can be fully qualified. Unfortunately, because RCL also imports grammar elements from Stitch and Acme, +it is often the case that names may clash with keywords. To overcome this, RCL uses the convention that if an element of a name is +a keyword, it can be preceded with a caret (`^`) which will then be ignored. So, for example, the property name: + +``` +def rainbow.deployment.^factory.class = ... +``` + +contains the keyword `factory`, but is exported as `rainbow.deployment.factory.class`. Admittedly this a a little messy, but it +does allow the incorporation of other grammars without a fear of name clashes. This can also be used when referring to Java classes. For example, +`acme` is a keyword in RCL and so to refer to the class `org.sa.rainbow.evaluator.acme.ArchEvaluator` you need to use `org.sa.rainbow.evaluator.^acme.ArchEvaluator`. + + +#### Referencing properties in other properties + +Properties may be referenced inside strings and on their own. To reference a property in a string, surrond it with `«...»`, e.g., + +``` +def event.log.path = "log" +def logging.path = "«event.log.path»/rainbow.out" +``` + +When referencing it outside a string, use double `««...»»`, e.g., + +``` +def customize.system.^target.master = ««rainbow.deployment.location»» +``` + +To insert `«` type Ctrl-Shift-<, `»` in the provided Eclipse plugin type Ctrl-Shift-> (Cmd-Shift on MacOS). Also autocomplete +will give these proposals and there is context sensitive bracket completion (so you get `««|»»` or `«|»` depending on if you are in a string or not (`|` indicates where the cursor will end up when you type Ctrl-Shift-<). + +### Acme and Stitch + +Most of the work on Rainbow uses Stitch and architecture models represented by Acme in models and adaptation management and execution. RCL supports these languages out of the box. +The current support for these languages in the Eclipse editor is minimal. There is simple parsing and scoping, but no other typechecking. This allows RCL configuration files to reference +names defined in Acme and Stitch files, but little else. Tis may change in the future. + +## Properties Files + +The rest of this file contains definitions of properties for configuring Rainbow. The syntax for declaring a property is: + +`def ? (= )?` + +There are eight types of properties that can be defined, and the type of the property indicates what subfields (if any) it should have as well as the contexts in which it can be referenced. There kinds of properties are: + +| Keyword | Description | +| --- | --- | +| _none_ | This is a generic property that can have any kind of value. | +| model | Defines a Rainbow model, and needs to specify things like the command factory, how to load a model, etc.| +| analysis | Defines a Rainbow analysis. It needs to specify a class that implements `org.rainbow.core.analysis.IRainbowAnalysis`. Analyses provide information about about state of the models. | +| adaptation-manager | Defines a Rainbow adaptation manager, which chooses what to do if an adaptation is required. It must impliment `org.sa.rainbow.stitch.adaptation.IAdaptationManager`.| +| executor | Defines a Rainbow Executor, that executes adaptation plans generated by the adaptation manager. It must implement `org.sa.rainbow.core.adaptation.IAdaptationExecutor` | +| effector-manager | Defines the class used to manager Effectors. | +| utility | Defines the utility profile and scenarios (only useful if Stitch is used) | +| gui | Defines which class (and associated configuration options) to use for the Rainbow GUI. | + + +### General Properties + +The Rainbow properties file defines properties for customizing the Rainbow deployment and architecture, as well as +properties that define the system that is being managed, like the location of components etc. These properties are used internally by Rainbow at startup, or may be used by +components of Raibow (e.g., in models). If you look at [properties.rbw](../deployments/rainbow-example/src/main/resources/rbw/rainbow-example/properties.rbw), you may be able to +see that the file is divided into several sections, though this is done out of convention and is not mandated. + +The first part is: + +``` +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. +def rainbow.path # Default property defined by rainbow + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +def logging.level = DEBUG +def event.log.path = "log" +def logging.path = "«event.log.path»/rainbow.out" +def monitoring.log.path = "«event.log.path»/rainbow-data.log" +``` + +This section is unlikely to change, though you may want to change the logging level. + +The next section specifies how Rainbow is being deployed and how different components should +communicate. + +``` +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +def rainbow.master.location.host = "rainbow-example" +#- Location information of the deployed delegate +def rainbow.deployment.location = "rainbow-example" +#- default registry port; change if port-tunneling +def rainbow.master.location.^port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +def rainbow.deployment.environment = "linux" + +def rainbow.delegate.beaconperiod = 10000 +def rainbow.deployment.^factory.class = org.sa.rainbow.core.ports.guava.GuavaRainbowPortFactory + +``` + +The first two properties need to contain the name or IP of the machine on which the Rainbow master will be running. Rainbow is composed of two main components - the Rainbow Master (or Oracle) which collates information from probes, stores the models, runs analysis and adaptation management, and manages the execution of adaptations. +There is also a Rainbow delegate, which is a component that manages running of probes, gauges, and effectors. There may be multiple instances of delegates running on different machines, thus enabling target systems to be +probed and effected locally. Delegates need to know the location of the master, and this property is used to communicate that. + +`def rainbow.master.location.^port` specifies which socket Rainbow opens up for communication. + +`def rainbow.deployment.environment` specifies what OS is running the master, which helps with starting shell scripts. "linux" is currently the only one fully tested, and it should also be ok for using on MacOS. + +`def rainbow.delegate.beaconperiod` specifies how often a delegate should send a heartbeat back to the master indicating it is alive. The Master will use this to make sure that Rainbow is deployed properly. + +`def rainbow.deployment.^factory.class` specifies how Rainbow components should communicate. Currently, two options are supported: + +1. `org.sa.rainbow.core.ports.guava.GuavaRainbowPortFactory` implements communication across a Guava Event Bus. It is intended to be used when Rainbow runs entirely on one machine. +2. `org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory` implements a custom event bus that is used to communicate across machines using `rainbow.master.location.port`. + +Skipping to the end of the file, this is where properties that are specific to the system being targeted, or where your own properties can be defined. + +The following properties in most circumstances should not be changed: + +``` +## Translator customization +#- Gauge spec +def customize.gauges.path = "model/gauges.yml" +#- Probe spec +def customize.probes.path = "system/probes.yml" +#- Effector spec +def customize.effectors.path = "system/effectors.yml" +## Adaptation Manager +#- Directory of Stitch adaptation script +def customize.scripts.path = "stitch" +#- Utilities description file, Strategy evaluation config, and minimum score threshold +def customize.^utility.path = "stitch/utilities.yml" +def customize.^utility.trackStrategy = "uC" +def customize.^utility.score.minimum.threshold = 0.033 +def customize.^utility.scenario = "scenario 1" + +``` + +These properties specify where Rainbow should find information about probes, gauges, etc, that are now generated by RCL. +The last properties are to do with Stitch and utilities. The last three may be changed, depending on what you want tracked and what scenarion (defined now in `utilities.rbw` should be used). + + +The other properties towards the end (beginning with `customize` need to be customized to the target system that you are wanting Rainbow to manage. In the current example, they specify properties +associated with Rubis example. + +### Models + +Models are used in Rainbow to specify information that is kept by Rainbow about the +managed (target) system and its environment. Models are updated by gauges using most +often using information from probes and translating them into changes on models. Analyses +can also update models. The adaptation manager can also query model information to help +decide what adaptations to perform. + +Models in Rainbow have two kinds of interface: a query interface that is used to read +information from a model, and an operation interface that is used to update models. +Operations on models are produced with command factories, specified by the rainbow configuration, +and are managed by Rainbow. Rainbow publishes operations when models are updated so +that interested components can be notified about changes to models. Operations can also +be undone by Rainbow so that if an operation fails, the model can be rolled back to +the previous version. + +To specify a model in RCL, you define a _model_ property, which may be referred to by +other components such as gauges and effectors. + +``` +# Rainbow Acme model of SWIM +def model SwimSys= { + ^type="Acme" + path="model/swim.acme" + ^factory=««SWIM»» + saveOnClose = true + saveLocation="model/swim-post.acme" +} +``` + +The `path` attribute indicates the file in the target that should be used to initialize the model. It is optional though most often should be specified. The model is loaded through the command factory, which is specified +with the `factory` attribute. The factory attribute can either point to a factory specified in +RCL or a class that extends +`org.sa.rainbow.core.models.commands.ModelCommandFactory` (see [Model Command Factory](#model-command-factories)). +The `type` indicates the type of the Model that should be registered with Rainbow. In this case, a model called `SwimSys` with the type `Acme` will be loaded into Rainbow. +If you want the model to be saved when Rainbow quits, you should specify this by setting `saveOnClose` and indicating where the model should be saved in `saveLocation`. + +### Other components + +The other types of components are also specified by defining typed properties. For evaluators and effector managers, only the class needs to be specified. For adaptation managers and executors, the model on which they operate +also needs to specified, through reference to a model property. For example, + +``` +def adaptation-manager AdaptationManager = { + ^model=««SwimSys»» + class=org.sa.rainbow.^stitch.adaptation.AdaptationManager +} +``` + +Specifies to start an Adaptation Manager with the name `AdaptationManager` using the +class `org.sa.rainbow.stitch.adaptation.AdaptationManager` and which is associated with the model +called `SwimSys`. + +Similarly: + +``` +def executor StitchExecutor = { + ^model=««SwimSys»» + class=org.sa.rainbow.^stitch.adaptation.StitchExecutor +} +``` + +## Model Command Factories +Model command factories are classes in Rainbow that are used to implement possible operations +on models. They are used by gauges to update models, and they are used in executors +to specify how to change the system - in this last case they are not performed directly +on the model but are intercepted by effectors and translated into operations on the +managed system. So, specifying a model command factory involves implementing/specifying +two things: operations and command factories to create the operations. + +### Implementing Rainbow Operations in Java + +Operations in Rainbow need to implement the interface +[org.sa.rainbow.core.models.commands.IRainbowModelOperation](../rainbow/rainbow-core/src/main/java/org/sa/rainbow/core/models/commands/IRainbowOperation.java). +In practice, there are two possible classes that you will extend. + +1. If you are dealing with Acme models, you will extend + [org.sa.rainbow.model.acme.AcmeModelOpetation](../rainbow/rainbow-acme-model/src/main/java/org/sa/rainbow/model/acme/AcmeModelOperation.java), + which is a generic class where you specify the result of the operation. You will + need to specify doConstructCommand, which returns the Acme command (IAcmeCommand) + that will operate on the Acme model. + +2. If you are defining your own model class, you will extend + [org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation](../rainbow/rainbow-core/src/main/java/org/sa/rainbow/core/models/commands/AbstractRainbowModelOperation.java). + This is a generic class that takes two parameters: the class of the model object + managed by Rainbow and the type of the result of the operation. In most cases, you will need to specify methods for executing, redoing, and undoing +the operations, as well as a method to ensure that the operation is valid on the model. + +For an example of an Acme operation, look at [org.sa.rainbow.model.acme.swim.commands.ActivateServerCmd](). +For an example of a non-Acme operation, check out the operations in the _rainbow-utility-model_ +project. + +### Specifying Command Factories + +In prior versions of Rainbow, these classes had to be handwritten, which was often tedious +and error prone. With RCL, command factories can be specified and the Java class generated. +If the model uses an existing command factory, then it should specify that class in +the **factory** property. Otherwise the factory property will be a reference to a command +factory specified in RCL. + +``` +model factory SWIM yields org.sa.rainbow.^model.^acme.swim.commands.SwimCommandFactory { + extends org.sa.rainbow.^model.^acme.AcmeModelCommandFactory + for org.sa.rainbow.^model.^acme.AcmeModelInstance + + command load is org.sa.rainbow.^model.^acme.swim.commands.SwimLoadModelCommand + command setDimmer(SwimFam.LoadBalancerT target, int dimmer) + is org.sa.rainbow.^model.^acme.swim.commands.SetDimmerCmd; + ... +} +``` + +Above is a fragment of a command factory specified in a RCL. The name **SWIM** specified +the name that will be used to refer to the factory in other RCL configuration file. +The class after **yields** specifies what Java class will be generated (by default in +the _src/main/java-gen_ directory) and what superclass it will have (optional). It also +specifies the class that implements the model that this factory is **for**. + +Following the **extends** and **for** specifications, two optional standard operations +are specified. The **load** command is used by Rainbow at start up to initialize the +model. The class that is specified must extend _org.sa.rainbow.core.models.commands.AbstractLoadModelCmd_. +It is also possible to specify an operation to save a model when Rainbow is finished +(using the **save** keyword instead of **load**). This operation must extend _org.sa.rainbow.core.models.commands.AbstractSaveoModelCmd_. + +After this comes the list of operations that the model can produce, e.g.: + +``` + command setDimmer(SwimFam.LoadBalancerT target, int dimmer) + is org.sa.rainbow.^model.^acme.swim.commands.SetDimmerCmd; +``` + +The first part is the name of the operation (which may be referred to by gauges and +effectors), e.g., _setDimmer_. Following this are the parameters for the operation. +The first argument may be a **target** which specifies the kind of model element that +the operation is defined on. The following list of arguments specify the operation paramters. +Operation argument types can refer to Acme types, +Java types, or builtin types like **int**, **String**, etc. Finally, the operation +specifies the implementing class for the operation. + +## Probe Specifications + +Probes are instruments in the running system that provide system-specific information +to Rainbow. Such information is converted to model information by _gauges_. There are +two types of probes supported by Rainbow: script based probes and Java probes. +In both cases, the `probes.rbw` file needs to be updated with the new probe information. +This file usually lives in the `system` directory of a target. See [Required Probe Fields](#required-probe-fields) +for a list of all the properties for a probe. + +### Probe Types + +Probe types specify information about probes that instances inherit (and can change +in the instance). For example, + +``` +probe type GenericProbeT = { + location = ««customize.system.^target.lb»» + script = { + mode = "continual" + path = "«probes.commonPath»/genericProbe.pl" + } +} +``` + +This defines a probe type called `GenericProbeT`. Instances of this probe type will +by default define a `location` and a `script` property. The `script` property will define +`mode` as `continual` and `path`. + +### Probe Instances + +Probe instances may indicate the probe type they are instances of. Otherwise, probes +are defined similarly to probe types. For example, + +``` +probe DimmerProbe -> GenericProbeT = { + alias = "dimmer" + script = { + argument = "get_dimmer" + } +} +``` + +This states that the `DimmerProbe` instance will get all the properties defined in `GenericProbeT` +in addition to the once defined in `GenericProbeT`. To define the same probe instance +without the probe type, you would need to specify: + +``` +probe DimmerProbe = { + location = ««customize.system.^target.lb»» + alias = "dimmer" + script = { + mode = "continual" + path = "«probes.commonPath»/genericProbe.pl" + argument = "get_dimmer" + } +} + +``` + +### Required Probe Fields + +| Property | Description | +| :-------- | :---------- | +| `alias` | The name that the probe as seen by the gauge. Gauges will put this in the `targetProbeType` field | +| `location` | The location where the probe is deployed (usually a property specified in `properties.rbw`) | +| `java = {...}` | Indicates the probe is implemented by Java class | +|    `class` | The class of the probe, implementing `org.sa.rainbow.translator.IProbe` or one of its subclasses. | +|    `period` | The reporting period of the probe (in ms)| +|   `args` | The arguments that will be passed to the constructor of the probe, in an array | +| `script = {...}` | Indicates the probe is implemented by a script | +|     `path` | The path of the script, which should exist on `location` | +|     `argument` | The argument(s) to pass to the script | + +For Java-based probes, the java class should be on the classpath. + +## Gauge Specification + +While probes provide information about the system, the intent of gauges is to abstract +this system information into model information, in the form of commands against the model +in Rainbow. There are three kinds of gauges in the Rainbow system: gauges that receive +information from probes; gauges that receive information from other gauges; and gauges +that generate information without either of these (for example, time-based gauges or +diagnostic gauges). + +In all cases, gauges must be specified in the `gauges.rbw` file located in the models +directory. This file contains both gauge types and gauge instances. Instances in Rainbow should create, +how they are attached to the model, and what (if any) probes they listen to. +For example, a gauge type could be defined for reporting the processing time property +for servers. The type would define what values (e.g., processing-time) are reported +by the gauge, how to set up the gauge initially (e.g., the period of reporting), and +how to configure the gauge when it is running (e.g., by changing the reporting units +from seconds to milliseconds). The instance specification specifies where a +particular gauge instance runs, what part of the model it is attached to, what probes +it is listening to, etc. + +Gauge specifications (types or instances) contain three main sections: + +1. Command and Model Information. This section specifies the model/model factory that +the gauge is associated with, and the commands that the gauge is intended to produce. +Gauges must produce at least one kind of command. + +2. Setup parameters. This sections defines the parameters that are used when constructing +the gauge, and are not intended to change after the gauge is created. This typically +includes information like the location of where the gauge is to be run, the class that +implements it, how often it should send a beacon to the master. + +3. Configuration Parameters: This section specifies attributes about the gauge that +may be changed later on through configuring the gauge. This might include information +like the probe being listened to, the sampling frequency, or any other information that +you may want to configure the gauge with. + +Gauges are only implemented using Java in the current framework. The `javaClass` specified +in the type must be on the classpath for the target system. To implement the gauge, +the following class hierarchy is provided by the Rainbow Infrastructure: + + - `AbstractGauge`: Implements basic Gauge management, such as heartbeat, + configuration, setting up, etc. Gauges that do not listen to any probes + should implement this class + + - `AbstractGaugeWithProbes extends AbstractGauge`: A gauge that handles the + targetProbeType and targetProbeList configuration parameters. + + - `RegularExpressionGauge extends AbstractGaugeWithProbes:` A gauge that processes + probe reports that match one or more regular expressions. The constructor for the + gauge should specify the regular expression patterns that are to be matched, and + the gauge provides a default runAction that calls "doMatch" when a one of the + expressions is matched. Extenders must implement this doMatch method to report the + value. + +### Gauge Types + +Gauge types specify + +1.the model factory that can be used to derive commands (specified +as either a RCL model factory imported into the file or as a Java class on the classpath). +2. The list of commands that instances will produce. In the type, these are given a +name that can be referred to in the gauge implementation, and a signature (which must +match the signature of the operation in the factory), with the target before the operation +name (if it exists). Consider the example: + +``` +gauge type DimmerGaugeT = { + model factory ««SWIM»» + command ^dimmer = LoadBalancerT.setDimmer(int) + setup = { + targetIP = "localhost" + beaconPeriod = 30000 + javaClass = org.sa.rainbow.translator.swim.gauges.SimpleGauge + } + config = { + samplingFrequency = 1500 + } + comment = "DimmerGaugeT measures and reports the dimmer value of the system" +} +``` + +This says that `DimmerGaugeT` is associated with the model factory `SWIM` and has one +command called `dimmer`. Notice that the command signature matches that in the factory: + +``` + command setDimmer(acme::SwimFam.LoadBalancerT target, int dimmer) +``` + +as the signature: `LoadBalancerT.setDimmer(int)`. + +There are then sections for setup and config that define possible parameters. These +are described in [Required Gauge Fields](#required-gauge-fields) + + +### Gauge Instances + +Like probes, gauge instances may refer to their type definitions. In this case, they +must specify a particular model (that has the same factory as declared in the type), +and list commands that are in the type. An error will be given if the instance does +not specity all commands or the signatures do not match. Consider the gauge: + +``` +gauge DimmerG0 -> DimmerGaugeT = { + model ««SwimSys»» + command dimmer = LB0.setDimmer($) + setup = { + targetIP = ««customize.system.^target.lb»» + } + config = { + targetProbe = ««DimmerProbe»» + } + comment = "DimmerG0 is associated with the component LB0 of the System, SwimSys, defined as an Acme model" +} +``` + +This gauge declares the type `DimmerGaugeT` and that it refers to the model instance +`SwimSys`. Note that this model instance has the factory `SWIM`. + +The command part refers to the command `dimmer` and has the definition of `LB0.setDimmer($)`. +`LB0` is defined in SwimSys as a component that has the type `LoadBalancerT`. In this +signature, real values can also be included (e.g., `LB0.setDimmer(1)` means the command +always sends the value `1` for the dimmer value). If a parameter is preceded is surround +by `$<...>` (as is the case here), this means that the gauge implementation is intended +to fill in this value - the type of this kind of parameter is not checked against the signature +until run time. + + +### Regular Expression Gauges + +One of the most common form of gauge is a RegularPatternGauge, which looks for matches +on probe output and uses regular expressions to match and pick up parts of the data. +Regular pattern gauges are now supported in RCL in the gauge type specification, and +RCL generate the Java class that implements this gauge. For example, consider that the +dimmer gauge should only process natural numbers, and so we only want to match data coming +from the probe that matches the pattern `[0-9]+`. We can do this by declaring in the +gauge type (eliding out unchanged details): + +``` +gauge type DimmerGaugeT = { + ... + command ^dimmer = "(?[0-9]+)" -> LoadBalancerT.setDimmer(int) + setup = { + ... + generatedClass = org.sa.rainbow.translator.swim.gauges.DimmerGauge + } + ... +} +``` + +The command specification part of the gauge type now specifies a regular expression +using named captured groups. It also specifies an attribute `generatedClass` that specifies +the class to generated when the project is built. + +Note that you may do pattern matching over multiple lines by using `(?s)` at the beginning of an expression to indicate that Pattern.DOTALL should be used. For example, if you want to match the following: + +``` +event: clock +value: 1234 +``` +You can indicated the pattern `(?s)event: clock.*time: (?

- - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.acmestudio.rainbow/resources/html/gauge-element.html b/ide/org.acmestudio.rainbow/resources/html/gauge-element.html index 44109d113..487519c78 100644 --- a/ide/org.acmestudio.rainbow/resources/html/gauge-element.html +++ b/ide/org.acmestudio.rainbow/resources/html/gauge-element.html @@ -1,725 +1,725 @@ - - - - -%PROPERTY gauges - - - - - -
-
- - + + + + +%PROPERTY gauges + + + + + +
+
+ + \ No newline at end of file diff --git a/ide/org.acmestudio.rainbow/resources/html/gauge.js b/ide/org.acmestudio.rainbow/resources/html/gauge.js index ef7ea5b65..6ce51b206 100644 --- a/ide/org.acmestudio.rainbow/resources/html/gauge.js +++ b/ide/org.acmestudio.rainbow/resources/html/gauge.js @@ -1,261 +1,261 @@ -function Gauge(placeholderName, configuration) -{ - this.placeholderName = placeholderName; - - var self = this; // for internal d3 functions - - this.configure = function(configuration) - { - this.config = configuration; - - this.config.size = this.config.size * 0.9; - - this.config.raduis = this.config.size * 0.97 / 2; - this.config.cx = this.config.size / 2; - this.config.cy = this.config.size / 2; - - this.config.min = undefined != configuration.min ? configuration.min : 0; - this.config.max = undefined != configuration.max ? configuration.max : 100; - this.config.range = this.config.max - this.config.min; - - this.config.majorTicks = configuration.majorTicks || 5; - this.config.minorTicks = configuration.minorTicks || 2; - - this.config.greenColor = configuration.greenColor || "#109618"; - this.config.yellowColor = configuration.yellowColor || "#FF9900"; - this.config.redColor = configuration.redColor || "#DC3912"; - - this.config.transitionDuration = configuration.transitionDuration || 500; - } - - this.render = function() - { - this.body = d3.select("#" + this.placeholderName) - .append("svg:svg") - .attr("class", "gauge") - .attr("width", this.config.size) - .attr("height", this.config.size); - - this.body.append("svg:circle") - .attr("cx", this.config.cx) - .attr("cy", this.config.cy) - .attr("r", this.config.raduis) - .style("fill", "#ccc") - .style("stroke", "#000") - .style("stroke-width", "0.5px"); - - this.body.append("svg:circle") - .attr("cx", this.config.cx) - .attr("cy", this.config.cy) - .attr("r", 0.9 * this.config.raduis) - .style("fill", "#fff") - .style("stroke", "#e0e0e0") - .style("stroke-width", "2px"); - - for (var index in this.config.greenZones) - { - this.drawBand(this.config.greenZones[index].from, this.config.greenZones[index].to, self.config.greenColor); - } - - for (var index in this.config.yellowZones) - { - this.drawBand(this.config.yellowZones[index].from, this.config.yellowZones[index].to, self.config.yellowColor); - } - - for (var index in this.config.redZones) - { - this.drawBand(this.config.redZones[index].from, this.config.redZones[index].to, self.config.redColor); - } - - if (undefined != this.config.label) - { - var fontSize = Math.round(this.config.size / 9); - this.body.append("svg:text") - .attr("x", this.config.cx) - .attr("y", this.config.cy / 2 + fontSize / 2) - .attr("dy", fontSize / 2) - .attr("text-anchor", "middle") - .text(this.config.label) - .style("font-size", fontSize + "px") - .style("fill", "#333") - .style("stroke-width", "0px"); - } - - var fontSize = Math.round(this.config.size / 16); - var majorDelta = this.config.range / (this.config.majorTicks - 1); - for (var major = this.config.min; major <= this.config.max; major += majorDelta) - { - var minorDelta = majorDelta / this.config.minorTicks; - for (var minor = major + minorDelta; minor < Math.min(major + majorDelta, this.config.max); minor += minorDelta) - { - var point1 = this.valueToPoint(minor, 0.75); - var point2 = this.valueToPoint(minor, 0.85); - - this.body.append("svg:line") - .attr("x1", point1.x) - .attr("y1", point1.y) - .attr("x2", point2.x) - .attr("y2", point2.y) - .style("stroke", "#666") - .style("stroke-width", "1px"); - } - - var point1 = this.valueToPoint(major, 0.7); - var point2 = this.valueToPoint(major, 0.85); - - this.body.append("svg:line") - .attr("x1", point1.x) - .attr("y1", point1.y) - .attr("x2", point2.x) - .attr("y2", point2.y) - .style("stroke", "#333") - .style("stroke-width", "2px"); - - if (major == this.config.min || major == this.config.max) - { - var point = this.valueToPoint(major, 0.63); - - this.body.append("svg:text") - .attr("x", point.x) - .attr("y", point.y) - .attr("dy", fontSize / 3) - .attr("text-anchor", major == this.config.min ? "start" : "end") - .text(major) - .style("font-size", fontSize + "px") - .style("fill", "#333") - .style("stroke-width", "0px"); - } - } - - var pointerContainer = this.body.append("svg:g").attr("class", "pointerContainer"); - - var midValue = (this.config.min + this.config.max) / 2; - - var pointerPath = this.buildPointerPath(midValue); - - var pointerLine = d3.svg.line() - .x(function(d) { return d.x }) - .y(function(d) { return d.y }) - .interpolate("basis"); - - pointerContainer.selectAll("path") - .data([pointerPath]) - .enter() - .append("svg:path") - .attr("d", pointerLine) - .style("fill", "#dc3912") - .style("stroke", "#c63310") - .style("fill-opacity", 0.7) - - pointerContainer.append("svg:circle") - .attr("cx", this.config.cx) - .attr("cy", this.config.cy) - .attr("r", 0.12 * this.config.raduis) - .style("fill", "#4684EE") - .style("stroke", "#666") - .style("opacity", 1); - - var fontSize = Math.round(this.config.size / 10); - pointerContainer.selectAll("text") - .data([midValue]) - .enter() - .append("svg:text") - .attr("x", this.config.cx) - .attr("y", this.config.size - this.config.cy / 4 - fontSize) - .attr("dy", fontSize / 2) - .attr("text-anchor", "middle") - .style("font-size", fontSize + "px") - .style("fill", "#000") - .style("stroke-width", "0px"); - - this.redraw(this.config.min, 0); - } - - this.buildPointerPath = function(value) - { - var delta = this.config.range / 13; - - var head = valueToPoint(value, 0.85); - var head1 = valueToPoint(value - delta, 0.12); - var head2 = valueToPoint(value + delta, 0.12); - - var tailValue = value - (this.config.range * (1/(270/360)) / 2); - var tail = valueToPoint(tailValue, 0.28); - var tail1 = valueToPoint(tailValue - delta, 0.12); - var tail2 = valueToPoint(tailValue + delta, 0.12); - - return [head, head1, tail2, tail, tail1, head2, head]; - - function valueToPoint(value, factor) - { - var point = self.valueToPoint(value, factor); - point.x -= self.config.cx; - point.y -= self.config.cy; - return point; - } - } - - this.drawBand = function(start, end, color) - { - if (0 >= end - start) return; - - this.body.append("svg:path") - .style("fill", color) - .attr("d", d3.svg.arc() - .startAngle(this.valueToRadians(start)) - .endAngle(this.valueToRadians(end)) - .innerRadius(0.65 * this.config.raduis) - .outerRadius(0.85 * this.config.raduis)) - .attr("transform", function() { return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(270)" }); - } - - this.redraw = function(value, transitionDuration) - { - var pointerContainer = this.body.select(".pointerContainer"); - - pointerContainer.selectAll("text").text(Math.round(value)); - - var pointer = pointerContainer.selectAll("path"); - pointer.transition() - .duration(undefined != transitionDuration ? transitionDuration : this.config.transitionDuration) - //.delay(0) - //.ease("linear") - //.attr("transform", function(d) - .attrTween("transform", function() - { - var pointerValue = value; - if (value > self.config.max) pointerValue = self.config.max + 0.02*self.config.range; - else if (value < self.config.min) pointerValue = self.config.min - 0.02*self.config.range; - var targetRotation = (self.valueToDegrees(pointerValue) - 90); - var currentRotation = self._currentRotation || targetRotation; - self._currentRotation = targetRotation; - - return function(step) - { - var rotation = currentRotation + (targetRotation-currentRotation)*step; - return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(" + rotation + ")"; - } - }); - } - - this.valueToDegrees = function(value) - { - // thanks @closealert - //return value / this.config.range * 270 - 45; - return value / this.config.range * 270 - (this.config.min / this.config.range * 270 + 45); - } - - this.valueToRadians = function(value) - { - return this.valueToDegrees(value) * Math.PI / 180; - } - - this.valueToPoint = function(value, factor) - { - return { x: this.config.cx - this.config.raduis * factor * Math.cos(this.valueToRadians(value)), - y: this.config.cy - this.config.raduis * factor * Math.sin(this.valueToRadians(value)) }; - } - - // initialization - this.configure(configuration); +function Gauge(placeholderName, configuration) +{ + this.placeholderName = placeholderName; + + var self = this; // for internal d3 functions + + this.configure = function(configuration) + { + this.config = configuration; + + this.config.size = this.config.size * 0.9; + + this.config.raduis = this.config.size * 0.97 / 2; + this.config.cx = this.config.size / 2; + this.config.cy = this.config.size / 2; + + this.config.min = undefined != configuration.min ? configuration.min : 0; + this.config.max = undefined != configuration.max ? configuration.max : 100; + this.config.range = this.config.max - this.config.min; + + this.config.majorTicks = configuration.majorTicks || 5; + this.config.minorTicks = configuration.minorTicks || 2; + + this.config.greenColor = configuration.greenColor || "#109618"; + this.config.yellowColor = configuration.yellowColor || "#FF9900"; + this.config.redColor = configuration.redColor || "#DC3912"; + + this.config.transitionDuration = configuration.transitionDuration || 500; + } + + this.render = function() + { + this.body = d3.select("#" + this.placeholderName) + .append("svg:svg") + .attr("class", "gauge") + .attr("width", this.config.size) + .attr("height", this.config.size); + + this.body.append("svg:circle") + .attr("cx", this.config.cx) + .attr("cy", this.config.cy) + .attr("r", this.config.raduis) + .style("fill", "#ccc") + .style("stroke", "#000") + .style("stroke-width", "0.5px"); + + this.body.append("svg:circle") + .attr("cx", this.config.cx) + .attr("cy", this.config.cy) + .attr("r", 0.9 * this.config.raduis) + .style("fill", "#fff") + .style("stroke", "#e0e0e0") + .style("stroke-width", "2px"); + + for (var index in this.config.greenZones) + { + this.drawBand(this.config.greenZones[index].from, this.config.greenZones[index].to, self.config.greenColor); + } + + for (var index in this.config.yellowZones) + { + this.drawBand(this.config.yellowZones[index].from, this.config.yellowZones[index].to, self.config.yellowColor); + } + + for (var index in this.config.redZones) + { + this.drawBand(this.config.redZones[index].from, this.config.redZones[index].to, self.config.redColor); + } + + if (undefined != this.config.label) + { + var fontSize = Math.round(this.config.size / 9); + this.body.append("svg:text") + .attr("x", this.config.cx) + .attr("y", this.config.cy / 2 + fontSize / 2) + .attr("dy", fontSize / 2) + .attr("text-anchor", "middle") + .text(this.config.label) + .style("font-size", fontSize + "px") + .style("fill", "#333") + .style("stroke-width", "0px"); + } + + var fontSize = Math.round(this.config.size / 16); + var majorDelta = this.config.range / (this.config.majorTicks - 1); + for (var major = this.config.min; major <= this.config.max; major += majorDelta) + { + var minorDelta = majorDelta / this.config.minorTicks; + for (var minor = major + minorDelta; minor < Math.min(major + majorDelta, this.config.max); minor += minorDelta) + { + var point1 = this.valueToPoint(minor, 0.75); + var point2 = this.valueToPoint(minor, 0.85); + + this.body.append("svg:line") + .attr("x1", point1.x) + .attr("y1", point1.y) + .attr("x2", point2.x) + .attr("y2", point2.y) + .style("stroke", "#666") + .style("stroke-width", "1px"); + } + + var point1 = this.valueToPoint(major, 0.7); + var point2 = this.valueToPoint(major, 0.85); + + this.body.append("svg:line") + .attr("x1", point1.x) + .attr("y1", point1.y) + .attr("x2", point2.x) + .attr("y2", point2.y) + .style("stroke", "#333") + .style("stroke-width", "2px"); + + if (major == this.config.min || major == this.config.max) + { + var point = this.valueToPoint(major, 0.63); + + this.body.append("svg:text") + .attr("x", point.x) + .attr("y", point.y) + .attr("dy", fontSize / 3) + .attr("text-anchor", major == this.config.min ? "start" : "end") + .text(major) + .style("font-size", fontSize + "px") + .style("fill", "#333") + .style("stroke-width", "0px"); + } + } + + var pointerContainer = this.body.append("svg:g").attr("class", "pointerContainer"); + + var midValue = (this.config.min + this.config.max) / 2; + + var pointerPath = this.buildPointerPath(midValue); + + var pointerLine = d3.svg.line() + .x(function(d) { return d.x }) + .y(function(d) { return d.y }) + .interpolate("basis"); + + pointerContainer.selectAll("path") + .data([pointerPath]) + .enter() + .append("svg:path") + .attr("d", pointerLine) + .style("fill", "#dc3912") + .style("stroke", "#c63310") + .style("fill-opacity", 0.7) + + pointerContainer.append("svg:circle") + .attr("cx", this.config.cx) + .attr("cy", this.config.cy) + .attr("r", 0.12 * this.config.raduis) + .style("fill", "#4684EE") + .style("stroke", "#666") + .style("opacity", 1); + + var fontSize = Math.round(this.config.size / 10); + pointerContainer.selectAll("text") + .data([midValue]) + .enter() + .append("svg:text") + .attr("x", this.config.cx) + .attr("y", this.config.size - this.config.cy / 4 - fontSize) + .attr("dy", fontSize / 2) + .attr("text-anchor", "middle") + .style("font-size", fontSize + "px") + .style("fill", "#000") + .style("stroke-width", "0px"); + + this.redraw(this.config.min, 0); + } + + this.buildPointerPath = function(value) + { + var delta = this.config.range / 13; + + var head = valueToPoint(value, 0.85); + var head1 = valueToPoint(value - delta, 0.12); + var head2 = valueToPoint(value + delta, 0.12); + + var tailValue = value - (this.config.range * (1/(270/360)) / 2); + var tail = valueToPoint(tailValue, 0.28); + var tail1 = valueToPoint(tailValue - delta, 0.12); + var tail2 = valueToPoint(tailValue + delta, 0.12); + + return [head, head1, tail2, tail, tail1, head2, head]; + + function valueToPoint(value, factor) + { + var point = self.valueToPoint(value, factor); + point.x -= self.config.cx; + point.y -= self.config.cy; + return point; + } + } + + this.drawBand = function(start, end, color) + { + if (0 >= end - start) return; + + this.body.append("svg:path") + .style("fill", color) + .attr("d", d3.svg.arc() + .startAngle(this.valueToRadians(start)) + .endAngle(this.valueToRadians(end)) + .innerRadius(0.65 * this.config.raduis) + .outerRadius(0.85 * this.config.raduis)) + .attr("transform", function() { return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(270)" }); + } + + this.redraw = function(value, transitionDuration) + { + var pointerContainer = this.body.select(".pointerContainer"); + + pointerContainer.selectAll("text").text(Math.round(value)); + + var pointer = pointerContainer.selectAll("path"); + pointer.transition() + .duration(undefined != transitionDuration ? transitionDuration : this.config.transitionDuration) + //.delay(0) + //.ease("linear") + //.attr("transform", function(d) + .attrTween("transform", function() + { + var pointerValue = value; + if (value > self.config.max) pointerValue = self.config.max + 0.02*self.config.range; + else if (value < self.config.min) pointerValue = self.config.min - 0.02*self.config.range; + var targetRotation = (self.valueToDegrees(pointerValue) - 90); + var currentRotation = self._currentRotation || targetRotation; + self._currentRotation = targetRotation; + + return function(step) + { + var rotation = currentRotation + (targetRotation-currentRotation)*step; + return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(" + rotation + ")"; + } + }); + } + + this.valueToDegrees = function(value) + { + // thanks @closealert + //return value / this.config.range * 270 - 45; + return value / this.config.range * 270 - (this.config.min / this.config.range * 270 + 45); + } + + this.valueToRadians = function(value) + { + return this.valueToDegrees(value) * Math.PI / 180; + } + + this.valueToPoint = function(value, factor) + { + return { x: this.config.cx - this.config.raduis * factor * Math.cos(this.valueToRadians(value)), + y: this.config.cy - this.config.raduis * factor * Math.sin(this.valueToRadians(value)) }; + } + + // initialization + this.configure(configuration); } \ No newline at end of file diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/Rainbow.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/Rainbow.java index a2bc6d775..9b8fee8b4 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/Rainbow.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/Rainbow.java @@ -1,80 +1,80 @@ -package org.acmestudio.rainbow; - -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.net.URL; - -import org.acmestudio.rainbow.model.events.RainbowModelEventListener; -import org.eclipse.core.runtime.FileLocator; -import org.eclipse.core.runtime.Platform; -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; - -/** - * The activator class controls the plug-in life cycle - */ -public class Rainbow extends AbstractUIPlugin { - - // The plug-in ID - public static final String PLUGIN_ID = "org.acmestudio.rainbow"; //$NON-NLS-1$ - - // The shared instance - private static Rainbow plugin; - - public static RainbowModelEventListener s_rainbowListener; - - /** - * The constructor - */ - public Rainbow() { - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) - */ - public void start(BundleContext context) throws Exception { - super.start(context); - Bundle bundle = Platform.getBundle("org.mozilla.xulrunner"); - if (bundle != null) { - URL resourceUrl = bundle.getResource("xulrunner"); - if (resourceUrl != null) { - try { - URL fileUrl = FileLocator.toFileURL(resourceUrl); - File file = new File (fileUrl.toURI ()); - System.setProperty("org.eclipse.swt.browser.XULRunnerPath", file.getAbsolutePath()); - } - catch (IOException | URISyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - Rainbow.plugin = this; - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) throws Exception { - Rainbow.plugin = null; - super.stop(context); - } - - /** - * Returns the shared instance - * - * @return the shared instance - */ - public static Rainbow getDefault() { - return Rainbow.plugin; - } - - public static RainbowModelEventListener getRainbowListener () { - return Rainbow.s_rainbowListener; - } - -} +package org.acmestudio.rainbow; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; + +import org.acmestudio.rainbow.model.events.RainbowModelEventListener; +import org.eclipse.core.runtime.FileLocator; +import org.eclipse.core.runtime.Platform; +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class Rainbow extends AbstractUIPlugin { + + // The plug-in ID + public static final String PLUGIN_ID = "org.acmestudio.rainbow"; //$NON-NLS-1$ + + // The shared instance + private static Rainbow plugin; + + public static RainbowModelEventListener s_rainbowListener; + + /** + * The constructor + */ + public Rainbow() { + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) + */ + public void start(BundleContext context) throws Exception { + super.start(context); + Bundle bundle = Platform.getBundle("org.mozilla.xulrunner"); + if (bundle != null) { + URL resourceUrl = bundle.getResource("xulrunner"); + if (resourceUrl != null) { + try { + URL fileUrl = FileLocator.toFileURL(resourceUrl); + File file = new File (fileUrl.toURI ()); + System.setProperty("org.eclipse.swt.browser.XULRunnerPath", file.getAbsolutePath()); + } + catch (IOException | URISyntaxException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + Rainbow.plugin = this; + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) + */ + public void stop(BundleContext context) throws Exception { + Rainbow.plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Rainbow getDefault() { + return Rainbow.plugin; + } + + public static RainbowModelEventListener getRainbowListener () { + return Rainbow.s_rainbowListener; + } + +} diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/handlers/RainbowDisconnectionHandler.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/handlers/RainbowDisconnectionHandler.java index 00ca5ad35..3bb67ccf2 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/handlers/RainbowDisconnectionHandler.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/handlers/RainbowDisconnectionHandler.java @@ -1,21 +1,21 @@ -package org.acmestudio.rainbow.handlers; -import org.acmestudio.rainbow.Rainbow; -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; - -public class RainbowDisconnectionHandler extends AbstractHandler { - - @Override - public Object execute (ExecutionEvent event) throws ExecutionException { - return null; - // Rainbow.getRainbowListener().disconnect(); - } - - - @Override - public boolean isEnabled () { - return super.isEnabled() && Rainbow.getRainbowListener() != null; - } - -} +package org.acmestudio.rainbow.handlers; +import org.acmestudio.rainbow.Rainbow; +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; + +public class RainbowDisconnectionHandler extends AbstractHandler { + + @Override + public Object execute (ExecutionEvent event) throws ExecutionException { + return null; + // Rainbow.getRainbowListener().disconnect(); + } + + + @Override + public boolean isEnabled () { + return super.isEnabled() && Rainbow.getRainbowListener() != null; + } + +} diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/AcmeEventDeserializer.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/AcmeEventDeserializer.java index f984c5dd7..d91264ab8 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/AcmeEventDeserializer.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/AcmeEventDeserializer.java @@ -1,351 +1,351 @@ -package org.acmestudio.rainbow.model.events; - -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import org.acmestudio.acme.core.resource.RegionManager; -import org.acmestudio.acme.element.IAcmeComponent; -import org.acmestudio.acme.element.IAcmeConnector; -import org.acmestudio.acme.element.IAcmeGroup; -import org.acmestudio.acme.element.IAcmePort; -import org.acmestudio.acme.element.IAcmeRole; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.command.IAcmeComponentCreateCommand; -import org.acmestudio.acme.model.command.IAcmeConnectorCreateCommand; -import org.acmestudio.acme.model.event.AcmeModelEventType; -import org.acmestudio.eclipse.core.util.LanguagePackHelper; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; -import org.sa.rainbow.core.util.Pair; -import org.sa.rainbow.model.acme.AcmeModelOperation; - -public class AcmeEventDeserializer { - - public IAcmeCommand deserialize (List events, IAcmeSystem model) throws RainbowDeserializationException { - - List>> commands = new LinkedList>>(); - - for (IRainbowMessage msg : events) { - deserialize(msg, model, commands); - } - - List> cmds = new LinkedList>(); - for (Pair> p : commands) { - cmds.add(p.secondValue()); - } - return model.getCommandFactory().compoundCommand(cmds); - } - - // Takes an event and turns it into a command. Currently, this does not use the operators for Rainbow (like addServer), but uses - // the raw Acme commands that are reported by Rainbow as sub events of the operators - public IAcmeCommand deserialize (IRainbowMessage event, IAcmeSystem model) throws RainbowDeserializationException { - List>> commands = new LinkedList<>(); - deserialize(event, model, commands); - return commands.get(0).secondValue(); - } - - private void deserialize (IRainbowMessage msg, IAcmeSystem model, List>> commands) - throws RainbowDeserializationException { - String eventType = (String) msg.getProperty(IRainbowMessageFactory.EVENT_TYPE_PROP); - AcmeModelEventType et = AcmeModelEventType.valueOf(eventType); - switch (et) { - case ADD_ATTACHMENT: - case REMOVE_ATTACHMENT: - deserializeAcmeAttachmentEvent(msg, model, et, commands); - break; - /* - * case ADD_BINDING: case REMOVE_BINDING: return - * deserializeAcmeBindingEvent(msg, model, et); - */ - case ADD_COMPONENT: - case REMOVE_COMPONENT: - deserializeAcmeComponentEvent(msg, model, et, commands); - break; - case ADD_CONNECTOR: - case REMOVE_CONNECTOR: - deserializeAcmeConnectorEvent(msg, model, et, commands); - break; - case ADD_GROUP: - case REMOVE_GROUP: - deserializeAcmeGroupEvent(msg, model, et, commands); - break; - /* - * case ADD_MEMBER: case REMOVE_MEMBER: - */ - case ADD_PORT: - case REMOVE_PORT: - deserializeAcmePortEvent(msg, model, et, commands); - break; - case ADD_ROLE: - case REMOVE_ROLE: - deserializeAcmeRoleEvent(msg, model, et, commands); - break; - case ADD_PROPERTY: - case REMOVE_PROPERTY: - case SET_PROPERTY_VALUE: - deserializeAcmePropertyEvent(msg, model, et, commands); - break; - default: - throw new RainbowDeserializationException(MessageFormat.format( - "Do not know how to deserialize an event of type ''{0}''.", et.name())); - } - } - - private void deserializeAcmePropertyEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, - List>> commands) - throws RainbowDeserializationException { - String propName = (String) msg.getProperty(AcmeModelOperation.PROPERTY_PROP); - switch (et) { - case SET_PROPERTY_VALUE: - IAcmeProperty prop = this. resolveInModel(propName, model, IAcmeProperty.class); - String value = (String) msg.getProperty(AcmeModelOperation.VALUE_PROP); - try { - IAcmePropertyValue val = LanguagePackHelper.defaultLanguageHelper().propertyValueFromString( - value, new RegionManager()); - commands.add(new Pair>(propName, model.getCommandFactory().propertyValueSetCommand(prop, - val))); - return; - } - catch (Exception e) { - throw new RainbowDeserializationException(MessageFormat.format("Could not convert ''{0}'' to a property value.", - value)); - } - } - throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", - et.name())); - } - - private void deserializeAcmeRoleEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, - List>> commands) - throws RainbowDeserializationException { - String roleName = (String) msg.getProperty(AcmeModelOperation.ROLE_PROP); - String connName = (String) msg.getProperty(AcmeModelOperation.CONNECTOR_PROP); - - model = getSystemPropertyIfExists(msg, model); - if (connName == null) { - connName = roleName.substring(0, roleName.lastIndexOf(".") - 1); - } - - switch (et) { - case ADD_ROLE: - IAcmeConnector conn = this. resolveInModel(connName, model, IAcmeConnector.class); - List dts = getTypeList(msg, AcmeModelOperation.DECLARED_TYPES_PROP); - List its = getTypeList(msg, AcmeModelOperation.INSTANTIATED_TYPES_PROP); - roleName = roleName.substring(roleName.lastIndexOf(".") + 1); - if (conn != null) { - commands.add(new Pair>(roleName, model.getCommandFactory().roleCreateCommand(conn, - roleName, dts, its))); - return; - } - else { - IAcmeConnectorCreateCommand cmd = this. findKeyedCommand(connName, commands, - IAcmeConnectorCreateCommand.class); - if (cmd != null) { - commands.add(new Pair>(roleName, model.getCommandFactory().roleCreateCommand(cmd, - roleName, dts, its))); - return; - } - else { - throw new RainbowDeserializationException(MessageFormat.format( - "Could not find a connector or a command associated with the connector ''{0}''.", connName)); - } - } - case REMOVE_ROLE: - IAcmeRole role = this. resolveInModel(roleName, model, IAcmeRole.class); - commands.add(new Pair>(roleName, model.getCommandFactory().roleDeleteCommand(role))); - return; - } - throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", - et.name())); - } - - - private T findKeyedCommand (String name, List>> commands, Class cls) { - T t = null; - for (int i = commands.size() - 1; i >= 0 && t == null; i--) { - Pair> pair = commands.get(i); - if (pair.firstValue().equals(name) && pair.secondValue().getClass().isAssignableFrom(cls)) { - t = (T) pair.secondValue(); - } - } - return t; - } - - private void deserializeAcmePortEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, - List>> commands) - throws RainbowDeserializationException { - String portName = (String) msg.getProperty(AcmeModelOperation.PORT_PROP); - String compName = (String) msg.getProperty(AcmeModelOperation.COMPONENT_PROP); - - model = getSystemPropertyIfExists(msg, model); - IAcmeComponent comp = null; - if (compName == null) { - compName = portName.substring(0, portName.lastIndexOf(".") - 1); - } - comp = this. resolveInModel(compName, model, IAcmeComponent.class); - - switch (et) { - case ADD_PORT: - List dts = getTypeList(msg, AcmeModelOperation.DECLARED_TYPES_PROP); - List its = getTypeList(msg, AcmeModelOperation.INSTANTIATED_TYPES_PROP); - portName = portName.substring(portName.lastIndexOf(".") + 1); - if (comp != null) { - commands.add(new Pair>(portName, model.getCommandFactory().portCreateCommand(comp, - portName, dts, its))); - return; - } - else { - IAcmeComponentCreateCommand cmd = this. findKeyedCommand(compName, commands, - IAcmeComponentCreateCommand.class); - if (cmd != null) { - commands.add(new Pair>(portName, model.getCommandFactory().portCreateCommand(cmd, - portName, dts, its))); - return; - } - else { - throw new RainbowDeserializationException(MessageFormat.format( - "Could not find a connector or a command associated with the connector ''{0}''.", compName)); - } - } - case REMOVE_PORT: - IAcmePort port = this. resolveInModel(portName, model, IAcmePort.class); - commands.add(new Pair>(portName, model.getCommandFactory().portDeleteCommand(port))); - return; - } - throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", - et.name())); - } - - private void deserializeAcmeGroupEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, - List>> commands) - throws RainbowDeserializationException { - String groupName = (String) msg.getProperty(AcmeModelOperation.GROUP_PROP); - - model = getSystemPropertyIfExists(msg, model); - - switch (et) { - case ADD_GROUP: - List dts = getTypeList(msg, AcmeModelOperation.DECLARED_TYPES_PROP); - List its = getTypeList(msg, AcmeModelOperation.INSTANTIATED_TYPES_PROP); - commands.add(new Pair>(groupName, model.getCommandFactory().groupCreateCommand(model, - groupName, dts, its))); - return; - case REMOVE_GROUP: - IAcmeGroup comp = this. resolveInModel(groupName, model, IAcmeGroup.class); - commands.add(new Pair>(groupName, model.getCommandFactory().groupDeleteCommand(comp))); - return; - } - throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", - et.name())); - } - - private void deserializeAcmeConnectorEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, - List>> commands) - throws RainbowDeserializationException { - String connName = (String) msg.getProperty(AcmeModelOperation.CONNECTOR_PROP); - - model = getSystemPropertyIfExists(msg, model); - - switch (et) { - case ADD_CONNECTOR: - List dts = getTypeList(msg, AcmeModelOperation.DECLARED_TYPES_PROP); - List its = getTypeList(msg, AcmeModelOperation.INSTANTIATED_TYPES_PROP); - commands.add(new Pair>(connName, model.getCommandFactory().connectorCreateCommand(model, - connName, dts, its))); - return; - case REMOVE_CONNECTOR: - IAcmeConnector comp = this. resolveInModel(connName, model, IAcmeConnector.class); - commands.add(new Pair>(connName, model.getCommandFactory().connectorDeleteCommand(comp))); - return; - } - throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", - et.name())); - } - - private void deserializeAcmeComponentEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, - List>> commands) - throws RainbowDeserializationException { - String compName = (String) msg.getProperty(AcmeModelOperation.COMPONENT_PROP); - - model = getSystemPropertyIfExists(msg, model); - - switch (et) { - case ADD_COMPONENT: - List dts = getTypeList(msg, AcmeModelOperation.DECLARED_TYPES_PROP); - List its = getTypeList(msg, AcmeModelOperation.INSTANTIATED_TYPES_PROP); - commands.add(new Pair>(compName, model.getCommandFactory().componentCreateCommand(model, - compName, dts, its))); - return; - case REMOVE_COMPONENT: - IAcmeComponent comp = this. resolveInModel(compName, model, IAcmeComponent.class); - commands.add(new Pair>(compName, model.getCommandFactory().componentDeleteCommand(comp))); - return; - } - throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", - et.name())); - - } - - protected List getTypeList (IRainbowMessage msg, String prop) { - String types = (String) msg.getProperty(prop); - List dts = Collections. emptyList(); - if (types != null && !types.isEmpty()) { - dts = Arrays.asList(types.split(",")); - } - return dts; - } - - private void deserializeAcmeAttachmentEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, - List>> commands) throws RainbowDeserializationException { - String portName = (String )msg.getProperty (AcmeModelOperation.PORT_PROP); - String roleName = (String )msg.getProperty(AcmeModelOperation.ROLE_PROP); - model = getSystemPropertyIfExists(msg, model); - - switch (et) { - case ADD_ATTACHMENT: - commands.add(new Pair>(portName + " to " + roleName, model.getCommandFactory() - .attachmentCreateCommand(model, portName, roleName))); - return; - case REMOVE_ATTACHMENT: - IAcmePort p = this. resolveInModel(portName, model, IAcmePort.class); - IAcmeRole r = this. resolveInModel(roleName, model, IAcmeRole.class); - commands.add(new Pair>(portName + " to " + roleName, model.getCommandFactory() - .attachmentDeleteCommand(model.getAttachment(p, r)))); - return; - } - throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", - et.name())); - } - - protected IAcmeSystem getSystemPropertyIfExists (IRainbowMessage msg, IAcmeSystem model) throws RainbowDeserializationException { - String systemName = (String )msg.getProperty(AcmeModelOperation.SYSTEM_PROP); - - if (systemName != null && !model.getName().equals(systemName)) { - Object o = model.lookupName(systemName); - if (o instanceof IAcmeSystem) { - model = (IAcmeSystem )o; - } - else { - throw new RainbowDeserializationException (MessageFormat.format("The system ''{0}'' could not be found in {1}", systemName, model.getName())); - } - } - return model; - } - - private T resolveInModel (String qualifiedName, IAcmeSystem model, Class cls) throws RainbowDeserializationException { - Object o = model.getContext().getModel().lookupName(qualifiedName); - if (o == null || !cls.isAssignableFrom(o.getClass())) { - - throw new RainbowDeserializationException(MessageFormat.format("Could not resolve ''{0}'' as a {1} in {2}", qualifiedName, - cls.getSimpleName(), model.getQualifiedName())); - } - T t = (T) o; - return t; - } -} +package org.acmestudio.rainbow.model.events; + +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import org.acmestudio.acme.core.resource.RegionManager; +import org.acmestudio.acme.element.IAcmeComponent; +import org.acmestudio.acme.element.IAcmeConnector; +import org.acmestudio.acme.element.IAcmeGroup; +import org.acmestudio.acme.element.IAcmePort; +import org.acmestudio.acme.element.IAcmeRole; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.command.IAcmeComponentCreateCommand; +import org.acmestudio.acme.model.command.IAcmeConnectorCreateCommand; +import org.acmestudio.acme.model.event.AcmeModelEventType; +import org.acmestudio.eclipse.core.util.LanguagePackHelper; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; +import org.sa.rainbow.core.util.Pair; +import org.sa.rainbow.model.acme.AcmeModelOperation; + +public class AcmeEventDeserializer { + + public IAcmeCommand deserialize (List events, IAcmeSystem model) throws RainbowDeserializationException { + + List>> commands = new LinkedList>>(); + + for (IRainbowMessage msg : events) { + deserialize(msg, model, commands); + } + + List> cmds = new LinkedList>(); + for (Pair> p : commands) { + cmds.add(p.secondValue()); + } + return model.getCommandFactory().compoundCommand(cmds); + } + + // Takes an event and turns it into a command. Currently, this does not use the operators for Rainbow (like addServer), but uses + // the raw Acme commands that are reported by Rainbow as sub events of the operators + public IAcmeCommand deserialize (IRainbowMessage event, IAcmeSystem model) throws RainbowDeserializationException { + List>> commands = new LinkedList<>(); + deserialize(event, model, commands); + return commands.get(0).secondValue(); + } + + private void deserialize (IRainbowMessage msg, IAcmeSystem model, List>> commands) + throws RainbowDeserializationException { + String eventType = (String) msg.getProperty(IRainbowMessageFactory.EVENT_TYPE_PROP); + AcmeModelEventType et = AcmeModelEventType.valueOf(eventType); + switch (et) { + case ADD_ATTACHMENT: + case REMOVE_ATTACHMENT: + deserializeAcmeAttachmentEvent(msg, model, et, commands); + break; + /* + * case ADD_BINDING: case REMOVE_BINDING: return + * deserializeAcmeBindingEvent(msg, model, et); + */ + case ADD_COMPONENT: + case REMOVE_COMPONENT: + deserializeAcmeComponentEvent(msg, model, et, commands); + break; + case ADD_CONNECTOR: + case REMOVE_CONNECTOR: + deserializeAcmeConnectorEvent(msg, model, et, commands); + break; + case ADD_GROUP: + case REMOVE_GROUP: + deserializeAcmeGroupEvent(msg, model, et, commands); + break; + /* + * case ADD_MEMBER: case REMOVE_MEMBER: + */ + case ADD_PORT: + case REMOVE_PORT: + deserializeAcmePortEvent(msg, model, et, commands); + break; + case ADD_ROLE: + case REMOVE_ROLE: + deserializeAcmeRoleEvent(msg, model, et, commands); + break; + case ADD_PROPERTY: + case REMOVE_PROPERTY: + case SET_PROPERTY_VALUE: + deserializeAcmePropertyEvent(msg, model, et, commands); + break; + default: + throw new RainbowDeserializationException(MessageFormat.format( + "Do not know how to deserialize an event of type ''{0}''.", et.name())); + } + } + + private void deserializeAcmePropertyEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, + List>> commands) + throws RainbowDeserializationException { + String propName = (String) msg.getProperty(AcmeModelOperation.PROPERTY_PROP); + switch (et) { + case SET_PROPERTY_VALUE: + IAcmeProperty prop = this. resolveInModel(propName, model, IAcmeProperty.class); + String value = (String) msg.getProperty(AcmeModelOperation.VALUE_PROP); + try { + IAcmePropertyValue val = LanguagePackHelper.defaultLanguageHelper().propertyValueFromString( + value, new RegionManager()); + commands.add(new Pair>(propName, model.getCommandFactory().propertyValueSetCommand(prop, + val))); + return; + } + catch (Exception e) { + throw new RainbowDeserializationException(MessageFormat.format("Could not convert ''{0}'' to a property value.", + value)); + } + } + throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", + et.name())); + } + + private void deserializeAcmeRoleEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, + List>> commands) + throws RainbowDeserializationException { + String roleName = (String) msg.getProperty(AcmeModelOperation.ROLE_PROP); + String connName = (String) msg.getProperty(AcmeModelOperation.CONNECTOR_PROP); + + model = getSystemPropertyIfExists(msg, model); + if (connName == null) { + connName = roleName.substring(0, roleName.lastIndexOf(".") - 1); + } + + switch (et) { + case ADD_ROLE: + IAcmeConnector conn = this. resolveInModel(connName, model, IAcmeConnector.class); + List dts = getTypeList(msg, AcmeModelOperation.DECLARED_TYPES_PROP); + List its = getTypeList(msg, AcmeModelOperation.INSTANTIATED_TYPES_PROP); + roleName = roleName.substring(roleName.lastIndexOf(".") + 1); + if (conn != null) { + commands.add(new Pair>(roleName, model.getCommandFactory().roleCreateCommand(conn, + roleName, dts, its))); + return; + } + else { + IAcmeConnectorCreateCommand cmd = this. findKeyedCommand(connName, commands, + IAcmeConnectorCreateCommand.class); + if (cmd != null) { + commands.add(new Pair>(roleName, model.getCommandFactory().roleCreateCommand(cmd, + roleName, dts, its))); + return; + } + else { + throw new RainbowDeserializationException(MessageFormat.format( + "Could not find a connector or a command associated with the connector ''{0}''.", connName)); + } + } + case REMOVE_ROLE: + IAcmeRole role = this. resolveInModel(roleName, model, IAcmeRole.class); + commands.add(new Pair>(roleName, model.getCommandFactory().roleDeleteCommand(role))); + return; + } + throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", + et.name())); + } + + + private T findKeyedCommand (String name, List>> commands, Class cls) { + T t = null; + for (int i = commands.size() - 1; i >= 0 && t == null; i--) { + Pair> pair = commands.get(i); + if (pair.firstValue().equals(name) && pair.secondValue().getClass().isAssignableFrom(cls)) { + t = (T) pair.secondValue(); + } + } + return t; + } + + private void deserializeAcmePortEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, + List>> commands) + throws RainbowDeserializationException { + String portName = (String) msg.getProperty(AcmeModelOperation.PORT_PROP); + String compName = (String) msg.getProperty(AcmeModelOperation.COMPONENT_PROP); + + model = getSystemPropertyIfExists(msg, model); + IAcmeComponent comp = null; + if (compName == null) { + compName = portName.substring(0, portName.lastIndexOf(".") - 1); + } + comp = this. resolveInModel(compName, model, IAcmeComponent.class); + + switch (et) { + case ADD_PORT: + List dts = getTypeList(msg, AcmeModelOperation.DECLARED_TYPES_PROP); + List its = getTypeList(msg, AcmeModelOperation.INSTANTIATED_TYPES_PROP); + portName = portName.substring(portName.lastIndexOf(".") + 1); + if (comp != null) { + commands.add(new Pair>(portName, model.getCommandFactory().portCreateCommand(comp, + portName, dts, its))); + return; + } + else { + IAcmeComponentCreateCommand cmd = this. findKeyedCommand(compName, commands, + IAcmeComponentCreateCommand.class); + if (cmd != null) { + commands.add(new Pair>(portName, model.getCommandFactory().portCreateCommand(cmd, + portName, dts, its))); + return; + } + else { + throw new RainbowDeserializationException(MessageFormat.format( + "Could not find a connector or a command associated with the connector ''{0}''.", compName)); + } + } + case REMOVE_PORT: + IAcmePort port = this. resolveInModel(portName, model, IAcmePort.class); + commands.add(new Pair>(portName, model.getCommandFactory().portDeleteCommand(port))); + return; + } + throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", + et.name())); + } + + private void deserializeAcmeGroupEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, + List>> commands) + throws RainbowDeserializationException { + String groupName = (String) msg.getProperty(AcmeModelOperation.GROUP_PROP); + + model = getSystemPropertyIfExists(msg, model); + + switch (et) { + case ADD_GROUP: + List dts = getTypeList(msg, AcmeModelOperation.DECLARED_TYPES_PROP); + List its = getTypeList(msg, AcmeModelOperation.INSTANTIATED_TYPES_PROP); + commands.add(new Pair>(groupName, model.getCommandFactory().groupCreateCommand(model, + groupName, dts, its))); + return; + case REMOVE_GROUP: + IAcmeGroup comp = this. resolveInModel(groupName, model, IAcmeGroup.class); + commands.add(new Pair>(groupName, model.getCommandFactory().groupDeleteCommand(comp))); + return; + } + throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", + et.name())); + } + + private void deserializeAcmeConnectorEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, + List>> commands) + throws RainbowDeserializationException { + String connName = (String) msg.getProperty(AcmeModelOperation.CONNECTOR_PROP); + + model = getSystemPropertyIfExists(msg, model); + + switch (et) { + case ADD_CONNECTOR: + List dts = getTypeList(msg, AcmeModelOperation.DECLARED_TYPES_PROP); + List its = getTypeList(msg, AcmeModelOperation.INSTANTIATED_TYPES_PROP); + commands.add(new Pair>(connName, model.getCommandFactory().connectorCreateCommand(model, + connName, dts, its))); + return; + case REMOVE_CONNECTOR: + IAcmeConnector comp = this. resolveInModel(connName, model, IAcmeConnector.class); + commands.add(new Pair>(connName, model.getCommandFactory().connectorDeleteCommand(comp))); + return; + } + throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", + et.name())); + } + + private void deserializeAcmeComponentEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, + List>> commands) + throws RainbowDeserializationException { + String compName = (String) msg.getProperty(AcmeModelOperation.COMPONENT_PROP); + + model = getSystemPropertyIfExists(msg, model); + + switch (et) { + case ADD_COMPONENT: + List dts = getTypeList(msg, AcmeModelOperation.DECLARED_TYPES_PROP); + List its = getTypeList(msg, AcmeModelOperation.INSTANTIATED_TYPES_PROP); + commands.add(new Pair>(compName, model.getCommandFactory().componentCreateCommand(model, + compName, dts, its))); + return; + case REMOVE_COMPONENT: + IAcmeComponent comp = this. resolveInModel(compName, model, IAcmeComponent.class); + commands.add(new Pair>(compName, model.getCommandFactory().componentDeleteCommand(comp))); + return; + } + throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", + et.name())); + + } + + protected List getTypeList (IRainbowMessage msg, String prop) { + String types = (String) msg.getProperty(prop); + List dts = Collections. emptyList(); + if (types != null && !types.isEmpty()) { + dts = Arrays.asList(types.split(",")); + } + return dts; + } + + private void deserializeAcmeAttachmentEvent (IRainbowMessage msg, IAcmeSystem model, AcmeModelEventType et, + List>> commands) throws RainbowDeserializationException { + String portName = (String )msg.getProperty (AcmeModelOperation.PORT_PROP); + String roleName = (String )msg.getProperty(AcmeModelOperation.ROLE_PROP); + model = getSystemPropertyIfExists(msg, model); + + switch (et) { + case ADD_ATTACHMENT: + commands.add(new Pair>(portName + " to " + roleName, model.getCommandFactory() + .attachmentCreateCommand(model, portName, roleName))); + return; + case REMOVE_ATTACHMENT: + IAcmePort p = this. resolveInModel(portName, model, IAcmePort.class); + IAcmeRole r = this. resolveInModel(roleName, model, IAcmeRole.class); + commands.add(new Pair>(portName + " to " + roleName, model.getCommandFactory() + .attachmentDeleteCommand(model.getAttachment(p, r)))); + return; + } + throw new RainbowDeserializationException(MessageFormat.format("Do not know how to deserialize an event of type ''{0}''.", + et.name())); + } + + protected IAcmeSystem getSystemPropertyIfExists (IRainbowMessage msg, IAcmeSystem model) throws RainbowDeserializationException { + String systemName = (String )msg.getProperty(AcmeModelOperation.SYSTEM_PROP); + + if (systemName != null && !model.getName().equals(systemName)) { + Object o = model.lookupName(systemName); + if (o instanceof IAcmeSystem) { + model = (IAcmeSystem )o; + } + else { + throw new RainbowDeserializationException (MessageFormat.format("The system ''{0}'' could not be found in {1}", systemName, model.getName())); + } + } + return model; + } + + private T resolveInModel (String qualifiedName, IAcmeSystem model, Class cls) throws RainbowDeserializationException { + Object o = model.getContext().getModel().lookupName(qualifiedName); + if (o == null || !cls.isAssignableFrom(o.getClass())) { + + throw new RainbowDeserializationException(MessageFormat.format("Could not resolve ''{0}'' as a {1} in {2}", qualifiedName, + cls.getSimpleName(), model.getQualifiedName())); + } + T t = (T) o; + return t; + } +} diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/RainbowDeserializationException.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/RainbowDeserializationException.java index 925496312..393dc4773 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/RainbowDeserializationException.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/RainbowDeserializationException.java @@ -1,9 +1,9 @@ -package org.acmestudio.rainbow.model.events; - -public class RainbowDeserializationException extends Exception { - - public RainbowDeserializationException(String string) { - super(string); - } - -} +package org.acmestudio.rainbow.model.events; + +public class RainbowDeserializationException extends Exception { + + public RainbowDeserializationException(String string) { + super(string); + } + +} diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/RainbowModelEventListener.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/RainbowModelEventListener.java index 278692ae0..bef6e9516 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/RainbowModelEventListener.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/model/events/RainbowModelEventListener.java @@ -1,149 +1,149 @@ -package org.acmestudio.rainbow.model.events; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.acmestudio.acme.core.exception.AcmeException; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.model.command.IAcmeCommand; -import org.acmestudio.acme.model.event.AcmeModelEventType; -import org.sa.rainbow.core.Identifiable; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.models.IModelInstanceProvider; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; -import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; -import org.sa.rainbow.core.ports.IModelUSBusPort; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; -import org.sa.rainbow.core.ports.eseb.ESEBChangeBusAnnouncePort; -import org.sa.rainbow.core.ports.eseb.ESEBGaugeModelUSBusPort; -import org.sa.rainbow.core.ports.eseb.ESEBModelChangeBusSubscriptionPort; -import org.sa.rainbow.model.acme.AcmeModelCommandFactory; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class RainbowModelEventListener { - - private Map m_ports = new HashMap<>(); - - private final String m_rainbowHost; - private final short m_rainbowPort; - - private Map m_announcePorts = new HashMap<>(); - - public RainbowModelEventListener(String rainbowHost, short rainbowPort) { - m_rainbowHost = rainbowHost; - m_rainbowPort = rainbowPort; - } - - /** - * Makes AcmeStudio listen to events on the model change bus that are associated with the - * system, so that changes reported on the model change bus (reflecting changes on the model in - * Rainbow) are made on the model in AcmeStudio. - * - * @param systemName - * @param system - * @throws IOException - */ - public void attachToSystem (final String systemName, final IAcmeSystem system) throws IOException { - - // Cache the port - ESEBModelChangeBusSubscriptionPort port = m_ports.get(systemName); - if (port == null) { - - // Create the port to the model change bus - port = new ESEBModelChangeBusSubscriptionPort(m_rainbowHost, m_rainbowPort, new IModelInstanceProvider() { - // This is a dummy model instance that must be supplied to the port. But seeing the - // model is already in AcmeStudio, we don't want to get it directly from Rainbow - @Override - public IModelInstance getModelInstance (String type, String name) { - if ("Acme".equals(type) && name.equals(systemName)) { - return (IModelInstance) new AcmeModelInstance(system, "AcmeStudio") { - - @Override - protected AcmeModelInstance generateInstance (IAcmeSystem arg0) { - return null; - } - - @Override - public AcmeModelCommandFactory getCommandFactory () { - return null; - } - - }; - } - return null; - } - }); - m_ports.put(systemName, port); - - // Subscribe to changes on the model change bus, getting events that are on Acme models - // with the same name as the one we are attached to. - port.subscribe(new IRainbowChangeBusSubscription() { - - Map parents = new HashMap<>(); - - @Override - public boolean matches (IRainbowMessage msg) { - String eventType = (String) msg.getProperty(IRainbowMessageFactory.EVENT_TYPE_PROP); - try { - AcmeModelEventType et = AcmeModelEventType.valueOf(eventType); - if (systemName.equals(msg.getProperty(IRainbowMessageFactory.MODEL_NAME_PROP)) - && "Acme".equals(msg.getProperty(IRainbowMessageFactory.MODEL_TYPE_PROP))) { - return true; - } - } - catch (Exception e) { - // The event is not an Acme event - } - return false; - - } - }, new IRainbowModelChangeCallback() { - - @Override - public void onEvent (IModelInstance arg0, IRainbowMessage arg1) { - processEvent(arg0.getModelInstance(), arg1); - } - }); - } - - // AcmeStudio can make changes to the model in Rainbow also, but these go through the Model - // US Bus - IModelUSBusPort announcePort = m_announcePorts.get(systemName); - if (announcePort == null) { - announcePort = new ESEBGaugeModelUSBusPort(new Identifiable() { - - @Override - public String id () { - return "AcmeStudio"; - } - }, m_rainbowHost, m_rainbowPort); - m_announcePorts.put(systemName, announcePort); - } - } - - // Processes a model change bus event by turning it into an AcmeCommand and executing it on the - // model in AcmeStudio - protected void processEvent (IAcmeSystem system, IRainbowMessage msg) { - AcmeEventDeserializer ds = new AcmeEventDeserializer(); - try { - IAcmeCommand command = ds.deserialize(msg, system); - command.execute(); - } - catch (RainbowDeserializationException | IllegalStateException | AcmeException e) { - e.printStackTrace(); - } - } - - public void disconnect () { - for (ESEBModelChangeBusSubscriptionPort port : m_ports.values()) { - - } - } - - public IModelUSBusPort getAnnouncePort (String name) { - return m_announcePorts.get(name); - } - -} +package org.acmestudio.rainbow.model.events; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.acmestudio.acme.core.exception.AcmeException; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.model.command.IAcmeCommand; +import org.acmestudio.acme.model.event.AcmeModelEventType; +import org.sa.rainbow.core.Identifiable; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.models.IModelInstanceProvider; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowChangeBusSubscription; +import org.sa.rainbow.core.ports.IModelChangeBusSubscriberPort.IRainbowModelChangeCallback; +import org.sa.rainbow.core.ports.IModelUSBusPort; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; +import org.sa.rainbow.core.ports.eseb.ESEBChangeBusAnnouncePort; +import org.sa.rainbow.core.ports.eseb.ESEBGaugeModelUSBusPort; +import org.sa.rainbow.core.ports.eseb.ESEBModelChangeBusSubscriptionPort; +import org.sa.rainbow.model.acme.AcmeModelCommandFactory; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class RainbowModelEventListener { + + private Map m_ports = new HashMap<>(); + + private final String m_rainbowHost; + private final short m_rainbowPort; + + private Map m_announcePorts = new HashMap<>(); + + public RainbowModelEventListener(String rainbowHost, short rainbowPort) { + m_rainbowHost = rainbowHost; + m_rainbowPort = rainbowPort; + } + + /** + * Makes AcmeStudio listen to events on the model change bus that are associated with the + * system, so that changes reported on the model change bus (reflecting changes on the model in + * Rainbow) are made on the model in AcmeStudio. + * + * @param systemName + * @param system + * @throws IOException + */ + public void attachToSystem (final String systemName, final IAcmeSystem system) throws IOException { + + // Cache the port + ESEBModelChangeBusSubscriptionPort port = m_ports.get(systemName); + if (port == null) { + + // Create the port to the model change bus + port = new ESEBModelChangeBusSubscriptionPort(m_rainbowHost, m_rainbowPort, new IModelInstanceProvider() { + // This is a dummy model instance that must be supplied to the port. But seeing the + // model is already in AcmeStudio, we don't want to get it directly from Rainbow + @Override + public IModelInstance getModelInstance (String type, String name) { + if ("Acme".equals(type) && name.equals(systemName)) { + return (IModelInstance) new AcmeModelInstance(system, "AcmeStudio") { + + @Override + protected AcmeModelInstance generateInstance (IAcmeSystem arg0) { + return null; + } + + @Override + public AcmeModelCommandFactory getCommandFactory () { + return null; + } + + }; + } + return null; + } + }); + m_ports.put(systemName, port); + + // Subscribe to changes on the model change bus, getting events that are on Acme models + // with the same name as the one we are attached to. + port.subscribe(new IRainbowChangeBusSubscription() { + + Map parents = new HashMap<>(); + + @Override + public boolean matches (IRainbowMessage msg) { + String eventType = (String) msg.getProperty(IRainbowMessageFactory.EVENT_TYPE_PROP); + try { + AcmeModelEventType et = AcmeModelEventType.valueOf(eventType); + if (systemName.equals(msg.getProperty(IRainbowMessageFactory.MODEL_NAME_PROP)) + && "Acme".equals(msg.getProperty(IRainbowMessageFactory.MODEL_TYPE_PROP))) { + return true; + } + } + catch (Exception e) { + // The event is not an Acme event + } + return false; + + } + }, new IRainbowModelChangeCallback() { + + @Override + public void onEvent (IModelInstance arg0, IRainbowMessage arg1) { + processEvent(arg0.getModelInstance(), arg1); + } + }); + } + + // AcmeStudio can make changes to the model in Rainbow also, but these go through the Model + // US Bus + IModelUSBusPort announcePort = m_announcePorts.get(systemName); + if (announcePort == null) { + announcePort = new ESEBGaugeModelUSBusPort(new Identifiable() { + + @Override + public String id () { + return "AcmeStudio"; + } + }, m_rainbowHost, m_rainbowPort); + m_announcePorts.put(systemName, announcePort); + } + } + + // Processes a model change bus event by turning it into an AcmeCommand and executing it on the + // model in AcmeStudio + protected void processEvent (IAcmeSystem system, IRainbowMessage msg) { + AcmeEventDeserializer ds = new AcmeEventDeserializer(); + try { + IAcmeCommand command = ds.deserialize(msg, system); + command.execute(); + } + catch (RainbowDeserializationException | IllegalStateException | AcmeException e) { + e.printStackTrace(); + } + } + + public void disconnect () { + for (ESEBModelChangeBusSubscriptionPort port : m_ports.values()) { + + } + } + + public IModelUSBusPort getAnnouncePort (String name) { + return m_announcePorts.get(name); + } + +} diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/RainbowConnectionDialog.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/RainbowConnectionDialog.java index f9d532f2c..bce9225f3 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/RainbowConnectionDialog.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/RainbowConnectionDialog.java @@ -1,173 +1,173 @@ -package org.acmestudio.rainbow.ui; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; - -import org.acmestudio.ui.util.Listeners; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.TitleAreaDialog; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.FormAttachment; -import org.eclipse.swt.layout.FormData; -import org.eclipse.swt.layout.FormLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.sa.rainbow.core.models.IModelInstanceProvider; -import org.sa.rainbow.core.ports.eseb.ESEBModelChangeBusSubscriptionPort; - -public class RainbowConnectionDialog extends TitleAreaDialog { - private Text m_hostTxt; - private Text m_portTxt; - private Text m_infoTxt; - private Button m_btnConnect; - protected ESEBModelChangeBusSubscriptionPort m_connectionPort; - protected IModelInstanceProvider m_modelProvider; - private String m_host; - private short m_port; - - /** - * Create the dialog. - * @param parentShell - */ - public RainbowConnectionDialog(Shell parentShell) { - super(parentShell); - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea (Composite parent) { - setMessage("Enter the host and port of the running Rainbow communication bus."); - setTitle("Connect to Rainbow"); - Composite area = (Composite) super.createDialogArea(parent); - Composite container = new Composite(area, SWT.NONE); - container.setLayout(new FormLayout()); - container.setLayoutData(new GridData(GridData.FILL_BOTH)); - - Label lblHost = new Label(container, SWT.NONE); - FormData fd_lblHost = new FormData(); - fd_lblHost.top = new FormAttachment(0, 10); - fd_lblHost.left = new FormAttachment(0, 10); - lblHost.setLayoutData(fd_lblHost); - lblHost.setText("Host:"); - - Label lblPort = new Label(container, SWT.NONE); - FormData fd_lblPort = new FormData(); - fd_lblPort.top = new FormAttachment(lblHost, 6); - fd_lblPort.left = new FormAttachment(0, 10); - lblPort.setLayoutData(fd_lblPort); - lblPort.setText("Port:"); - - m_hostTxt = new Text(container, SWT.BORDER); - FormData fd_text = new FormData(); - fd_text.right = new FormAttachment(lblHost, 256, SWT.RIGHT); - fd_text.top = new FormAttachment(0, 4); - fd_text.left = new FormAttachment(lblHost, 20); - m_hostTxt.setLayoutData(fd_text); - ModifyListener modifyListener = new ModifyListener() { - - @Override - public void modifyText (ModifyEvent e) { - verifyInput(); - } - }; - m_hostTxt.addModifyListener(modifyListener); - - m_portTxt = new Text(container, SWT.BORDER); - FormData fd_text_1 = new FormData(); - fd_text_1.right = new FormAttachment(m_hostTxt, 0, SWT.RIGHT); - fd_text_1.top = new FormAttachment(m_hostTxt, 6); - fd_text_1.left = new FormAttachment(m_hostTxt, 0, SWT.LEFT); - m_portTxt.setLayoutData(fd_text_1); - m_portTxt.addModifyListener(modifyListener); - m_portTxt.addVerifyListener(new Listeners.NumberVerifier(0, Short.MAX_VALUE)); - - m_btnConnect = new Button(container, SWT.NONE); - FormData fd_btnConnect = new FormData(); - fd_btnConnect.bottom = new FormAttachment(m_portTxt, 0, SWT.BOTTOM); - fd_btnConnect.left = new FormAttachment(m_portTxt, 24); - m_btnConnect.setLayoutData(fd_btnConnect); - m_btnConnect.setText("Connect"); - m_btnConnect.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected (SelectionEvent e) { - try { - m_connectionPort = new ESEBModelChangeBusSubscriptionPort(m_hostTxt.getText(), Short.parseShort(m_portTxt - .getText()), m_modelProvider); - getButton(IDialogConstants.OK_ID).setEnabled(true); - } - catch (NumberFormatException | IOException e1) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - e1.printStackTrace(new PrintStream(baos)); - m_infoTxt.setText("Could not connect to Rainbow:\n" + baos.toString()); - } - } - }); - - m_infoTxt = new Text(container, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI); - m_infoTxt.setEditable(false); - FormData fd_text_2 = new FormData(); - fd_text_2.top = new FormAttachment(m_portTxt, 6); - fd_text_2.left = new FormAttachment(0, 10); - fd_text_2.right = new FormAttachment(0, 434); - fd_text_2.bottom = new FormAttachment(100, -10); - m_infoTxt.setLayoutData(fd_text_2); - - m_btnConnect.setEnabled(false); - return area; - - } - - protected void verifyInput () { - if (!m_portTxt.getText().trim().isEmpty() && !m_hostTxt.getText().trim().isEmpty()) { - m_btnConnect.setEnabled (true); - } - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar (Composite parent) { - createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - getButton(IDialogConstants.OK_ID).setEnabled(false); - } - - /** - * Return the initial size of the dialog. - */ - @Override - protected Point getInitialSize () { - return new Point(450, 300); - } - - @Override - protected void okPressed () { - m_host = m_hostTxt.getText(); - m_port = Short.parseShort(m_portTxt.getText()); - super.okPressed(); - } - - public String getHost () { - return m_host; - } - - public short getPort () { - return m_port; - } -} +package org.acmestudio.rainbow.ui; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import org.acmestudio.ui.util.Listeners; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.FormAttachment; +import org.eclipse.swt.layout.FormData; +import org.eclipse.swt.layout.FormLayout; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.sa.rainbow.core.models.IModelInstanceProvider; +import org.sa.rainbow.core.ports.eseb.ESEBModelChangeBusSubscriptionPort; + +public class RainbowConnectionDialog extends TitleAreaDialog { + private Text m_hostTxt; + private Text m_portTxt; + private Text m_infoTxt; + private Button m_btnConnect; + protected ESEBModelChangeBusSubscriptionPort m_connectionPort; + protected IModelInstanceProvider m_modelProvider; + private String m_host; + private short m_port; + + /** + * Create the dialog. + * @param parentShell + */ + public RainbowConnectionDialog(Shell parentShell) { + super(parentShell); + } + + /** + * Create contents of the dialog. + * @param parent + */ + @Override + protected Control createDialogArea (Composite parent) { + setMessage("Enter the host and port of the running Rainbow communication bus."); + setTitle("Connect to Rainbow"); + Composite area = (Composite) super.createDialogArea(parent); + Composite container = new Composite(area, SWT.NONE); + container.setLayout(new FormLayout()); + container.setLayoutData(new GridData(GridData.FILL_BOTH)); + + Label lblHost = new Label(container, SWT.NONE); + FormData fd_lblHost = new FormData(); + fd_lblHost.top = new FormAttachment(0, 10); + fd_lblHost.left = new FormAttachment(0, 10); + lblHost.setLayoutData(fd_lblHost); + lblHost.setText("Host:"); + + Label lblPort = new Label(container, SWT.NONE); + FormData fd_lblPort = new FormData(); + fd_lblPort.top = new FormAttachment(lblHost, 6); + fd_lblPort.left = new FormAttachment(0, 10); + lblPort.setLayoutData(fd_lblPort); + lblPort.setText("Port:"); + + m_hostTxt = new Text(container, SWT.BORDER); + FormData fd_text = new FormData(); + fd_text.right = new FormAttachment(lblHost, 256, SWT.RIGHT); + fd_text.top = new FormAttachment(0, 4); + fd_text.left = new FormAttachment(lblHost, 20); + m_hostTxt.setLayoutData(fd_text); + ModifyListener modifyListener = new ModifyListener() { + + @Override + public void modifyText (ModifyEvent e) { + verifyInput(); + } + }; + m_hostTxt.addModifyListener(modifyListener); + + m_portTxt = new Text(container, SWT.BORDER); + FormData fd_text_1 = new FormData(); + fd_text_1.right = new FormAttachment(m_hostTxt, 0, SWT.RIGHT); + fd_text_1.top = new FormAttachment(m_hostTxt, 6); + fd_text_1.left = new FormAttachment(m_hostTxt, 0, SWT.LEFT); + m_portTxt.setLayoutData(fd_text_1); + m_portTxt.addModifyListener(modifyListener); + m_portTxt.addVerifyListener(new Listeners.NumberVerifier(0, Short.MAX_VALUE)); + + m_btnConnect = new Button(container, SWT.NONE); + FormData fd_btnConnect = new FormData(); + fd_btnConnect.bottom = new FormAttachment(m_portTxt, 0, SWT.BOTTOM); + fd_btnConnect.left = new FormAttachment(m_portTxt, 24); + m_btnConnect.setLayoutData(fd_btnConnect); + m_btnConnect.setText("Connect"); + m_btnConnect.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected (SelectionEvent e) { + try { + m_connectionPort = new ESEBModelChangeBusSubscriptionPort(m_hostTxt.getText(), Short.parseShort(m_portTxt + .getText()), m_modelProvider); + getButton(IDialogConstants.OK_ID).setEnabled(true); + } + catch (NumberFormatException | IOException e1) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e1.printStackTrace(new PrintStream(baos)); + m_infoTxt.setText("Could not connect to Rainbow:\n" + baos.toString()); + } + } + }); + + m_infoTxt = new Text(container, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI); + m_infoTxt.setEditable(false); + FormData fd_text_2 = new FormData(); + fd_text_2.top = new FormAttachment(m_portTxt, 6); + fd_text_2.left = new FormAttachment(0, 10); + fd_text_2.right = new FormAttachment(0, 434); + fd_text_2.bottom = new FormAttachment(100, -10); + m_infoTxt.setLayoutData(fd_text_2); + + m_btnConnect.setEnabled(false); + return area; + + } + + protected void verifyInput () { + if (!m_portTxt.getText().trim().isEmpty() && !m_hostTxt.getText().trim().isEmpty()) { + m_btnConnect.setEnabled (true); + } + } + + /** + * Create contents of the button bar. + * @param parent + */ + @Override + protected void createButtonsForButtonBar (Composite parent) { + createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + getButton(IDialogConstants.OK_ID).setEnabled(false); + } + + /** + * Return the initial size of the dialog. + */ + @Override + protected Point getInitialSize () { + return new Point(450, 300); + } + + @Override + protected void okPressed () { + m_host = m_hostTxt.getText(); + m_port = Short.parseShort(m_portTxt.getText()); + super.okPressed(); + } + + public String getHost () { + return m_host; + } + + public short getPort () { + return m_port; + } +} diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/ShowSourceDialog.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/ShowSourceDialog.java index adf658ef4..c4d25ebea 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/ShowSourceDialog.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/ShowSourceDialog.java @@ -1,64 +1,64 @@ -package org.acmestudio.rainbow.ui; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.swt.browser.Browser; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Text; - -public class ShowSourceDialog extends Dialog { - - private final Browser m_swtBrowser; - private StyledText m_text; - - /** - * Create the dialog. - * @param parentShell - * @param swtBrowser - */ - public ShowSourceDialog(Shell parentShell, Browser swtBrowser) { - super(parentShell); - setShellStyle(SWT.RESIZE); - m_swtBrowser = swtBrowser; - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea (Composite parent) { - Composite container = (Composite) super.createDialogArea(parent); - container.setLayout(new FillLayout(SWT.HORIZONTAL)); - - m_text = new StyledText(container, SWT.BORDER | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI); - m_text.setEditable(false); - String text = m_swtBrowser.getText(); - m_text.setText(text); - return container; - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar (Composite parent) { - createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); - } - - /** - * Return the initial size of the dialog. - */ - @Override - protected Point getInitialSize () { - return new Point(450, 300); - } - -} +package org.acmestudio.rainbow.ui; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.swt.browser.Browser; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Text; + +public class ShowSourceDialog extends Dialog { + + private final Browser m_swtBrowser; + private StyledText m_text; + + /** + * Create the dialog. + * @param parentShell + * @param swtBrowser + */ + public ShowSourceDialog(Shell parentShell, Browser swtBrowser) { + super(parentShell); + setShellStyle(SWT.RESIZE); + m_swtBrowser = swtBrowser; + } + + /** + * Create contents of the dialog. + * @param parent + */ + @Override + protected Control createDialogArea (Composite parent) { + Composite container = (Composite) super.createDialogArea(parent); + container.setLayout(new FillLayout(SWT.HORIZONTAL)); + + m_text = new StyledText(container, SWT.BORDER | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI); + m_text.setEditable(false); + String text = m_swtBrowser.getText(); + m_text.setText(text); + return container; + } + + /** + * Create contents of the button bar. + * @param parent + */ + @Override + protected void createButtonsForButtonBar (Composite parent) { + createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); + } + + /** + * Return the initial size of the dialog. + */ + @Override + protected Point getInitialSize () { + return new Point(450, 300); + } + +} diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugeEventListener.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugeEventListener.java index 395e5584a..bd952ef58 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugeEventListener.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugeEventListener.java @@ -1,49 +1,49 @@ -package org.acmestudio.rainbow.ui.part; - -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.type.IAcmeRecordValue; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.model.event.AcmeEventListenerAdapter; -import org.acmestudio.acme.model.event.AcmePropertyEvent; -import org.eclipse.swt.browser.Browser; -import org.eclipse.swt.widgets.Display; - -public class GaugeEventListener extends AcmeEventListenerAdapter { - - private final IAcmeProperty m_property; - private final IAcmeProperty m_gaugeDescription; - private final Browser m_browser; - - public GaugeEventListener(IAcmeProperty property, IAcmeProperty gd, Browser browser) { - m_property = property; - m_gaugeDescription = gd; - m_browser = browser; - } - - @Override - public void propertyValueSet (AcmePropertyEvent event) { - Display.getDefault().asyncExec (new Runnable() { - public void run () { - // Update the browser gauge with the new value - String gaugeId = getGaugeId(); - float propertyValue = PropertyHelper.toJavaVal(m_property.getValue(), Float.class); - String script = "updateGauge ('" + gaugeId + "', " + Float.toString(propertyValue) + ");"; - m_browser.execute(script); - } - }); - } - - private String getGaugeId () { - IAcmeRecordValue gd = (IAcmeRecordValue )m_gaugeDescription.getValue(); - String gaugeId = (String) PropertyHelper.toJavaVal(gd.getField("name").getValue()); - return gaugeId; - } - - @Override - public void propertyDeleted (AcmePropertyEvent event) { - if (event.getProperty() == m_gaugeDescription && event.getPropertyBearer() == m_property) { - m_property.removeEventListener(this); - m_browser.execute("removeRainbowGauge (" + getGaugeId () + ");"); - } - } -} +package org.acmestudio.rainbow.ui.part; + +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.type.IAcmeRecordValue; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.model.event.AcmeEventListenerAdapter; +import org.acmestudio.acme.model.event.AcmePropertyEvent; +import org.eclipse.swt.browser.Browser; +import org.eclipse.swt.widgets.Display; + +public class GaugeEventListener extends AcmeEventListenerAdapter { + + private final IAcmeProperty m_property; + private final IAcmeProperty m_gaugeDescription; + private final Browser m_browser; + + public GaugeEventListener(IAcmeProperty property, IAcmeProperty gd, Browser browser) { + m_property = property; + m_gaugeDescription = gd; + m_browser = browser; + } + + @Override + public void propertyValueSet (AcmePropertyEvent event) { + Display.getDefault().asyncExec (new Runnable() { + public void run () { + // Update the browser gauge with the new value + String gaugeId = getGaugeId(); + float propertyValue = PropertyHelper.toJavaVal(m_property.getValue(), Float.class); + String script = "updateGauge ('" + gaugeId + "', " + Float.toString(propertyValue) + ");"; + m_browser.execute(script); + } + }); + } + + private String getGaugeId () { + IAcmeRecordValue gd = (IAcmeRecordValue )m_gaugeDescription.getValue(); + String gaugeId = (String) PropertyHelper.toJavaVal(gd.getField("name").getValue()); + return gaugeId; + } + + @Override + public void propertyDeleted (AcmePropertyEvent event) { + if (event.getProperty() == m_gaugeDescription && event.getPropertyBearer() == m_property) { + m_property.removeEventListener(this); + m_browser.execute("removeRainbowGauge (" + getGaugeId () + ");"); + } + } +} diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugesSection.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugesSection.java index 2ec687221..4a0f90d65 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugesSection.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugesSection.java @@ -1,483 +1,483 @@ -package org.acmestudio.rainbow.ui.part; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.acmestudio.acme.ModelHelper; -import org.acmestudio.acme.PropertyHelper; -import org.acmestudio.acme.core.resource.RegionManager; -import org.acmestudio.acme.core.type.IAcmeFloatValue; -import org.acmestudio.acme.core.type.IAcmeRecordValue; -import org.acmestudio.acme.element.IAcmeElement; -import org.acmestudio.acme.element.IAcmeElementInstance; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.element.property.IAcmeProperty; -import org.acmestudio.acme.element.property.IAcmePropertyValue; -import org.acmestudio.eclipse.core.util.LanguagePackHelper; -import org.acmestudio.rainbow.Rainbow; -import org.acmestudio.rainbow.ui.ShowSourceDialog; -import org.acmestudio.ui.EclipseHelper; -import org.acmestudio.ui.view.element.ElementViewPart; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.ActionContributionItem; -import org.eclipse.jface.action.IContributionItem; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.viewers.IFilter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.browser.Browser; -import org.eclipse.swt.browser.BrowserFunction; -import org.eclipse.swt.browser.ProgressEvent; -import org.eclipse.swt.browser.ProgressListener; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Dialog; -import org.eclipse.swt.widgets.Display; -import org.sa.rainbow.core.error.RainbowModelException; -import org.sa.rainbow.core.models.commands.IRainbowModelOperation; -import org.sa.rainbow.core.ports.IModelUSBusPort; -import org.sa.rainbow.model.acme.AcmeModelCommandFactory; -import org.sa.rainbow.model.acme.AcmeModelInstance; - -public class GaugesSection extends ElementViewPart { - public static final String GAUGE_DESCRIPTION_TYPE = "GaugeDescriptionT"; - public static final String GAUGE_RESOURCE = "/resources/html/gauge-element.html"; - - protected static String s_html = null; - - public static class Filter implements IFilter { - - /** - * Returns true if the object is an acme element and at least one of its - * properties has a meta property with gauge information. - */ - @Override - public boolean select (Object toTest) { - Object o = EclipseHelper.unwrapToElement(toTest); - boolean applies = false; - if (o instanceof IAcmeElementInstance) { - IAcmeElementInstance element = (IAcmeElementInstance) o; - Set properties = element.getProperties(); - for (Iterator i = properties.iterator(); i.hasNext() && !applies;) { - IAcmeProperty prop = (IAcmeProperty) i.next(); - Set metaProps = prop.getProperties(); - for (Iterator j = metaProps.iterator(); j.hasNext() && !applies;) { - IAcmeProperty metaProp = (IAcmeProperty) j.next(); - if (metaProp.getType () != null && metaProp.getType().getName().endsWith(GAUGE_DESCRIPTION_TYPE)) - applies = true; - } - } - - } - return applies; - } - } - - private static void initializeResource () { - try { - InputStream stream = GaugesSection.class.getResourceAsStream(GAUGE_RESOURCE); - BufferedReader reader = new BufferedReader (new InputStreamReader(stream)); - String line = null; - StringBuilder builder = new StringBuilder (); - String ls = System.getProperty ("line.separator"); - while ((line = reader.readLine ()) != null) { - builder.append (line); - builder.append (ls); - } - - s_html = builder.toString (); - } - catch (IOException e) { - e.printStackTrace(); - } - } - - private IAcmeElementInstance m_element; - private Browser m_swtBrowser; - private Map> m_gaugedProperties = new LinkedHashMap<>(); - private Map> m_registeredListeners = Collections - .> synchronizedMap(new HashMap>()); - private AcmeModelInstance m_commandFactory; - private Action m_showSourceAction; - public GaugesSection () { - if (s_html == null) - initializeResource(); - } - - - @Override - public void createControl (Composite parent, int style) { - super.createControl(parent, style); -// parent.setLayoutData(GridDataFactory.fillDefaults().align(GridData.FILL, GridData.FILL).grab(true, true).create()); - getComposite ().setLayout(new FillLayout()); - getComposite ().setBackground(org.eclipse.draw2d.ColorConstants.red); - m_swtBrowser = new Browser(getComposite (), SWT.MOZILLA); - m_swtBrowser.setJavascriptEnabled(true); - - // Add hook to allow updates - new BrowserFunction(m_swtBrowser, "triggerUpdateValue") { - @Override - public Object function (Object[] arguments) { - IAcmeProperty property = m_element.getProperty((String )arguments[0]); - if (property != null) { - if (property.getProperty("operation") != null) { - IAcmeProperty operation = property.getProperty ("operation"); - Map elements = PropertyHelper.toJavaVal((IAcmeRecordValue )operation.getValue()); - List args = (List )elements.get("arguments"); - AcmeModelCommandFactory cf = m_commandFactory.getCommandFactory(); - ValuePromptDialog dialog = new ValuePromptDialog(GaugesSection.this.getComposite().getShell()); - if (dialog.open() == IDialogConstants.OK_ID) { - String val = dialog.getValue (); - try { - IRainbowModelOperation cmd = cf.generateCommand((String )elements.get("name"), m_element.getQualifiedName(), val); - IModelUSBusPort announcePort = Rainbow.getRainbowListener().getAnnouncePort (ModelHelper.getAcmeSystem(m_element).getName ()); - announcePort.updateModel(cmd); - } - catch (RainbowModelException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } - return null; - } - }; - - makeActions (); - } - - @Override - public void setInput (IAcmeElement o) { - removeListeners(); - m_gaugedProperties.clear(); - m_registeredListeners.clear (); - super.setInput(o); - if (o instanceof IAcmeElementInstance) { - m_element = (IAcmeElementInstance) o; - } - - pullOutGaugeProperties(); - setupGaugeHtml (); - addListeners(); - - if (o != null) { - IAcmeSystem sys = ModelHelper.getAcmeSystem(o); - IAcmeProperty cfProp = sys.getProperty("rainbow-command-factory"); - if (cfProp != null) { - String cf = (String )PropertyHelper.toJavaVal(cfProp.getValue()); - if (cf != null) { - if (m_commandFactory == null || !cf.equals(m_commandFactory.getClass ().getName ())) { - try { - Class cfCls = Class.forName(cf); - Constructor init = cfCls.getConstructor(new Class[] {IAcmeSystem.class, String.class}); - if (init != null) { - m_commandFactory = (AcmeModelInstance )init.newInstance(sys, "AcmeStudio"); - } - } - catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException - | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } - } - } - - private void setupGaugeHtml () { - if (m_element == null || m_gaugedProperties.isEmpty()) { - m_swtBrowser.setText ("

There are no gauges for this element

"); - return; - } - m_swtBrowser.setText(s_html); - - m_swtBrowser.addProgressListener(new ProgressListener() { - - @Override - public void completed (ProgressEvent event) { -// m_swtBrowser.execute("test();"); - - // Create all the gauges for the gauge properties - for (Entry> e : m_gaugedProperties.entrySet()) { - for (IAcmeProperty gaugeDescProp : e.getValue()) { - IAcmePropertyValue value = gaugeDescProp.getValue(); - String propName = e.getKey(); - if (value instanceof IAcmeRecordValue) { - IAcmeRecordValue gaugeDesc = (IAcmeRecordValue) value; - Object gaugeType = PropertyHelper.toJavaVal(gaugeDesc.getField("gauge-type").getValue()); - if ("PressureGauge".equals(gaugeType)) { - createPressureGauge(propName, gaugeDesc); - } - else if ("TrinaryGauge".equals (gaugeType)) { - createTrinaryGauge (propName, gaugeDesc); - } - else if ("MovingLineGauge".equals(gaugeType)) - createMovingLineGauge(propName, gaugeDesc); - } - } - } - } - - @Override - public void changed (ProgressEvent event) { - - } - }); - - - - - - } - - private void createTrinaryGauge (String propName, IAcmeRecordValue gaugeDesc) { - IAcmePropertyValue goodValueAcme = gaugeDesc.getField("good").getValue(); - IAcmePropertyValue badValueAcme = gaugeDesc.getField("bad").getValue(); - String good = "1"; - String bad = "-1"; - if (goodValueAcme != null) { - try { - good = LanguagePackHelper.defaultLanguageHelper().propertyValueToString(goodValueAcme, new RegionManager ()); - } - catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (badValueAcme != null) { - try { - bad = LanguagePackHelper.defaultLanguageHelper().propertyValueToString(badValueAcme, new RegionManager ()); - } - catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - String name = (String )PropertyHelper.toJavaVal(gaugeDesc.getField ("name").getValue ()); - String scriptCommand = "createTrinaryGauge ('" + name + "','" + propName + "', '" + good + "', '" + bad + "');"; - m_swtBrowser.execute(scriptCommand); - try { - String script = "updateGauge ('" + name + "', '" + LanguagePackHelper.defaultLanguageHelper().propertyValueToString(m_element.getProperty(propName).getValue(), new RegionManager ()) +"');"; - m_swtBrowser.execute(script); - } - catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - private void createPressureGauge (String propName, IAcmeRecordValue gaugeDesc) { - IAcmeProperty gaugedProperty = m_element.getProperty(propName); - IAcmePropertyValue minValueAcme = gaugeDesc.getField("min").getValue(); - IAcmePropertyValue maxValueAcme = gaugeDesc.getField("max").getValue (); - IAcmePropertyValue redValueAcme = gaugeDesc.getField("red").getValue (); - IAcmePropertyValue yellowValueAcme = gaugeDesc.getField ("yellow").getValue (); - float minValue = minValueAcme instanceof IAcmeFloatValue?(float )PropertyHelper.toJavaVal(minValueAcme):(int)PropertyHelper.toJavaVal(minValueAcme); - float maxValue = maxValueAcme instanceof IAcmeFloatValue?(float )PropertyHelper.toJavaVal(maxValueAcme):(int )PropertyHelper.toJavaVal(maxValueAcme); - float red = -1; - if (gaugeDesc.getField("red") != null && redValueAcme != null) { - red = redValueAcme instanceof IAcmeFloatValue?(float )PropertyHelper.toJavaVal (redValueAcme):(int )PropertyHelper.toJavaVal(redValueAcme); - } - float yellow = -1; - if (gaugeDesc.getField ("yellow") != null && yellowValueAcme != null) { - yellow = yellowValueAcme instanceof IAcmeFloatValue?(float )PropertyHelper.toJavaVal(yellowValueAcme):(int )PropertyHelper.toJavaVal (yellowValueAcme); - } - String name = (String) PropertyHelper.toJavaVal(gaugeDesc.getField("name").getValue ()); - - String scriptCmd = "createPressureGauge ('" + name + "', '" + propName + "', " + Float.toString (minValue) + ", " + Float.toString (maxValue); - if (red != -1) { - scriptCmd += ", " + Float.toString(red); - if (yellow != -1) - scriptCmd += ", " + Float.toString (yellow); - } - - if (gaugedProperty.getProperty("operation") != null) { - scriptCmd += ", true"; - } - - scriptCmd += ");"; - m_swtBrowser.execute(scriptCmd); - try { - String script = "updateGauge ('" + name + "', " + LanguagePackHelper.defaultLanguageHelper().propertyValueToString(gaugedProperty.getValue(), new RegionManager ()) +");"; - m_swtBrowser.execute(script); - } - catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - private static class TriggerUpdateValueFunction extends BrowserFunction { - - private final IAcmeElementInstance m_element; - - public TriggerUpdateValueFunction(Browser browser, IAcmeElementInstance element) { - super(browser, "triggerUpdateValue"); - m_element = element; - } - - @Override - public Object function (Object[] arguments) { - IAcmeProperty property = m_element.getProperty((String )arguments[0]); - if (property != null) { - - } - return null; - } - - } - - private static class NextValueFunction extends BrowserFunction { - - protected static final String NEXT = "nextValueFor"; - private IAcmeProperty m_prop; - - public NextValueFunction(Browser swtBrowser, IAcmeProperty prop) { - super(swtBrowser, NEXT + prop.getName().replaceAll("-", "_")); - m_prop = prop; - } - - @Override - public Object function (Object[] arguments) { - if (m_prop.getValue () == null) - return null; - return PropertyHelper.toJavaVal(m_prop.getValue (), Float.class); - } - - } - - - private void createMovingLineGauge (String propName, IAcmeRecordValue gaugeDesc) { - IAcmePropertyValue minValueAcme = gaugeDesc.getField("min").getValue (); - IAcmePropertyValue maxValueAcme = gaugeDesc.getField("max").getValue (); - IAcmePropertyValue windowValueAcme = gaugeDesc.getField("window").getValue (); - IAcmePropertyValue thresholdValueAcme = gaugeDesc.getField("threshold").getValue (); - String name = (String )PropertyHelper.toJavaVal(gaugeDesc.getField("name").getValue ()); - - float min = PropertyHelper.toJavaVal(minValueAcme, Float.class); - float max = PropertyHelper.toJavaVal(maxValueAcme, Float.class); - float threshold = PropertyHelper.toJavaVal(thresholdValueAcme, Float.class); - - int window = windowValueAcme!=null?PropertyHelper.toJavaVal(windowValueAcme, Integer.class):10; - - IAcmeProperty prop = m_element.getProperty(propName); - NextValueFunction nvf = new NextValueFunction (m_swtBrowser, prop); - - String params = "{threshold:" + threshold + "}"; - String script = "createMovingLineGauge('" + name + "', '" + propName + "', " + Float.toString (min) + ", " + Float.toString (max) + ", " + window + ", " + nvf.getName () + ", " + params + ");"; - m_swtBrowser.execute(script); - - } - - private void removeListeners () { - if (m_element == null) - return; - for (Entry> entry : m_registeredListeners.entrySet()) { - IAcmeProperty property = m_element.getProperty(entry.getKey ()); - for (GaugeEventListener l : entry.getValue()) { - property.removeEventListener(l); - } - } - } - - /** - * Adds a listener to each property that fires when the value changes to - * update the gauge - */ - private void addListeners () { - if (m_element == null) - return; - for (Entry> entry : m_gaugedProperties.entrySet()) { - IAcmeProperty property = m_element.getProperty(entry.getKey ()); - Set listeners = new HashSet<> (); - for (IAcmeProperty gd : entry.getValue()) { - GaugeEventListener eu = new GaugeEventListener (property, gd, m_swtBrowser); - listeners.add (eu); - property.addEventListener(eu); - } - - } - - m_swtBrowser.addDisposeListener(new DisposeListener() { - - @Override - public void widgetDisposed (DisposeEvent e) { - removeListeners(); - } - }); - } - - private void pullOutGaugeProperties () { - if (m_element == null) - return; - Set properties = m_element.getProperties(); - for (IAcmeProperty prop : properties) { - Set gaugeDescs = pullOutGaugeDescriptions(prop); - if (!gaugeDescs.isEmpty()) - m_gaugedProperties.put(prop.getName(), gaugeDescs); - } - } - - private Set pullOutGaugeDescriptions (IAcmeProperty prop) { - Set gaugeDescs = new LinkedHashSet<>(); - for (IAcmeProperty p : prop.getProperties()) { - if (p.getType().getName().endsWith(GAUGE_DESCRIPTION_TYPE)) - gaugeDescs.add(p); - } - return gaugeDescs; - } - - @Override - public void dispose () { - super.dispose (); - if (m_swtBrowser != null) m_swtBrowser.dispose(); - m_swtBrowser = null; - removeListeners(); - } - - - private void makeActions () { - m_showSourceAction = new Action () { - @Override - public void run () { - ShowSourceDialog dialog = new ShowSourceDialog (Display.getDefault().getActiveShell(), m_swtBrowser); - dialog.open (); - } - }; - m_showSourceAction.setText ("Show source"); - } - - @Override - public IContributionItem[] getContributions () { - return new ActionContributionItem [] {new ActionContributionItem(m_showSourceAction)}; - } - - - @Override - public void addItemSelectionListener (SelectionListener listener) { - - } - - - -} +package org.acmestudio.rainbow.ui.part; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.acmestudio.acme.ModelHelper; +import org.acmestudio.acme.PropertyHelper; +import org.acmestudio.acme.core.resource.RegionManager; +import org.acmestudio.acme.core.type.IAcmeFloatValue; +import org.acmestudio.acme.core.type.IAcmeRecordValue; +import org.acmestudio.acme.element.IAcmeElement; +import org.acmestudio.acme.element.IAcmeElementInstance; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.element.property.IAcmeProperty; +import org.acmestudio.acme.element.property.IAcmePropertyValue; +import org.acmestudio.eclipse.core.util.LanguagePackHelper; +import org.acmestudio.rainbow.Rainbow; +import org.acmestudio.rainbow.ui.ShowSourceDialog; +import org.acmestudio.ui.EclipseHelper; +import org.acmestudio.ui.view.element.ElementViewPart; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.ActionContributionItem; +import org.eclipse.jface.action.IContributionItem; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.IFilter; +import org.eclipse.swt.SWT; +import org.eclipse.swt.browser.Browser; +import org.eclipse.swt.browser.BrowserFunction; +import org.eclipse.swt.browser.ProgressEvent; +import org.eclipse.swt.browser.ProgressListener; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Dialog; +import org.eclipse.swt.widgets.Display; +import org.sa.rainbow.core.error.RainbowModelException; +import org.sa.rainbow.core.models.commands.IRainbowModelOperation; +import org.sa.rainbow.core.ports.IModelUSBusPort; +import org.sa.rainbow.model.acme.AcmeModelCommandFactory; +import org.sa.rainbow.model.acme.AcmeModelInstance; + +public class GaugesSection extends ElementViewPart { + public static final String GAUGE_DESCRIPTION_TYPE = "GaugeDescriptionT"; + public static final String GAUGE_RESOURCE = "/resources/html/gauge-element.html"; + + protected static String s_html = null; + + public static class Filter implements IFilter { + + /** + * Returns true if the object is an acme element and at least one of its + * properties has a meta property with gauge information. + */ + @Override + public boolean select (Object toTest) { + Object o = EclipseHelper.unwrapToElement(toTest); + boolean applies = false; + if (o instanceof IAcmeElementInstance) { + IAcmeElementInstance element = (IAcmeElementInstance) o; + Set properties = element.getProperties(); + for (Iterator i = properties.iterator(); i.hasNext() && !applies;) { + IAcmeProperty prop = (IAcmeProperty) i.next(); + Set metaProps = prop.getProperties(); + for (Iterator j = metaProps.iterator(); j.hasNext() && !applies;) { + IAcmeProperty metaProp = (IAcmeProperty) j.next(); + if (metaProp.getType () != null && metaProp.getType().getName().endsWith(GAUGE_DESCRIPTION_TYPE)) + applies = true; + } + } + + } + return applies; + } + } + + private static void initializeResource () { + try { + InputStream stream = GaugesSection.class.getResourceAsStream(GAUGE_RESOURCE); + BufferedReader reader = new BufferedReader (new InputStreamReader(stream)); + String line = null; + StringBuilder builder = new StringBuilder (); + String ls = System.getProperty ("line.separator"); + while ((line = reader.readLine ()) != null) { + builder.append (line); + builder.append (ls); + } + + s_html = builder.toString (); + } + catch (IOException e) { + e.printStackTrace(); + } + } + + private IAcmeElementInstance m_element; + private Browser m_swtBrowser; + private Map> m_gaugedProperties = new LinkedHashMap<>(); + private Map> m_registeredListeners = Collections + .> synchronizedMap(new HashMap>()); + private AcmeModelInstance m_commandFactory; + private Action m_showSourceAction; + public GaugesSection () { + if (s_html == null) + initializeResource(); + } + + + @Override + public void createControl (Composite parent, int style) { + super.createControl(parent, style); +// parent.setLayoutData(GridDataFactory.fillDefaults().align(GridData.FILL, GridData.FILL).grab(true, true).create()); + getComposite ().setLayout(new FillLayout()); + getComposite ().setBackground(org.eclipse.draw2d.ColorConstants.red); + m_swtBrowser = new Browser(getComposite (), SWT.MOZILLA); + m_swtBrowser.setJavascriptEnabled(true); + + // Add hook to allow updates + new BrowserFunction(m_swtBrowser, "triggerUpdateValue") { + @Override + public Object function (Object[] arguments) { + IAcmeProperty property = m_element.getProperty((String )arguments[0]); + if (property != null) { + if (property.getProperty("operation") != null) { + IAcmeProperty operation = property.getProperty ("operation"); + Map elements = PropertyHelper.toJavaVal((IAcmeRecordValue )operation.getValue()); + List args = (List )elements.get("arguments"); + AcmeModelCommandFactory cf = m_commandFactory.getCommandFactory(); + ValuePromptDialog dialog = new ValuePromptDialog(GaugesSection.this.getComposite().getShell()); + if (dialog.open() == IDialogConstants.OK_ID) { + String val = dialog.getValue (); + try { + IRainbowModelOperation cmd = cf.generateCommand((String )elements.get("name"), m_element.getQualifiedName(), val); + IModelUSBusPort announcePort = Rainbow.getRainbowListener().getAnnouncePort (ModelHelper.getAcmeSystem(m_element).getName ()); + announcePort.updateModel(cmd); + } + catch (RainbowModelException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + return null; + } + }; + + makeActions (); + } + + @Override + public void setInput (IAcmeElement o) { + removeListeners(); + m_gaugedProperties.clear(); + m_registeredListeners.clear (); + super.setInput(o); + if (o instanceof IAcmeElementInstance) { + m_element = (IAcmeElementInstance) o; + } + + pullOutGaugeProperties(); + setupGaugeHtml (); + addListeners(); + + if (o != null) { + IAcmeSystem sys = ModelHelper.getAcmeSystem(o); + IAcmeProperty cfProp = sys.getProperty("rainbow-command-factory"); + if (cfProp != null) { + String cf = (String )PropertyHelper.toJavaVal(cfProp.getValue()); + if (cf != null) { + if (m_commandFactory == null || !cf.equals(m_commandFactory.getClass ().getName ())) { + try { + Class cfCls = Class.forName(cf); + Constructor init = cfCls.getConstructor(new Class[] {IAcmeSystem.class, String.class}); + if (init != null) { + m_commandFactory = (AcmeModelInstance )init.newInstance(sys, "AcmeStudio"); + } + } + catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException + | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + } + } + + private void setupGaugeHtml () { + if (m_element == null || m_gaugedProperties.isEmpty()) { + m_swtBrowser.setText ("

There are no gauges for this element

"); + return; + } + m_swtBrowser.setText(s_html); + + m_swtBrowser.addProgressListener(new ProgressListener() { + + @Override + public void completed (ProgressEvent event) { +// m_swtBrowser.execute("test();"); + + // Create all the gauges for the gauge properties + for (Entry> e : m_gaugedProperties.entrySet()) { + for (IAcmeProperty gaugeDescProp : e.getValue()) { + IAcmePropertyValue value = gaugeDescProp.getValue(); + String propName = e.getKey(); + if (value instanceof IAcmeRecordValue) { + IAcmeRecordValue gaugeDesc = (IAcmeRecordValue) value; + Object gaugeType = PropertyHelper.toJavaVal(gaugeDesc.getField("gauge-type").getValue()); + if ("PressureGauge".equals(gaugeType)) { + createPressureGauge(propName, gaugeDesc); + } + else if ("TrinaryGauge".equals (gaugeType)) { + createTrinaryGauge (propName, gaugeDesc); + } + else if ("MovingLineGauge".equals(gaugeType)) + createMovingLineGauge(propName, gaugeDesc); + } + } + } + } + + @Override + public void changed (ProgressEvent event) { + + } + }); + + + + + + } + + private void createTrinaryGauge (String propName, IAcmeRecordValue gaugeDesc) { + IAcmePropertyValue goodValueAcme = gaugeDesc.getField("good").getValue(); + IAcmePropertyValue badValueAcme = gaugeDesc.getField("bad").getValue(); + String good = "1"; + String bad = "-1"; + if (goodValueAcme != null) { + try { + good = LanguagePackHelper.defaultLanguageHelper().propertyValueToString(goodValueAcme, new RegionManager ()); + } + catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + if (badValueAcme != null) { + try { + bad = LanguagePackHelper.defaultLanguageHelper().propertyValueToString(badValueAcme, new RegionManager ()); + } + catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + String name = (String )PropertyHelper.toJavaVal(gaugeDesc.getField ("name").getValue ()); + String scriptCommand = "createTrinaryGauge ('" + name + "','" + propName + "', '" + good + "', '" + bad + "');"; + m_swtBrowser.execute(scriptCommand); + try { + String script = "updateGauge ('" + name + "', '" + LanguagePackHelper.defaultLanguageHelper().propertyValueToString(m_element.getProperty(propName).getValue(), new RegionManager ()) +"');"; + m_swtBrowser.execute(script); + } + catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private void createPressureGauge (String propName, IAcmeRecordValue gaugeDesc) { + IAcmeProperty gaugedProperty = m_element.getProperty(propName); + IAcmePropertyValue minValueAcme = gaugeDesc.getField("min").getValue(); + IAcmePropertyValue maxValueAcme = gaugeDesc.getField("max").getValue (); + IAcmePropertyValue redValueAcme = gaugeDesc.getField("red").getValue (); + IAcmePropertyValue yellowValueAcme = gaugeDesc.getField ("yellow").getValue (); + float minValue = minValueAcme instanceof IAcmeFloatValue?(float )PropertyHelper.toJavaVal(minValueAcme):(int)PropertyHelper.toJavaVal(minValueAcme); + float maxValue = maxValueAcme instanceof IAcmeFloatValue?(float )PropertyHelper.toJavaVal(maxValueAcme):(int )PropertyHelper.toJavaVal(maxValueAcme); + float red = -1; + if (gaugeDesc.getField("red") != null && redValueAcme != null) { + red = redValueAcme instanceof IAcmeFloatValue?(float )PropertyHelper.toJavaVal (redValueAcme):(int )PropertyHelper.toJavaVal(redValueAcme); + } + float yellow = -1; + if (gaugeDesc.getField ("yellow") != null && yellowValueAcme != null) { + yellow = yellowValueAcme instanceof IAcmeFloatValue?(float )PropertyHelper.toJavaVal(yellowValueAcme):(int )PropertyHelper.toJavaVal (yellowValueAcme); + } + String name = (String) PropertyHelper.toJavaVal(gaugeDesc.getField("name").getValue ()); + + String scriptCmd = "createPressureGauge ('" + name + "', '" + propName + "', " + Float.toString (minValue) + ", " + Float.toString (maxValue); + if (red != -1) { + scriptCmd += ", " + Float.toString(red); + if (yellow != -1) + scriptCmd += ", " + Float.toString (yellow); + } + + if (gaugedProperty.getProperty("operation") != null) { + scriptCmd += ", true"; + } + + scriptCmd += ");"; + m_swtBrowser.execute(scriptCmd); + try { + String script = "updateGauge ('" + name + "', " + LanguagePackHelper.defaultLanguageHelper().propertyValueToString(gaugedProperty.getValue(), new RegionManager ()) +");"; + m_swtBrowser.execute(script); + } + catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + private static class TriggerUpdateValueFunction extends BrowserFunction { + + private final IAcmeElementInstance m_element; + + public TriggerUpdateValueFunction(Browser browser, IAcmeElementInstance element) { + super(browser, "triggerUpdateValue"); + m_element = element; + } + + @Override + public Object function (Object[] arguments) { + IAcmeProperty property = m_element.getProperty((String )arguments[0]); + if (property != null) { + + } + return null; + } + + } + + private static class NextValueFunction extends BrowserFunction { + + protected static final String NEXT = "nextValueFor"; + private IAcmeProperty m_prop; + + public NextValueFunction(Browser swtBrowser, IAcmeProperty prop) { + super(swtBrowser, NEXT + prop.getName().replaceAll("-", "_")); + m_prop = prop; + } + + @Override + public Object function (Object[] arguments) { + if (m_prop.getValue () == null) + return null; + return PropertyHelper.toJavaVal(m_prop.getValue (), Float.class); + } + + } + + + private void createMovingLineGauge (String propName, IAcmeRecordValue gaugeDesc) { + IAcmePropertyValue minValueAcme = gaugeDesc.getField("min").getValue (); + IAcmePropertyValue maxValueAcme = gaugeDesc.getField("max").getValue (); + IAcmePropertyValue windowValueAcme = gaugeDesc.getField("window").getValue (); + IAcmePropertyValue thresholdValueAcme = gaugeDesc.getField("threshold").getValue (); + String name = (String )PropertyHelper.toJavaVal(gaugeDesc.getField("name").getValue ()); + + float min = PropertyHelper.toJavaVal(minValueAcme, Float.class); + float max = PropertyHelper.toJavaVal(maxValueAcme, Float.class); + float threshold = PropertyHelper.toJavaVal(thresholdValueAcme, Float.class); + + int window = windowValueAcme!=null?PropertyHelper.toJavaVal(windowValueAcme, Integer.class):10; + + IAcmeProperty prop = m_element.getProperty(propName); + NextValueFunction nvf = new NextValueFunction (m_swtBrowser, prop); + + String params = "{threshold:" + threshold + "}"; + String script = "createMovingLineGauge('" + name + "', '" + propName + "', " + Float.toString (min) + ", " + Float.toString (max) + ", " + window + ", " + nvf.getName () + ", " + params + ");"; + m_swtBrowser.execute(script); + + } + + private void removeListeners () { + if (m_element == null) + return; + for (Entry> entry : m_registeredListeners.entrySet()) { + IAcmeProperty property = m_element.getProperty(entry.getKey ()); + for (GaugeEventListener l : entry.getValue()) { + property.removeEventListener(l); + } + } + } + + /** + * Adds a listener to each property that fires when the value changes to + * update the gauge + */ + private void addListeners () { + if (m_element == null) + return; + for (Entry> entry : m_gaugedProperties.entrySet()) { + IAcmeProperty property = m_element.getProperty(entry.getKey ()); + Set listeners = new HashSet<> (); + for (IAcmeProperty gd : entry.getValue()) { + GaugeEventListener eu = new GaugeEventListener (property, gd, m_swtBrowser); + listeners.add (eu); + property.addEventListener(eu); + } + + } + + m_swtBrowser.addDisposeListener(new DisposeListener() { + + @Override + public void widgetDisposed (DisposeEvent e) { + removeListeners(); + } + }); + } + + private void pullOutGaugeProperties () { + if (m_element == null) + return; + Set properties = m_element.getProperties(); + for (IAcmeProperty prop : properties) { + Set gaugeDescs = pullOutGaugeDescriptions(prop); + if (!gaugeDescs.isEmpty()) + m_gaugedProperties.put(prop.getName(), gaugeDescs); + } + } + + private Set pullOutGaugeDescriptions (IAcmeProperty prop) { + Set gaugeDescs = new LinkedHashSet<>(); + for (IAcmeProperty p : prop.getProperties()) { + if (p.getType().getName().endsWith(GAUGE_DESCRIPTION_TYPE)) + gaugeDescs.add(p); + } + return gaugeDescs; + } + + @Override + public void dispose () { + super.dispose (); + if (m_swtBrowser != null) m_swtBrowser.dispose(); + m_swtBrowser = null; + removeListeners(); + } + + + private void makeActions () { + m_showSourceAction = new Action () { + @Override + public void run () { + ShowSourceDialog dialog = new ShowSourceDialog (Display.getDefault().getActiveShell(), m_swtBrowser); + dialog.open (); + } + }; + m_showSourceAction.setText ("Show source"); + } + + @Override + public IContributionItem[] getContributions () { + return new ActionContributionItem [] {new ActionContributionItem(m_showSourceAction)}; + } + + + @Override + public void addItemSelectionListener (SelectionListener listener) { + + } + + + +} diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugesSectionAdapter.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugesSectionAdapter.java index 756418e9d..e811fdc09 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugesSectionAdapter.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/GaugesSectionAdapter.java @@ -1,17 +1,17 @@ -package org.acmestudio.rainbow.ui.part; - -import org.acmestudio.ui.view.element.ElementViewPart; -import org.acmestudio.ui.view.property.AbstractElementViewPartSectionAdapter; - -public class GaugesSectionAdapter extends AbstractElementViewPartSectionAdapter { - - public GaugesSectionAdapter() { - super (); - } - - @Override - public ElementViewPart createElementViewPart () { - return new GaugesSection(); - } - -} +package org.acmestudio.rainbow.ui.part; + +import org.acmestudio.ui.view.element.ElementViewPart; +import org.acmestudio.ui.view.property.AbstractElementViewPartSectionAdapter; + +public class GaugesSectionAdapter extends AbstractElementViewPartSectionAdapter { + + public GaugesSectionAdapter() { + super (); + } + + @Override + public ElementViewPart createElementViewPart () { + return new GaugesSection(); + } + +} diff --git a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/ValuePromptDialog.java b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/ValuePromptDialog.java index ae79046ca..4d1693277 100644 --- a/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/ValuePromptDialog.java +++ b/ide/org.acmestudio.rainbow/src/org/acmestudio/rainbow/ui/part/ValuePromptDialog.java @@ -1,82 +1,82 @@ -package org.acmestudio.rainbow.ui.part; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.layout.FormLayout; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.SWT; -import org.eclipse.swt.layout.FormData; -import org.eclipse.swt.layout.FormAttachment; -import org.eclipse.swt.widgets.Text; - -public class ValuePromptDialog extends Dialog { - private Text m_text; - private String m_textValue; - - /** - * Create the dialog. - * @param parentShell - */ - public ValuePromptDialog(Shell parentShell) { - super(parentShell); - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea (Composite parent) { - Composite container = (Composite) super.createDialogArea(parent); - container.setLayout(new FormLayout()); - - Label lblEnterValue = new Label(container, SWT.NONE); - FormData fd_lblEnterValue = new FormData(); - fd_lblEnterValue.top = new FormAttachment(0, 10); - fd_lblEnterValue.left = new FormAttachment(0, 10); - lblEnterValue.setLayoutData(fd_lblEnterValue); - lblEnterValue.setText("Enter value:"); - - m_text = new Text(container, SWT.BORDER); - FormData fd_text = new FormData(); - fd_text.top = new FormAttachment(0, 10); - fd_text.left = new FormAttachment(lblEnterValue, 6); - fd_text.right = new FormAttachment(100, -10); - m_text.setLayoutData(fd_text); - - return container; - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar (Composite parent) { - createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - } - - /** - * Return the initial size of the dialog. - */ - @Override - protected Point getInitialSize () { - return new Point(450, 115); - } - - @Override - protected void okPressed () { - m_textValue = m_text.getText(); - super.okPressed(); - } - - public String getValue () { - return m_textValue; - } -} +package org.acmestudio.rainbow.ui.part; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.layout.FormLayout; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.FormData; +import org.eclipse.swt.layout.FormAttachment; +import org.eclipse.swt.widgets.Text; + +public class ValuePromptDialog extends Dialog { + private Text m_text; + private String m_textValue; + + /** + * Create the dialog. + * @param parentShell + */ + public ValuePromptDialog(Shell parentShell) { + super(parentShell); + } + + /** + * Create contents of the dialog. + * @param parent + */ + @Override + protected Control createDialogArea (Composite parent) { + Composite container = (Composite) super.createDialogArea(parent); + container.setLayout(new FormLayout()); + + Label lblEnterValue = new Label(container, SWT.NONE); + FormData fd_lblEnterValue = new FormData(); + fd_lblEnterValue.top = new FormAttachment(0, 10); + fd_lblEnterValue.left = new FormAttachment(0, 10); + lblEnterValue.setLayoutData(fd_lblEnterValue); + lblEnterValue.setText("Enter value:"); + + m_text = new Text(container, SWT.BORDER); + FormData fd_text = new FormData(); + fd_text.top = new FormAttachment(0, 10); + fd_text.left = new FormAttachment(lblEnterValue, 6); + fd_text.right = new FormAttachment(100, -10); + m_text.setLayoutData(fd_text); + + return container; + } + + /** + * Create contents of the button bar. + * @param parent + */ + @Override + protected void createButtonsForButtonBar (Composite parent) { + createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + } + + /** + * Return the initial size of the dialog. + */ + @Override + protected Point getInitialSize () { + return new Point(450, 115); + } + + @Override + protected void okPressed () { + m_textValue = m_text.getText(); + super.okPressed(); + } + + public String getValue () { + return m_textValue; + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/.gitignore b/ide/org.sa.rainbow.configuration.parent/.gitignore new file mode 100644 index 000000000..1c8923942 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/.gitignore @@ -0,0 +1,3 @@ +**/src-gen +**/xtend-gen +**/target/* diff --git a/ide/org.sa.rainbow.configuration.parent/.project b/ide/org.sa.rainbow.configuration.parent/.project new file mode 100644 index 000000000..f4641b300 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/.project @@ -0,0 +1,17 @@ + + + org.sa.rainbow.configuration.parent + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/ide/org.sa.rainbow.configuration.parent/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.configuration.parent/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/.project b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/.project new file mode 100644 index 000000000..27426fb0a --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/.project @@ -0,0 +1,23 @@ + + + org.sa.rainbow.configuration.feature + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.pde.FeatureBuilder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.FeatureNature + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/build.properties b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/build.properties new file mode 100644 index 000000000..64f93a9f0 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/build.properties @@ -0,0 +1 @@ +bin.includes = feature.xml diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/feature.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/feature.xml new file mode 100644 index 000000000..28d9a1bd4 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/feature.xml @@ -0,0 +1,51 @@ + + + + + The configuration DSL for Rainbow as an Eclipse Plugin. + + + + Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/pom.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/pom.xml new file mode 100644 index 000000000..46b52e42b --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.feature/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + + org.sa.rainbow.configuration + org.sa.rainbow.configuration.parent + 1.0.1-SNAPSHOT + + org.sa.rainbow.configuration.feature + eclipse-feature + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.classpath b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.classpath new file mode 100644 index 000000000..8d26fa598 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.project b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.project new file mode 100644 index 000000000..b2725dcec --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.project @@ -0,0 +1,40 @@ + + + org.sa.rainbow.configuration.ide + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.xtext.ui.shared.xtextNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.PluginNature + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.settings/org.eclipse.jdt.core.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..0c68a61dc --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/META-INF/MANIFEST.MF b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/META-INF/MANIFEST.MF new file mode 100644 index 000000000..9447fd91a --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/META-INF/MANIFEST.MF @@ -0,0 +1,16 @@ +Manifest-Version: 1.0 +Automatic-Module-Name: org.sa.rainbow.configuration.ide +Bundle-ManifestVersion: 2 +Bundle-Name: org.sa.rainbow.configuration.ide +Bundle-Vendor: My Company +Bundle-Version: 1.0.1.qualifier +Bundle-SymbolicName: org.sa.rainbow.configuration.ide; singleton:=true +Bundle-ActivationPolicy: lazy +Require-Bundle: org.sa.rainbow.configuration, + org.eclipse.xtext.ide, + org.eclipse.xtext.xbase.ide, + org.antlr.runtime;bundle-version="[3.2.0,3.2.1)" +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Export-Package: org.sa.rainbow.configuration.ide, + org.sa.rainbow.configuration.ide.contentassist.antlr, + org.sa.rainbow.configuration.ide.contentassist.antlr.internal diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/build.properties b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/build.properties new file mode 100644 index 000000000..5c6bbf99f --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/build.properties @@ -0,0 +1,6 @@ +source.. = src/,\ + src-gen/,\ + xtend-gen/ +bin.includes = .,\ + META-INF/ +bin.excludes = **/*.xtend diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/pom.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/pom.xml new file mode 100644 index 000000000..38c0e7eed --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/pom.xml @@ -0,0 +1,21 @@ + + 4.0.0 + + org.sa.rainbow.configuration + org.sa.rainbow.configuration.parent + 1.0.1-SNAPSHOT + + org.sa.rainbow.configuration.ide + eclipse-plugin + + + + + org.eclipse.xtend + xtend-maven-plugin + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/src/org/sa/rainbow/configuration/ide/RclIdeModule.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/src/org/sa/rainbow/configuration/ide/RclIdeModule.xtend new file mode 100644 index 000000000..544301204 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/src/org/sa/rainbow/configuration/ide/RclIdeModule.xtend @@ -0,0 +1,15 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.ide + +/** + * Use this class to register ide components. + */ +class RclIdeModule extends AbstractRclIdeModule { + +// override configure(Binder binder) { +// super.configure(binder) +// } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/src/org/sa/rainbow/configuration/ide/RclIdeSetup.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/src/org/sa/rainbow/configuration/ide/RclIdeSetup.xtend new file mode 100644 index 000000000..2f35bfef9 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ide/src/org/sa/rainbow/configuration/ide/RclIdeSetup.xtend @@ -0,0 +1,20 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.ide + +import com.google.inject.Guice +import org.eclipse.xtext.util.Modules2 +import org.sa.rainbow.configuration.RclRuntimeModule +import org.sa.rainbow.configuration.RclStandaloneSetup + +/** + * Initialization support for running Xtext languages as language servers. + */ +class RclIdeSetup extends RclStandaloneSetup { + + override createInjector() { + Guice.createInjector(Modules2.mixin(new RclRuntimeModule, new RclIdeModule)) + } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/.project b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/.project new file mode 100644 index 000000000..1020917d8 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/.project @@ -0,0 +1,17 @@ + + + org.sa.rainbow.configuration.repository + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/category.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/category.xml new file mode 100644 index 000000000..d7fb87024 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/category.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/pom.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/pom.xml new file mode 100644 index 000000000..34e9b196d --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.repository/pom.xml @@ -0,0 +1,51 @@ + + 4.0.0 + + org.sa.rainbow.configuration + org.sa.rainbow.configuration.parent + 1.0.1-SNAPSHOT + + org.sa.rainbow.configuration.repository + eclipse-repository + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-clean-plugin + + + [2.5,) + + + clean + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/.project b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/.project new file mode 100644 index 000000000..8c2248fc5 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/.project @@ -0,0 +1,17 @@ + + + org.sa.rainbow.configuration.target + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/org.sa.rainbow.configuration.target.target b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/org.sa.rainbow.configuration.target.target new file mode 100644 index 000000000..f89581997 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/org.sa.rainbow.configuration.target.target @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/pom.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/pom.xml new file mode 100644 index 000000000..78999920d --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.target/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + + org.sa.rainbow.configuration + org.sa.rainbow.configuration.parent + 1.0.1-SNAPSHOT + + org.sa.rainbow.configuration.target + eclipse-target-definition + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.classpath b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.classpath new file mode 100644 index 000000000..e08907a80 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.classpath @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.project b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.project new file mode 100644 index 000000000..ce8c27ec6 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.project @@ -0,0 +1,40 @@ + + + org.sa.rainbow.configuration.tests + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.xtext.ui.shared.xtextNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.PluginNature + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.settings/org.eclipse.jdt.core.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..0c68a61dc --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/META-INF/MANIFEST.MF b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/META-INF/MANIFEST.MF new file mode 100644 index 000000000..ec238ebee --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/META-INF/MANIFEST.MF @@ -0,0 +1,17 @@ +Manifest-Version: 1.0 +Automatic-Module-Name: org.sa.rainbow.configuration.tests +Bundle-ManifestVersion: 2 +Bundle-Name: org.sa.rainbow.configuration.tests +Bundle-Vendor: My Company +Bundle-Version: 1.0.1.qualifier +Bundle-SymbolicName: org.sa.rainbow.configuration.tests; singleton:=true +Bundle-ActivationPolicy: lazy +Require-Bundle: org.sa.rainbow.configuration, + org.junit.jupiter.api;bundle-version="[5.0.0,6.0.0)", + org.eclipse.xtext.testing, + org.eclipse.xtext.xbase.testing, + org.eclipse.xtext.xbase.lib;bundle-version="2.14.0", + org.objectweb.asm;bundle-version="[7.1.0,7.2.0)";resolution:=optional, + org.sa.rainbow.stitch.ui;bundle-version="1.0.0" +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Export-Package: org.sa.rainbow.configuration.tests;x-internal=true diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/build.properties b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/build.properties new file mode 100644 index 000000000..5c6bbf99f --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/build.properties @@ -0,0 +1,6 @@ +source.. = src/,\ + src-gen/,\ + xtend-gen/ +bin.includes = .,\ + META-INF/ +bin.excludes = **/*.xtend diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/pom.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/pom.xml new file mode 100644 index 000000000..2ddacb1f8 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/pom.xml @@ -0,0 +1,21 @@ + + 4.0.0 + + org.sa.rainbow.configuration + org.sa.rainbow.configuration.parent + 1.0.1-SNAPSHOT + + org.sa.rainbow.configuration.tests + eclipse-test-plugin + + + + + org.eclipse.xtend + xtend-maven-plugin + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/src/org/sa/rainbow/configuration/tests/RclParsingTest.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/src/org/sa/rainbow/configuration/tests/RclParsingTest.xtend new file mode 100644 index 000000000..4d9eaa0f7 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.tests/src/org/sa/rainbow/configuration/tests/RclParsingTest.xtend @@ -0,0 +1,30 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.tests + +import com.google.inject.Inject +import org.eclipse.xtext.testing.InjectWith +import org.eclipse.xtext.testing.extensions.InjectionExtension +import org.eclipse.xtext.testing.util.ParseHelper +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.^extension.ExtendWith +import org.sa.rainbow.configuration.rcl.RainbowConfiguration + +@ExtendWith(InjectionExtension) +@InjectWith(RclInjectorProvider) +class RclParsingTest { + @Inject + ParseHelper parseHelper + + @Test + def void loadModel() { + val result = parseHelper.parse(''' + target test + ''') + Assertions.assertNotNull(result) + val errors = result.eResource.errors + Assertions.assertTrue(errors.isEmpty, '''Unexpected errors: «errors.join(", ")»''') + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.classpath b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.classpath new file mode 100644 index 000000000..e08907a80 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.classpath @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.project b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.project new file mode 100644 index 000000000..74136f3aa --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.project @@ -0,0 +1,40 @@ + + + org.sa.rainbow.configuration.ui.tests + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.xtext.ui.shared.xtextNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.PluginNature + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.settings/org.eclipse.jdt.core.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..0c68a61dc --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/META-INF/MANIFEST.MF b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/META-INF/MANIFEST.MF new file mode 100644 index 000000000..c6ce9636a --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/META-INF/MANIFEST.MF @@ -0,0 +1,18 @@ +Manifest-Version: 1.0 +Automatic-Module-Name: org.sa.rainbow.configuration.ui.tests +Bundle-ManifestVersion: 2 +Bundle-Name: org.sa.rainbow.configuration.ui.tests +Bundle-Vendor: My Company +Bundle-Version: 1.0.1.qualifier +Bundle-SymbolicName: org.sa.rainbow.configuration.ui.tests; singleton:=true +Bundle-ActivationPolicy: lazy +Require-Bundle: org.sa.rainbow.configuration.ui, + org.junit.jupiter.api;bundle-version="[5.0.0,6.0.0)", + org.eclipse.xtext.testing, + org.eclipse.xtext.xbase.testing, + org.eclipse.xtext.xbase.junit, + org.eclipse.core.runtime, + org.eclipse.xtext.ui.testing, + org.eclipse.ui.workbench;resolution:=optional +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Export-Package: org.sa.rainbow.configuration.ui.tests;x-internal=true diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/build.properties b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/build.properties new file mode 100644 index 000000000..5c6bbf99f --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/build.properties @@ -0,0 +1,6 @@ +source.. = src/,\ + src-gen/,\ + xtend-gen/ +bin.includes = .,\ + META-INF/ +bin.excludes = **/*.xtend diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/pom.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/pom.xml new file mode 100644 index 000000000..d231d3ff5 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui.tests/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + + org.sa.rainbow.configuration + org.sa.rainbow.configuration.parent + 1.0.1-SNAPSHOT + + org.sa.rainbow.configuration.ui.tests + eclipse-test-plugin + + + + + org.eclipse.xtend + xtend-maven-plugin + + + org.eclipse.tycho + tycho-surefire-plugin + + true + + + + org.eclipse.tycho + target-platform-configuration + + + + + + eclipse-feature + org.eclipse.rcp + 0.0.0 + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.classpath b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.classpath new file mode 100644 index 000000000..8d26fa598 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.project b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.project new file mode 100644 index 000000000..a6eb321e9 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.project @@ -0,0 +1,40 @@ + + + org.sa.rainbow.configuration.ui + + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.xtext.ui.shared.xtextNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.PluginNature + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.settings/org.eclipse.jdt.core.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..0c68a61dc --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/META-INF/MANIFEST.MF b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/META-INF/MANIFEST.MF new file mode 100644 index 000000000..83edce840 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/META-INF/MANIFEST.MF @@ -0,0 +1,51 @@ +Manifest-Version: 1.0 +Automatic-Module-Name: org.sa.rainbow.configuration.ui +Bundle-ManifestVersion: 2 +Bundle-Name: org.sa.rainbow.configuration.ui +Bundle-Vendor: My Company +Bundle-Version: 1.0.1.qualifier +Bundle-SymbolicName: org.sa.rainbow.configuration.ui; singleton:=true +Bundle-ActivationPolicy: lazy +Require-Bundle: org.sa.rainbow.configuration, + org.sa.rainbow.configuration.ide, + org.eclipse.xtext.ui, + org.eclipse.xtext.ui.shared, + org.eclipse.xtext.ui.codetemplates.ui, + org.eclipse.ui.editors;bundle-version="3.5.0", + org.eclipse.ui.ide;bundle-version="3.5.0", + org.eclipse.ui, + org.eclipse.compare, + org.eclipse.xtext.builder, + org.eclipse.xtext.xbase.lib;bundle-version="2.14.0", + org.eclipse.xtend.lib;bundle-version="2.14.0";resolution:=optional, + org.eclipse.xtext.xbase.ui, + org.eclipse.xtext.common.types.ui, + org.sa.rainbow.stitch;bundle-version="1.0.0", + org.eclipse.core.runtime, + org.eclipse.core.resources, + org.eclipse.ui.forms, + org.eclipse.jdt.core, + org.acme.xtext;bundle-version="1.0.0" +Import-Package: org.apache.log4j, + org.eclipse.xtext.ui.codemining;resolution:=optional +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Export-Package: org.sa.rainbow.configuration.ui;uses:="com.google.inject,com.google.inject.binder,org.eclipse.ui.plugin", + org.sa.rainbow.configuration.ui.commands;uses:="org.eclipse.core.commands", + org.sa.rainbow.configuration.ui.contentassist; + uses:="org.eclipse.emf.ecore, + com.google.common.base, + org.eclipse.xtext.ide.editor.bracketmatching, + org.eclipse.xtext.ui.editor.contentassist, + org.eclipse.xtext", + org.sa.rainbow.configuration.ui.internal;uses:="org.osgi.framework,com.google.inject,org.eclipse.ui.plugin", + org.sa.rainbow.configuration.ui.labeling, + org.sa.rainbow.configuration.ui.outline, + org.sa.rainbow.configuration.ui.quickfix;uses:="org.eclipse.xtext.validation,org.eclipse.xtext.ui.editor.quickfix", + org.sa.rainbow.configuration.ui.wizard;uses:="org.eclipse.core.runtime,org.eclipse.xtext.ui.wizard.template" +Bundle-Activator: org.sa.rainbow.configuration.ui.ConfigurationActivator +Bundle-ClassPath: ., + lib/rainbow-acme-model.jar, + lib/rainbow-core.jar, + lib/rainbow-gui.jar, + lib/rainbow-stitch.jar, + lib/rainbow-utility-model.jar diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/build.properties b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/build.properties new file mode 100644 index 000000000..126061132 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/build.properties @@ -0,0 +1,14 @@ +source.. = src/,\ + src-gen/,\ + xtend-gen/ +bin.includes = .,\ + META-INF/,\ + plugin.xml,\ + templates/,\ + icons/,\ + lib/rainbow-acme-model.jar,\ + lib/rainbow-core.jar,\ + lib/rainbow-gui.jar,\ + lib/rainbow-stitch.jar,\ + lib/rainbow-utility-model.jar +bin.excludes = **/*.xtend diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/file_template.png b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/file_template.png new file mode 100644 index 000000000..0c6391789 Binary files /dev/null and b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/file_template.png differ diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_ConfigModel_file.png b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_ConfigModel_file.png new file mode 100644 index 000000000..4bd4eadb2 Binary files /dev/null and b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_ConfigModel_file.png differ diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_ConfigModel_proj.gif b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_ConfigModel_proj.gif new file mode 100644 index 000000000..984bc9139 Binary files /dev/null and b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_ConfigModel_proj.gif differ diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_RCL_file.png b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_RCL_file.png new file mode 100644 index 000000000..4bd4eadb2 Binary files /dev/null and b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_RCL_file.png differ diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_RCL_proj.gif b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_RCL_proj.gif new file mode 100644 index 000000000..984bc9139 Binary files /dev/null and b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/new_RCL_proj.gif differ diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/project_template.png b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/project_template.png new file mode 100644 index 000000000..fddcb8c4e Binary files /dev/null and b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/project_template.png differ diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/rbw.png b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/rbw.png new file mode 100644 index 000000000..ef4f3d3b8 Binary files /dev/null and b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/icons/rbw.png differ diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/plugin.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/plugin.xml new file mode 100644 index 000000000..9d133577d --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/plugin.xml @@ -0,0 +1,592 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/pom.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/pom.xml new file mode 100644 index 000000000..7bddb8d50 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/pom.xml @@ -0,0 +1,91 @@ + + 4.0.0 + + org.sa.rainbow.configuration + org.sa.rainbow.configuration.parent + 1.0.1-SNAPSHOT + + org.sa.rainbow.configuration.ui + eclipse-plugin + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libraries + initialize + + copy + + + ${basedir}/lib/ + true + true + true + true + + + rainbow + rainbow-core + ${rainbowVersion} + + + rainbow + rainbow-utility-model + ${rainbowVersion} + + + rainbow + rainbow-gui + ${rainbowVersion} + + + rainbow + rainbow-acme-model + ${rainbowVersion} + + + rainbow + rainbow-stitch + ${rainbowVersion} + + + org.acme.xtext + org.acme.xtext + 1.0.0-SNAPSHOT + + + + + + + + org.eclipse.xtend + xtend-maven-plugin + + + + + + + rainbow + rainbow-core + ${rainbowVersion} + + + rainbow + rainbow-acme-model + ${rainbowVersion} + + + org.sa.rainbow.configuration + org.sa.rainbow.configuration + 1.0.1-SNAPSHOT + eclipse-plugin + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/AutoEditStrategyProvider.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/AutoEditStrategyProvider.java new file mode 100644 index 000000000..841664bb1 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/AutoEditStrategyProvider.java @@ -0,0 +1,30 @@ +package org.sa.rainbow.configuration.ui; +import org.eclipse.jface.text.IDocument; +import org.eclipse.xtext.ui.editor.autoedit.DefaultAutoEditStrategyProvider; + +public class AutoEditStrategyProvider extends DefaultAutoEditStrategyProvider { + + + + @Override + protected void configure(IEditStrategyAcceptor acceptor) { + super.configure(acceptor); + configurePropertyReference(acceptor); + } + + private void configurePropertyReference(IEditStrategyAcceptor acceptor) { + acceptor.accept(singleLineTerminals.newInstance("\u00AB\u00AB", "\u00BB\u00BB"), IDocument.DEFAULT_CONTENT_TYPE); + acceptor.accept(partitionDeletion.newInstance("\\u00AB\\u00AB", "u00BB\u00BB"), IDocument.DEFAULT_CONTENT_TYPE); + } + + @Override + protected void configureStringLiteral(IEditStrategyAcceptor acceptor) { +// super.configureStringLiteral(acceptor); + acceptor.accept(partitionInsert.newInstance("\"","\""), TokenTypeToPartitionMapper.RICH_STRING_LITERAL_PARTITION); + acceptor.accept(partitionInsert.newInstance("\u00AB","\u00BB"), TokenTypeToPartitionMapper.RICH_STRING_LITERAL_PARTITION); + acceptor.accept(partitionDeletion.newInstance("\u00AB","\u00BB"), TokenTypeToPartitionMapper.RICH_STRING_LITERAL_PARTITION); + acceptor.accept(singleLineTerminals.newInstance("\u00AB","\u00BB"), IDocument.DEFAULT_CONTENT_TYPE); + } + + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/ConfigurationActivator.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/ConfigurationActivator.java new file mode 100644 index 000000000..aa544e4c8 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/ConfigurationActivator.java @@ -0,0 +1,24 @@ +package org.sa.rainbow.configuration.ui; + +public class ConfigurationActivator extends org.sa.rainbow.configuration.ui.internal.ConfigurationActivator { + + public ConfigurationActivator() { + super(); + } + + /* + * @Override protected Injector createInjector(String language) { Injector + * injector = super.createInjector(language); if + * (!EPackage.Registry.INSTANCE.containsKey( + * "http://www.sa.org/rainbow/stitch/Stitch")) { + * EPackage.Registry.INSTANCE.put("http://www.sa.org/rainbow/stitch/Stitch", + * StitchPackage.eINSTANCE); } IResourceFactory resourceFactory = + * injector.getInstance(IResourceFactory.class); IResourceServiceProvider + * serviceProvider = injector.getInstance(IResourceServiceProvider.class); + * Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap ().put("s", + * resourceFactory); + * IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put( + * "s", serviceProvider); return injector; } + */ + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/FontManager.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/FontManager.java new file mode 100644 index 000000000..6c6b63327 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/FontManager.java @@ -0,0 +1,30 @@ +package org.sa.rainbow.configuration.ui; + +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.widgets.Display; + + +public class FontManager { + + + static private Map s_fontMap; + + + protected FontManager() {} + + public static Font getFont(String name, int size, int style) { + String key = name + size + style; + if (s_fontMap == null) s_fontMap = new HashMap<>(); + Font f = s_fontMap.get(key); + if (f == null) { + FontData fd = new FontData(name, size, style); + f = new Font(Display.getDefault(), fd); + s_fontMap.put(key, f); + } + return f; + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RainbowBracePairsProvider.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RainbowBracePairsProvider.xtend new file mode 100644 index 000000000..1b6144da8 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RainbowBracePairsProvider.xtend @@ -0,0 +1,27 @@ +package org.sa.rainbow.configuration.ui + +import com.google.inject.Singleton +import java.util.Set +import org.eclipse.xtend.lib.annotations.Accessors +import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor +import org.eclipse.xtext.ide.editor.bracketmatching.BracePair +import org.eclipse.xtext.ide.editor.bracketmatching.IBracePairProvider + +@Singleton +@Accessors +@FinalFieldsConstructor +class RainbowBracePairsProvider implements IBracePairProvider { + + val Set pairs + + + new() { + this(#{ + new BracePair("(", ")", true), + new BracePair("{", "}", true), + new BracePair("[", "]", true)//, +// new BracePair("\u00AB", "\u00BB", true) + }) + } + +} \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHighlighter.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHighlighter.java new file mode 100644 index 000000000..b25b31193 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHighlighter.java @@ -0,0 +1,160 @@ +package org.sa.rainbow.configuration.ui; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import java.util.Collections; +import java.util.Set; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.xtext.EcoreUtil2; +import org.eclipse.xtext.ide.editor.syntaxcoloring.DefaultSemanticHighlightingCalculator; +import org.eclipse.xtext.ide.editor.syntaxcoloring.IHighlightedPositionAcceptor; +import org.eclipse.xtext.nodemodel.INode; +import org.eclipse.xtext.nodemodel.util.NodeModelUtils; +import org.eclipse.xtext.resource.XtextResource; +import org.eclipse.xtext.ui.editor.syntaxcoloring.DefaultHighlightingConfiguration; +import org.eclipse.xtext.util.CancelIndicator; +import org.sa.rainbow.configuration.ConfigAttributeConstants; +import org.sa.rainbow.configuration.XtendUtils; +import org.sa.rainbow.configuration.rcl.Assignment; +import org.sa.rainbow.configuration.rcl.Component; +import org.sa.rainbow.configuration.rcl.DeclaredProperty; +import org.sa.rainbow.configuration.rcl.Effector; +import org.sa.rainbow.configuration.rcl.Gauge; +import org.sa.rainbow.configuration.rcl.GaugeTypeBody; +import org.sa.rainbow.configuration.rcl.Probe; +import org.sa.rainbow.configuration.rcl.RclPackage; +import org.sa.rainbow.configuration.rcl.RichStringLiteral; +import org.sa.rainbow.configuration.rcl.RichStringPart; + +public class RclHighlighter extends DefaultSemanticHighlightingCalculator { + @Override + protected void doProvideHighlightingFor(XtextResource resource, IHighlightedPositionAcceptor acceptor, + CancelIndicator cancelIndicator) { + EObject rootObject = resource.getParseResult().getRootASTElement(); + + for (RichStringLiteral rs : EcoreUtil2.getAllContentsOfType(rootObject, RichStringLiteral.class)) { + for (INode node : NodeModelUtils.findNodesForFeature(rs, RclPackage.Literals.RICH_STRING_LITERAL__VALUE)) { + acceptor.addPosition(node.getOffset(), node.getLength(), DefaultHighlightingConfiguration.STRING_ID); + } + } + for (RichStringPart rs : EcoreUtil2.getAllContentsOfType(rootObject,RichStringPart.class)) { + for (INode node : NodeModelUtils.findNodesForFeature(rs, RclPackage.Literals.RICH_STRING_PART__REFERABLE)) { + acceptor.addPosition(node.getOffset(), node.getLength(), RclHighlightingConfiguration.PROPERTY_REFERENCE_ID); + } + } + for (Gauge g : EcoreUtil2.getAllContentsOfType(rootObject, Gauge.class)) { + for (Assignment a : EcoreUtil2.getAllContentsOfType(g, Assignment.class)) { +// if (a.eContainer().eContainer() instanceof Gauge) { + if (ConfigAttributeConstants.GAUGE_KEYWORDS.contains(a.getName())) { + for (INode node : NodeModelUtils.findNodesForFeature(a, RclPackage.Literals.ASSIGNMENT__NAME)) { + acceptor.addPosition(node.getOffset(), node.getLength(), RclHighlightingConfiguration.SOFT_KEYWORD_ID); + } + } +// } + } + } + for (GaugeTypeBody g : EcoreUtil2.getAllContentsOfType(rootObject, GaugeTypeBody.class)) { + for (Assignment a : EcoreUtil2.getAllContentsOfType(g, Assignment.class)) { +// if (a.eContainer().eContainer() instanceof Gauge) { + if (ConfigAttributeConstants.GAUGE_KEYWORDS.contains(a.getName())) { + for (INode node : NodeModelUtils.findNodesForFeature(a, RclPackage.Literals.ASSIGNMENT__NAME)) { + acceptor.addPosition(node.getOffset(), node.getLength(), RclHighlightingConfiguration.SOFT_KEYWORD_ID); + } + } +// } + } + } + for (Probe g : EcoreUtil2.getAllContentsOfType(rootObject, Probe.class)) { + for (Assignment a : EcoreUtil2.getAllContentsOfType(g, Assignment.class)) { +// if (a.eContainer().eContainer() instanceof Gauge) { + if (ConfigAttributeConstants.PROBE_KEYWORDS.contains(a.getName())) { + for (INode node : NodeModelUtils.findNodesForFeature(a, RclPackage.Literals.ASSIGNMENT__NAME)) { + acceptor.addPosition(node.getOffset(), node.getLength(), RclHighlightingConfiguration.SOFT_KEYWORD_ID); + } + } +// } + } + } + for (Effector e : EcoreUtil2.getAllContentsOfType(rootObject, Effector.class)) { + for (Assignment a : EcoreUtil2.getAllContentsOfType(e, Assignment.class)) { + if (ConfigAttributeConstants.EFFECTOR_KEYOWRDS.contains(a.getName())) { + for (INode node : NodeModelUtils.findNodesForFeature(a, RclPackage.Literals.ASSIGNMENT__NAME)) { + acceptor.addPosition(node.getOffset(), node.getLength(), RclHighlightingConfiguration.SOFT_KEYWORD_ID); + } + } + } + } + for (Component c : EcoreUtil2.getAllContentsOfType(rootObject, Component.class)) { + DeclaredProperty p = EcoreUtil2.getContainerOfType(c, DeclaredProperty.class); + if (p != null) { + for (Assignment a : EcoreUtil2.getAllContentsOfType(p, Assignment.class)) { + Set kw = Collections.emptySet(); + switch (p.getComponent()) { + case ANALYSIS: + kw = ConfigAttributeConstants.ANALYSIS_KEYWORDS; + highlightSoftKeyword(acceptor, a, kw); + break; + case EFFECTORMANAGER: + kw = ConfigAttributeConstants.EFFECTOR_MANAGER_KEYWORDS; + highlightSoftKeyword(acceptor, a, kw); + break; + case EXECUTOR: + kw = ConfigAttributeConstants.EXECUTOR_KEYWORDS; + highlightSoftKeyword(acceptor, a, kw); + break; + case GUI: + if (XtendUtils.isKeyProperty(ConfigAttributeConstants.GUI_PROPERTY_TUPES, a)) { + for (INode node : NodeModelUtils.findNodesForFeature(a, RclPackage.Literals.ASSIGNMENT__NAME)) { + acceptor.addPosition(node.getOffset(), node.getLength(), RclHighlightingConfiguration.SOFT_KEYWORD_ID); + } + } + break; + case MANAGER: + kw = ConfigAttributeConstants.MANAGER_KEYWORDS; + highlightSoftKeyword(acceptor, a, kw); + break; + case MODEL: + kw = ConfigAttributeConstants.MODEL_KEYWORDS; + highlightSoftKeyword(acceptor, a, kw); + break; + case UTILITY: + kw = ConfigAttributeConstants.UTILITY_KEYWORDS; + highlightSoftKeyword(acceptor, a, kw); + case PROPERTY: + break; + default: + ; + + } + } + } + + } + super.doProvideHighlightingFor(resource, acceptor, cancelIndicator); + } + + protected void highlightSoftKeyword(IHighlightedPositionAcceptor acceptor, Assignment a, Set kw) { + if (kw.contains(a.getName())) { + for (INode node : NodeModelUtils.findNodesForFeature(a, RclPackage.Literals.ASSIGNMENT__NAME)) { + acceptor.addPosition(node.getOffset(), node.getLength(), RclHighlightingConfiguration.SOFT_KEYWORD_ID); + } + } + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHighlightingConfiguration.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHighlightingConfiguration.java new file mode 100644 index 000000000..6337206f4 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHighlightingConfiguration.java @@ -0,0 +1,48 @@ +package org.sa.rainbow.configuration.ui; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import org.eclipse.swt.SWT; +import org.eclipse.xtext.ui.editor.syntaxcoloring.DefaultHighlightingConfiguration; +import org.eclipse.xtext.ui.editor.syntaxcoloring.IHighlightingConfigurationAcceptor; +import org.eclipse.xtext.ui.editor.utils.TextStyle; + +public class RclHighlightingConfiguration extends DefaultHighlightingConfiguration { + public static final String SOFT_KEYWORD_ID = "SoftKeyword"; + public static final String PROPERTY_REFERENCE_ID = "PropertyReference"; + + @Override + public void configure(IHighlightingConfigurationAcceptor acceptor) { + super.configure(acceptor); + acceptor.acceptDefaultHighlighting(PROPERTY_REFERENCE_ID, "Property Reference", propertyReferenceStyle()); + acceptor.acceptDefaultHighlighting(SOFT_KEYWORD_ID, "Soft Keyword", softKeywordStyle()); + } + + private TextStyle propertyReferenceStyle() { + TextStyle s = stringTextStyle(); + s.setStyle(SWT.ITALIC); + return s; + } + + private TextStyle softKeywordStyle() { + TextStyle s = keywordTextStyle(); + s.setStyle(SWT.NORMAL); + return s; + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHyperlinkDetector.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHyperlinkDetector.java new file mode 100644 index 000000000..ad0b55d77 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHyperlinkDetector.java @@ -0,0 +1,67 @@ +package org.sa.rainbow.configuration.ui; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.hyperlink.IHyperlink; +import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.xtext.resource.XtextResource; +import org.eclipse.xtext.ui.editor.ISourceViewerAware; +import org.eclipse.xtext.ui.editor.hyperlinking.IHyperlinkHelper; +import org.eclipse.xtext.ui.editor.model.XtextDocumentUtil; +import org.eclipse.xtext.util.concurrent.IUnitOfWork; + +import com.google.inject.Inject; + +public class RclHyperlinkDetector implements IHyperlinkDetector { + @Inject + private IHyperlinkHelper helper; + + /** + * @since 2.19 + */ + @Inject + private XtextDocumentUtil xtextDocumentUtil; + + public RclHyperlinkDetector() { + } + + @Override + public IHyperlink[] detectHyperlinks(final ITextViewer textViewer, final IRegion region, final boolean canShowMultipleHyperlinks) { + return xtextDocumentUtil.getXtextDocument(textViewer).tryReadOnly(new IUnitOfWork() { + @Override + public IHyperlink[] exec(XtextResource resource) throws Exception { + if (helper instanceof ISourceViewerAware && textViewer instanceof ISourceViewer) { + ((ISourceViewerAware) helper).setSourceViewer((ISourceViewer) textViewer); + } + return helper.createHyperlinksByOffset(resource, region.getOffset(), canShowMultipleHyperlinks); + } + }); + } + + public void setHelper(IHyperlinkHelper helper) { + this.helper = helper; + } + + public IHyperlinkHelper getHelper() { + return helper; + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHyperlinkHelper.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHyperlinkHelper.java new file mode 100644 index 000000000..b88b6f377 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclHyperlinkHelper.java @@ -0,0 +1,72 @@ +package org.sa.rainbow.configuration.ui; + +import java.util.List; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.Region; +import org.eclipse.xtext.common.types.xtext.ui.JdtHyperlink; +import org.eclipse.xtext.common.types.xtext.ui.TypeAwareHyperlinkHelper; +import org.eclipse.xtext.nodemodel.INode; +import org.eclipse.xtext.nodemodel.util.NodeModelUtils; +import org.eclipse.xtext.resource.XtextResource; +import org.eclipse.xtext.resource.XtextResourceSet; +import org.eclipse.xtext.ui.editor.hyperlinking.IHyperlinkAcceptor; +import org.eclipse.xtext.ui.editor.hyperlinking.XtextHyperlink; +import org.sa.rainbow.configuration.rcl.Factory; +import org.sa.rainbow.configuration.rcl.Import; +import org.sa.rainbow.configuration.rcl.RclPackage; + +import com.google.inject.Inject; +import com.google.inject.Provider; + +public class RclHyperlinkHelper extends TypeAwareHyperlinkHelper { + +// @Inject +// private IQualifiedNameProvider qualifiedNameProvider; +// +// @Inject +// private IQualifiedNameConverter qualifiedNameConverter; +// + @Inject + private Provider hyperlinkProvider; + + @Override + public void createHyperlinksByOffset(XtextResource resource, int offset, IHyperlinkAcceptor acceptor) { + // TODO Auto-generated method stub + super.createHyperlinksByOffset(resource, offset, acceptor); + + EObject eObject = getEObjectAtOffsetHelper().resolveElementAt(resource, offset); + if (eObject instanceof Import) { + Import import1 = (Import) eObject; + List nodes = NodeModelUtils.findNodesForFeature(eObject, RclPackage.Literals.IMPORT__IMPORT_URI); + if (!nodes.isEmpty()) { + INode node = nodes.get(0); + XtextHyperlink hyperlink = hyperlinkProvider.get(); + hyperlink.setHyperlinkRegion(new Region(node.getOffset(), node.getLength())); + hyperlink.setHyperlinkText("Open imported file"); + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + IProject myProject = root.getProject(eObject.eResource().getURI().segment(1)); + URI cd = eObject.eResource().getURI().trimSegments(1); + + String location = cd.path().replace("/resource/"+eObject.eResource().getURI().segment(1) +"/", ""); + if (myProject.getFile("/" + location + "/" + import1.getImportURI()).exists()) { + location = "platform:/resource/" + eObject.eResource().getURI().segment(1) + "/" + + location + "/" + import1.getImportURI(); + URI importUri = URI.createURI(location); + hyperlink.setURI(importUri); + acceptor.accept(hyperlink); + } + + } + } + + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclUiModule.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclUiModule.xtend new file mode 100644 index 000000000..8c60fdf94 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/RclUiModule.xtend @@ -0,0 +1,96 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.ui +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ + +import com.google.inject.Binder +import com.google.inject.name.Names +import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor +import org.eclipse.xtext.common.types.access.IJvmTypeProvider +import org.eclipse.xtext.common.types.access.jdt.JdtTypeProviderFactory +import org.eclipse.xtext.common.types.xtext.AbstractTypeScopeProvider +import org.eclipse.xtext.common.types.xtext.ui.ITypesProposalProvider +import org.eclipse.xtext.common.types.xtext.ui.JdtBasedSimpleTypeScopeProvider +import org.eclipse.xtext.ide.editor.bracketmatching.IBracePairProvider +import org.eclipse.xtext.ide.editor.syntaxcoloring.DefaultSemanticHighlightingCalculator +import org.eclipse.xtext.service.SingletonBinding +import org.eclipse.xtext.ui.editor.hyperlinking.HyperlinkHelper +import org.eclipse.xtext.ui.editor.model.TerminalsTokenTypeToPartitionMapper +import org.eclipse.xtext.ui.editor.syntaxcoloring.DefaultHighlightingConfiguration +import org.sa.rainbow.configuration.ConfigAttributeConstants +import org.sa.rainbow.configuration.ui.contentassist.RainbowJdtTypesProposalProvider +import org.sa.rainbow.configuration.ui.contentassist.RainbowTemplateProposalProvider + +/** + * Use this class to register components to be used within the Eclipse IDE. + */ +@FinalFieldsConstructor +class RclUiModule extends AbstractRclUiModule { + override bindIHyperlinkDetector() { + return RclHyperlinkDetector + } + + + override bindITemplateProposalProvider() { + return RainbowTemplateProposalProvider; + } + + def configureJvmTypeProvider(Binder binder) { + binder.requestStaticInjection(ConfigAttributeConstants) + binder.bind(AbstractTypeScopeProvider).annotatedWith(Names.named("jvmtypes")).to(JdtBasedSimpleTypeScopeProvider) + binder.bind(IJvmTypeProvider.Factory).annotatedWith(Names.named("jvmtypes")).to(JdtTypeProviderFactory) + binder.bind(ITypesProposalProvider).annotatedWith(Names.named("jvmtypes")).to(RainbowJdtTypesProposalProvider) + + } + + override configure(Binder binder) { + super.configure(binder) + binder.bind(DefaultSemanticHighlightingCalculator).to(RclHighlighter) + binder.bind(DefaultHighlightingConfiguration).to(RclHighlightingConfiguration) + binder.bind(HyperlinkHelper).to(RclHyperlinkHelper) + } + + @SingletonBinding override Class bindIBracePairProvider() { + return RainbowBracePairsProvider + } + + override bindAbstractEditStrategyProvider() { + return AutoEditStrategyProvider + } + + def Class bindTerminalsTokenTypeToPartitionMapper() { + return TokenTypeToPartitionMapper + } + +// override configureHighlightingLexer(Binder binder) { +// binder.bind(org.eclipse.xtext.parser.antlr.Lexer) +// .annotatedWith(Names.named(LexerIdeBindings.HIGHLIGHTING)) +// .to(InternalConfigModelCustomLexer); +// } + +// override configureContentAssistLexer(Binder binder) { +// binder.bind(Lexer) +// .annotatedWith(Names.named(LexerIdeBindings.CONTENT_ASSIST)) +// .to(InternalConfigModelCustomLexer); +// } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/TokenTypeToPartitionMapper.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/TokenTypeToPartitionMapper.java new file mode 100644 index 000000000..7db9f3eb9 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/TokenTypeToPartitionMapper.java @@ -0,0 +1,56 @@ +package org.sa.rainbow.configuration.ui; + +import org.eclipse.jface.text.IDocument; +import org.eclipse.xtext.ui.editor.model.TerminalsTokenTypeToPartitionMapper; + +import com.google.inject.Singleton; + +/** + * @author Sebastian Zarnekow - Initial contribution and API + * @author Holger Schill + */ +@Singleton +public class TokenTypeToPartitionMapper extends TerminalsTokenTypeToPartitionMapper { + + public final static String RICH_STRING_LITERAL_PARTITION = "__rich_string"; + public static final String[] SUPPORTED_TOKEN_TYPES = new String[] { + COMMENT_PARTITION, + SL_COMMENT_PARTITION, + STRING_LITERAL_PARTITION, + RICH_STRING_LITERAL_PARTITION, + IDocument.DEFAULT_CONTENT_TYPE + }; + + @Override + protected String calculateId(String tokenName, int tokenType) { + if ( + "RULE_RICH_TEXT_DQ".equals(tokenName) || + "RULE_RICH_TEXT_START_DQ".equals(tokenName) || + "RULE_RICH_TEXT_END_DQ".equals(tokenName) || + "RULE_RICH_TEXT_INBETWEEN_DQ".equals(tokenName)) { + return RICH_STRING_LITERAL_PARTITION; + } + if ("RULE_ML_COMMENT".equals(tokenName)) { + return COMMENT_PARTITION; + } + return super.calculateId(tokenName, tokenType); + } + +// @Override +// protected String getMappedValue(int tokenType) { +// if(tokenType == XtendDocumentTokenSource.JAVA_DOC_TOKEN_TYPE){ +// return JAVA_DOC_PARTITION; +// } +// return super.getMappedValue(tokenType); +// } + + @Override + public String[] getSupportedPartitionTypes() { + return SUPPORTED_TOKEN_TYPES; + } + + @Override + public boolean isMultiLineComment(String partitionType) { + return super.isMultiLineComment(partitionType); + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/codemining/RclCodeMiningProvider.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/codemining/RclCodeMiningProvider.java new file mode 100644 index 000000000..976321ea9 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/codemining/RclCodeMiningProvider.java @@ -0,0 +1,171 @@ +/* + * generated by Xtext 2.20.0 + */ +package org.sa.rainbow.configuration.ui.codemining; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.codemining.ICodeMining; +import org.eclipse.jface.text.codemining.ICodeMiningProvider; +import org.eclipse.jface.text.codemining.LineContentCodeMining; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Point; +import org.eclipse.xtext.EcoreUtil2; +import org.eclipse.xtext.Keyword; +import org.eclipse.xtext.nodemodel.ICompositeNode; +import org.eclipse.xtext.nodemodel.INode; +import org.eclipse.xtext.nodemodel.impl.LeafNode; +import org.eclipse.xtext.nodemodel.util.NodeModelUtils; +import org.eclipse.xtext.resource.XtextResource; +import org.eclipse.xtext.ui.codemining.AbstractXtextCodeMiningProvider; +import org.eclipse.xtext.util.CancelIndicator; +import org.eclipse.xtext.util.IAcceptor; +import org.sa.rainbow.configuration.XtendUtils; +import org.sa.rainbow.configuration.rcl.DeclaredProperty; +import org.sa.rainbow.configuration.rcl.PropertyReference; +import org.sa.rainbow.configuration.rcl.RichStringPart; +import org.sa.rainbow.configuration.services.RclGrammarAccess; +import org.sa.rainbow.configuration.ui.FontManager; + +import com.google.inject.Inject; + +@SuppressWarnings("restriction") +public class RclCodeMiningProvider extends AbstractXtextCodeMiningProvider { + + class SmallLineContentCodeMining extends LineContentCodeMining { + + private String m_content; + + public SmallLineContentCodeMining(int beforeCharacter, String content) { + super(new Position(beforeCharacter, 1), RclCodeMiningProvider.this); + m_content = content; + + } + + @Override + protected CompletableFuture doResolve(ITextViewer viewer, IProgressMonitor monitor) { + return CompletableFuture.runAsync(() -> { + super.setLabel(m_content); + }); + } + + @Override + public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { + String title = getLabel() != null ? getLabel() : ""; + Font widgetFont = textWidget.getFont(); + Font smallFont = FontManager.getFont(widgetFont.getFontData()[0].getName(), widgetFont.getFontData()[0].getHeight()-2, widgetFont.getFontData()[0].getStyle() | SWT.ITALIC); + gc.setFont(smallFont); + Point stringExtent = gc.stringExtent(title); + gc.drawText(title, x, y); + gc.drawRectangle(x, y, stringExtent.x, stringExtent.y); + gc.setFont(widgetFont); + return stringExtent; + } + + } + + + RclGrammarAccess grammar; + + final Keyword RG_KW; + + + + // Using constructor injection to allow initializaing RG_KW. + @Inject + public RclCodeMiningProvider(RclGrammarAccess grammar) { + this.grammar = grammar; + RG_KW = grammar.getPropertyReferenceAccess() + .getRightPointingDoubleAngleQuotationMarkRightPointingDoubleAngleQuotationMarkKeyword_2(); + } + + @Override + protected void createCodeMinings(IDocument document, XtextResource resource, CancelIndicator indicator, + IAcceptor acceptor) throws BadLocationException { + if (resource.getContents().isEmpty()) + return; + + minePropertyReferences(resource, acceptor); + mineStringReferences(resource, acceptor); + + // TODO: implement me + // use acceptor.accept(super.createNewLineHeaderCodeMining(...)) to add a new + // code mining to the final list + + // example: + // acceptor.accept(createNewLineHeaderCodeMining(1, document, "Header + // annotation")); + } + + private void mineStringReferences(XtextResource resource, IAcceptor acceptor) { + List allReferences = EcoreUtil2.eAllOfType(resource.getContents().get(0), RichStringPart.class); + for (RichStringPart part : allReferences) { + if (XtendUtils.isSimpleDeclaredProperty(part.getReferable())) { + ICompositeNode node = NodeModelUtils.findActualNodeFor(part); + String annotationText = "=" + XtendUtils.valueOfSimpleDeclaredProperty(part.getReferable()); +// acceptor.accept(createNewLineContentCodeMining(node.getTotalEndOffset(), annotationText)); + acceptor.accept (new SmallLineContentCodeMining(node.getTotalEndOffset(), annotationText)); +// for (Iterator it = node.getAsTreeIterable().iterator(); it.hasNext();) { +// INode child = it.next(); +// if (!it.hasNext()) { +//// String annotationText = " = " + XtendUtils.valueOfSimpleDeclaredProperty(part.getReferable()); +// acceptor.accept(createNewLineContentCodeMining(node.getTotalEndOffset(), annotationText)); +// break; +// } +// } + } + } + } + + protected void minePropertyReferences(XtextResource resource, IAcceptor acceptor) { + List allReferences = EcoreUtil2.eAllOfType(resource.getContents().get(0), + PropertyReference.class); + + for (PropertyReference ref : allReferences) { + if (ref.getReferable() instanceof DeclaredProperty + && XtendUtils.isSimpleDeclaredProperty((DeclaredProperty) ref.getReferable())) { + ICompositeNode node = NodeModelUtils.findActualNodeFor(ref); + for (Iterator it = node.getAsTreeIterable().iterator(); it.hasNext();) { + INode child = it.next(); + if (RG_KW.equals(child.getGrammarElement())) { + String annotationText = "=" + XtendUtils + .valueOfSimpleDeclaredProperty((DeclaredProperty) ref.getReferable()); + acceptor.accept (new SmallLineContentCodeMining(child.getTotalOffset(), annotationText)); + +// acceptor.accept(createNewLineContentCodeMining(child.getTotalOffset(), annotationText)); + } + } + } + } + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/commands/InsertStringHandler.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/commands/InsertStringHandler.java new file mode 100644 index 000000000..2cd95ab0a --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/commands/InsertStringHandler.java @@ -0,0 +1,90 @@ +package org.sa.rainbow.configuration.ui.commands; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentExtension3; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.widgets.Event; +import org.eclipse.xtext.ui.editor.XtextEditor; +import org.eclipse.xtext.ui.editor.utils.EditorUtils; +import org.sa.rainbow.configuration.ui.TokenTypeToPartitionMapper; + +/** + * Handler to allow easy typing of guillemet characters on windows + * and linux, too. + */ +public abstract class InsertStringHandler extends AbstractHandler { + + public static final char LEFT_GUILLEMET = '\u00ab'; + public static final char RIGHT_GUILLEMET = '\u00bb'; + + public static class LeftGuillemet extends InsertStringHandler { + public LeftGuillemet() { + super(LEFT_GUILLEMET); + } + } + + public static class RightGuillemet extends InsertStringHandler { + public RightGuillemet() { + super(RIGHT_GUILLEMET); + } + } + + private char replaceChar; + + protected InsertStringHandler(char replaceChar) { + this.replaceChar = replaceChar; + } + + @Override + public Object execute(ExecutionEvent event) throws ExecutionException { + XtextEditor editor = EditorUtils.getActiveXtextEditor(event); + + + if (editor != null) { + String type = IDocument.DEFAULT_CONTENT_TYPE; + try { + int offset = editor.getInternalSourceViewer().getTextWidget().getCaretOffset(); + type = TextUtilities.getContentType(editor.getInternalSourceViewer().getDocument(), IDocumentExtension3.DEFAULT_PARTITIONING, offset, false); + } + catch (Exception e) {} + // Hack, would be nicer with document edits, but this way we don't loose auto edit + StyledText textWidget = editor.getInternalSourceViewer().getTextWidget(); + Event e = new Event(); + e.character = replaceChar; + e.type = SWT.KeyDown; + e.doit = true; + textWidget.notifyListeners(SWT.KeyDown, e); + if (IDocument.DEFAULT_CONTENT_TYPE.equals(type)) { + e = new Event(); + e.character = replaceChar; + e.type = SWT.KeyDown; + e.doit = true; + textWidget.notifyListeners(SWT.KeyDown, e); + } + } + return null; + } +} \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/NonContinuingAcceptor.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/NonContinuingAcceptor.java new file mode 100644 index 000000000..19aed2047 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/NonContinuingAcceptor.java @@ -0,0 +1,49 @@ +package org.sa.rainbow.configuration.ui.contentassist; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor; +import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor.Delegate; + +public class NonContinuingAcceptor extends Delegate { + + private boolean m_canAcceptMoreProposals; + + public NonContinuingAcceptor(ICompletionProposalAcceptor delegate) { + super(delegate); + m_canAcceptMoreProposals = true; + } + + @Override + public void accept(ICompletionProposal proposal) { + if (proposal != null) + super.accept(proposal); + } + + @Override + public boolean canAcceptMoreProposals() { + return m_canAcceptMoreProposals; + } + + public void setAcceptMoreProposals(boolean accept) { + m_canAcceptMoreProposals = accept; + } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/RainbowJdtTypesProposalProvider.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/RainbowJdtTypesProposalProvider.java new file mode 100644 index 000000000..975c73c76 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/RainbowJdtTypesProposalProvider.java @@ -0,0 +1,73 @@ +package org.sa.rainbow.configuration.ui.contentassist; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import org.eclipse.emf.ecore.EReference; +import org.eclipse.xtext.common.types.JvmType; +import org.eclipse.xtext.common.types.xtext.ui.JdtTypesProposalProvider; +import org.eclipse.xtext.conversion.ValueConverterException; +import org.eclipse.xtext.conversion.impl.AbstractValueConverter; +import org.eclipse.xtext.conversion.impl.QualifiedNameValueConverter; +import org.eclipse.xtext.nodemodel.INode; +import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext; +import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor; +import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalFactory; + +import com.google.inject.Inject; + +public class RainbowJdtTypesProposalProvider extends JdtTypesProposalProvider { + + @Inject + private QualifiedNameValueConverter qnValueConverter; + + @Override + public void createSubTypeProposals(JvmType superType, ICompletionProposalFactory proposalFactory, ContentAssistContext context, EReference typeReference, Filter filter, ICompletionProposalAcceptor acceptor) { + createSubTypeProposals(superType, proposalFactory, context, typeReference, filter, getConverter(), acceptor); + } + + /** + * Overridden to pass a default value converter + */ + @Override + public void createTypeProposals(ICompletionProposalFactory proposalFactory, ContentAssistContext context, EReference typeReference, Filter filter, ICompletionProposalAcceptor acceptor) { + createTypeProposals(proposalFactory, context, typeReference, filter, getConverter(), acceptor); + } + + + private AbstractValueConverter getConverter() { + return new AbstractValueConverter() { + /** + * Remove ^ character from escaped segments + */ + @Override + public String toValue(String string, INode node) throws ValueConverterException { + return string.replace("^", ""); + } + + /** + * Escape segments colliding with keywords with ^ character + */ + @Override + public String toString(String value) throws ValueConverterException { + // this converter will escape keywords with ^ + return qnValueConverter.toString(value); + } + }; + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/RainbowTemplateProposalProvider.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/RainbowTemplateProposalProvider.xtend new file mode 100644 index 000000000..e42887d21 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/RainbowTemplateProposalProvider.xtend @@ -0,0 +1,96 @@ +package org.sa.rainbow.configuration.ui.contentassist + +import com.google.inject.Inject +import java.util.List +import org.eclipse.jface.text.templates.ContextTypeRegistry +import org.eclipse.jface.text.templates.Template +import org.eclipse.jface.text.templates.TemplateContext +import org.eclipse.jface.text.templates.persistence.TemplateStore +import org.eclipse.xtext.EcoreUtil2 +import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext +import org.eclipse.xtext.ui.editor.contentassist.ITemplateAcceptor +import org.eclipse.xtext.ui.editor.templates.ContextTypeIdHelper +import org.eclipse.xtext.ui.editor.templates.DefaultTemplateProposalProvider +import org.sa.rainbow.configuration.ModelUtil +import org.sa.rainbow.configuration.ModelUtil.CommandRep +import org.sa.rainbow.configuration.rcl.EffectorBody +import org.sa.rainbow.configuration.rcl.Gauge +import org.sa.rainbow.configuration.rcl.GaugeTypeBody +import org.sa.rainbow.configuration.rcl.PropertyReference +import org.sa.rainbow.configuration.services.RclGrammarAccess + +class RainbowTemplateProposalProvider extends DefaultTemplateProposalProvider { + + val ContextTypeIdHelper helper; + + @Inject + new(TemplateStore templateStore, ContextTypeRegistry registry, ContextTypeIdHelper helper) { + super(templateStore, registry, helper) + this.helper = helper + } + + @Inject + RclGrammarAccess ga; + + override protected createTemplates(TemplateContext templateContext, ContentAssistContext context, + ITemplateAcceptor acceptor) { + super.createTemplates(templateContext, context, acceptor) + + val prID = helper.getId(ga.propertyReferenceRule) + if (prID == templateContext.contextType.id) { + val template = new Template("name::type", "Old syle model reference", "modelRefNameAndType", + "${modelName}::${modelType}", false) + val tp = createProposal(template, templateContext, context, null, getRelevance(template)) + acceptor.accept(tp) + return + } + + val model = context.currentModel + val gauge = EcoreUtil2.getContainerOfType(model, Gauge) + val gaugeType = EcoreUtil2.getContainerOfType(model, GaugeTypeBody) + val effector = EcoreUtil2.getContainerOfType(model, EffectorBody) + val container = gauge != null ? gauge : gaugeType != null ? gaugeType : effector != null ? effector : null + + if (helper.getId(ga.commandCallRule) == templateContext.contextType.id || + helper.getId(ga.commandReferenceRule) == templateContext.contextType.id) { + switch container { + EffectorBody: + templatesForFactory(ModelUtil.getCommandsFromReference(container.ref, null, null, false), + templateContext, context, acceptor, false, false) + GaugeTypeBody case container.mcf instanceof PropertyReference: + templatesForFactory(ModelUtil.getCommandsFromReference(container.mcf as PropertyReference, null, container.commands.map [ + it.command + ].toList, true), templateContext, context, acceptor, true, true) + Gauge case container?.superType?.body?.mcf instanceof PropertyReference: + templatesForFactory( + ModelUtil.getCommandsFromReference(container?.superType?.body?.mcf as PropertyReference, + container?.superType?.body?.commands?.map[it.command]?.toList(), container.body.commands.map [ + it.command + ].toList, true), templateContext, context, acceptor, true, false) + } + return + } + + } + + def templatesForFactory(List reps, TemplateContext templateContext, ContentAssistContext context, + ITemplateAcceptor acceptor, boolean isGauge, boolean isGaugeType) { + reps.forEach [ + var template = new Template('''command «it.name»''', '''Call for command «it.name»''', + templateContext.contextType. + id, '''command «IF isGauge»${name} = «ENDIF»«IF it.hasTarget !== null»${«it.hasTarget»}.«ENDIF»«it.name»(«FOR f : it.formalNames SEPARATOR ', '»${«f»}«ENDFOR»)''', + true) + var tp = createProposal(template, templateContext, context, null, getRelevance(template)) + acceptor.accept(tp) + if (isGaugeType) { + template = new Template('''command «it.name» with regexp''', '''Command «it.name» with regexp''', + templateContext.contextType. + id, '''command ${name} = ${regexmp} -> «IF it.hasTarget !== null»${«it.hasTarget»}.«ENDIF»«it.name»(«FOR f : it.formalNames SEPARATOR ', '»${«f»}«ENDFOR»)''', + true) + tp = createProposal(template, templateContext, context, null, getRelevance(template)) + acceptor.accept(tp) + } + ] + } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/RclProposalProvider.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/RclProposalProvider.xtend new file mode 100644 index 000000000..e639d160b --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/contentassist/RclProposalProvider.xtend @@ -0,0 +1,854 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.ui.contentassist + +/* + * Copyright 2020 Carnegie Mellon University + + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR + * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE + * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +import com.google.common.base.Predicate +import com.google.common.collect.Sets +import com.google.inject.Inject +import com.google.inject.name.Named +import java.util.Collection +import java.util.HashSet +import java.util.List +import java.util.Set +import java.util.stream.Collectors +import javax.swing.text.BadLocationException +import org.eclipse.emf.ecore.EObject +import org.eclipse.jface.viewers.StyledString +import org.eclipse.xtext.CrossReference +import org.eclipse.xtext.EcoreUtil2 +import org.eclipse.xtext.Grammar +import org.eclipse.xtext.GrammarUtil +import org.eclipse.xtext.Group +import org.eclipse.xtext.Keyword +import org.eclipse.xtext.RuleCall +import org.eclipse.xtext.common.types.access.IJvmTypeProvider +import org.eclipse.xtext.common.types.xtext.ui.ITypesProposalProvider +import org.eclipse.xtext.common.types.xtext.ui.TypeMatchFilters +import org.eclipse.xtext.resource.IEObjectDescription +import org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal +import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext +import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor +import org.eclipse.xtext.ui.editor.contentassist.ITemplateAcceptor +import org.eclipse.xtext.ui.editor.contentassist.ITemplateProposalProvider +import org.eclipse.xtext.xbase.lib.Functions.Function1 +import org.sa.rainbow.configuration.ConfigAttributeConstants +import org.sa.rainbow.configuration.XtendUtils +import org.sa.rainbow.configuration.rcl.Array +import org.sa.rainbow.configuration.rcl.Assignment +import org.sa.rainbow.configuration.rcl.BooleanLiteral +import org.sa.rainbow.configuration.rcl.Component +import org.sa.rainbow.configuration.rcl.ComponentType +import org.sa.rainbow.configuration.rcl.DeclaredProperty +import org.sa.rainbow.configuration.rcl.DoubleLiteral +import org.sa.rainbow.configuration.rcl.Effector +import org.sa.rainbow.configuration.rcl.Factory +import org.sa.rainbow.configuration.rcl.Gauge +import org.sa.rainbow.configuration.rcl.GaugeType +import org.sa.rainbow.configuration.rcl.IPLiteral +import org.sa.rainbow.configuration.rcl.IntegerLiteral +import org.sa.rainbow.configuration.rcl.Probe +import org.sa.rainbow.configuration.rcl.PropertyReference +import org.sa.rainbow.configuration.rcl.RclPackage +import org.sa.rainbow.configuration.rcl.StringLiteral +import org.sa.rainbow.configuration.services.RclGrammarAccess +import org.sa.rainbow.core.gauges.AbstractGauge +import org.sa.rainbow.core.models.IModelInstance +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd +import org.sa.rainbow.core.models.commands.ModelCommandFactory +import org.sa.rainbow.model.acme.AcmeModelOperation +import org.sa.rainbow.translator.probes.AbstractProbe + +/** + * See https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#content-assist + * on how to customize the content assistant. + */ +class RclProposalProvider extends AbstractRclProposalProvider { + + @Inject + RclGrammarAccess cfGrammar + + static var Set KEYWORDS = null + + def isKeyword(String s) { + if (KEYWORDS === null) { + KEYWORDS = newHashSet + val Set grammars = newHashSet + grammars.add(cfGrammar.grammar) + grammars.addAll(GrammarUtil.allUsedGrammars(cfGrammar.grammar)); + for (g : grammars) { + KEYWORDS.addAll(GrammarUtil.getAllKeywords(g)) + } + } + return KEYWORDS.contains(s) + } + + override completeRichStringPart_Referable(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + + lookupCrossReference( + assignment.getTerminal() as CrossReference, + context, + acceptor, + [ IEObjectDescription e | + val eobj = e.EObjectOrProxy + return (eobj instanceof DeclaredProperty && + XtendUtils.isSimpleDeclaredProperty(eobj as DeclaredProperty)) + ] + ) + } + + override complete_RICH_TEXT_DQ(EObject model, RuleCall ruleCall, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + completeInRichString(model, ruleCall, context, acceptor, "\"") + } + + override complete_RICH_TEXT_START_DQ(EObject model, RuleCall ruleCall, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + completeInRichString(model, ruleCall, context, acceptor, "\"") + } + + override complete_RICH_TEXT_END_DQ(EObject model, RuleCall ruleCall, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + completeInRichString(model, ruleCall, context, acceptor, "\"") + } + + override complete_RICH_TEXT_INBETWEEN_DQ(EObject model, RuleCall ruleCall, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + completeInRichString(model, ruleCall, context, acceptor, "\"") + } + +// override complete_RICH_TEXT_SQ(EObject model, RuleCall ruleCall, ContentAssistContext context, +// ICompletionProposalAcceptor acceptor) { +// completeInRichString(model, ruleCall, context, acceptor, "'") +// } +// +// override complete_RICH_TEXT_START_SQ(EObject model, RuleCall ruleCall, ContentAssistContext context, +// ICompletionProposalAcceptor acceptor) { +// completeInRichString(model, ruleCall, context, acceptor, "'") +// } +// +// override complete_RICH_TEXT_END_SQ(EObject model, RuleCall ruleCall, ContentAssistContext context, +// ICompletionProposalAcceptor acceptor) { +// completeInRichString(model, ruleCall, context, acceptor,"'") +// } +// +// override complete_RICH_TEXT_INBETWEEN_SQ(EObject model, RuleCall ruleCall, ContentAssistContext context, +// ICompletionProposalAcceptor acceptor) { +// completeInRichString(model, ruleCall, context, acceptor, "'") +// } + def completeInRichString(EObject object, RuleCall call, ContentAssistContext context, + ICompletionProposalAcceptor acceptor, String delimiter) { + val node = context.getCurrentNode(); + val textRegion = node.textRegion; + val offset = textRegion.offset + val length = textRegion.length + val currentNodeText = node.text + if (currentNodeText.startsWith("\u00BB") && offset + 1 <= context.offset || + currentNodeText.startsWith(delimiter) && offset + delimiter.length <= context.offset) { + if (context.offset > offset && context.offset < offset + length) { + addGuillemotsProposal(context, acceptor) + } + } else if (currentNodeText.startsWith("\u00AB\u00AB")) { + try { + val document = context.viewer.document + val nodeLine = document.getLineOffset(offset) + val completionLine = document.getLineOffset(context.offset) + if (completionLine > nodeLine) { + addGuillemotsProposal(context, acceptor) + } + } catch (BadLocationException e) { + } + } + } + + def addGuillemotsProposal(ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + acceptor.accept( + new ConfigurableCompletionProposal("\u00AB\u00BB", context.getOffset(), context.getSelectedText().length(), + 1)); + } + + override complete_PropertyReference(EObject model, RuleCall ruleCall, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + super.complete_PropertyReference(model, ruleCall, context, acceptor) + val proposal = new ConfigurableCompletionProposal("\u00AB\u00AB\u00BB\u00BB", context.getOffset(), + context.getSelectedText().length(), 2) + proposal.priority = 1 + acceptor.accept(proposal) + } + + override completeReference_Referable(EObject model, org.eclipse.xtext.Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + } + + override complete_Assignment(EObject model, RuleCall ruleCall, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + + // Check Gauge attributes + var parent = model + var assignmentContext = null as Assignment + while (parent !== null && + (!(parent instanceof Gauge) && !(parent instanceof Probe) && !(parent instanceof GaugeType) && + !(parent instanceof Effector))) { + parent = parent.eContainer + if (parent instanceof Assignment) { + assignmentContext = parent as Assignment + } + } + + val allPossibleFields = new HashSet() + if (parent instanceof Gauge || parent instanceof GaugeType) { + if (assignmentContext === null) { + allPossibleFields.addAll(ConfigAttributeConstants.ALL_OFREQUIRED_GAUGE_SUBFILEDS.keySet) + allPossibleFields.addAll(ConfigAttributeConstants.OPTIONAL_GUAGE_FIELDS) + if (parent instanceof Gauge) { + allPossibleFields.removeAll((parent as Gauge).body.assignment.map[it.name]) + } else { + allPossibleFields.removeAll((parent as GaugeType).body.assignment.map[it.name]) + } + } else { + var subfields = ConfigAttributeConstants.ALL_OFREQUIRED_GAUGE_SUBFILEDS.get(assignmentContext.name) + if (subfields !== null) { + allPossibleFields.addAll(subfields) + } + subfields = ConfigAttributeConstants.OPTIONAL_GAUGE_SUBFIELDS.get(assignmentContext.name) + if (subfields !== null) { + allPossibleFields.addAll(subfields) + } + allPossibleFields.removeAll((assignmentContext.value.value as Component).assignment.map[it.name]) + } + } else if (parent instanceof Probe) { + if (assignmentContext === null) { + allPossibleFields.addAll(ConfigAttributeConstants.ALL_OFREQUIRED_PROBE_FIELDS) + allPossibleFields.addAll(ConfigAttributeConstants.ONE_OFREQUIRED_PROBE_FIELDS); + allPossibleFields.removeAll((parent as Probe).properties.assignment.map[it.name]) + } else { + var subfields = ConfigAttributeConstants.ALL_OFREQUIRED_PROBE_SUBFIELDS.get(assignmentContext.name) + if (subfields !== null) { + allPossibleFields.addAll(subfields) + } + subfields = ConfigAttributeConstants.OPTIONAL_PROBE_SUBFIELDS.get(assignmentContext.name) + if (subfields !== null) { + allPossibleFields.addAll(subfields) + } + allPossibleFields.removeAll((assignmentContext.value.value as Component).assignment.map[it.name]) + } + } else if (parent instanceof Effector) { + if (assignmentContext === null) { + allPossibleFields.addAll(ConfigAttributeConstants.ALL_OFREQUIRED_EFFECTOR_FIELDS) + allPossibleFields.addAll(ConfigAttributeConstants.ONE_OFREQUIRED_EFFECTOR_FIELDS) + allPossibleFields.removeAll((parent as Effector).body.assignment.map[it.name]) + } else { + var subfields = ConfigAttributeConstants.ALL_OFREQUIRED_EFFECTOR_SUBFIELDS.get(assignmentContext.name) + if (subfields !== null) { + allPossibleFields.addAll(subfields) + } + subfields = ConfigAttributeConstants.OPTIONAL_EFFECTOR_SUBFIELDS.get(assignmentContext.name) + if (subfields !== null) { + allPossibleFields.addAll(subfields) + } + allPossibleFields.removeAll((assignmentContext.value.value as Component).assignment.map[it.name]) + } + } else { + parent = EcoreUtil2.getContainerOfType(model, DeclaredProperty) + if ((parent as DeclaredProperty)?.component == ComponentType.UTILITY) { + val sb = new StringBuffer() + var eContainer = model + while (eContainer != parent) { + eContainer = eContainer.eContainer + if (eContainer instanceof Assignment) { + sb.insert(0, ':') + val par = (eContainer as Assignment) + if (ConfigAttributeConstants.UTILITY_PROPERTY_TYPES.containsKey(par.name)) { + sb.insert(0, par.name) + } + } + } + val container = sb.toString + for (key : ConfigAttributeConstants.UTILITY_PROPERTY_TYPES.keySet) { + if (key.startsWith(container)) { + if (container.contains(':')) { + val split = key.split(':') + allPossibleFields.add(split.get(split.length - 1)) + } else { + allPossibleFields.add(key) + } + } + } + } else if ((parent as DeclaredProperty)?.component == ComponentType.GUI) { + var m = model; + if(m instanceof Assignment && m.eContainer instanceof Component) m = m.eContainer + allPossibleFields.addAll( + XtendUtils.getPropertySuggestions(ConfigAttributeConstants.GUI_PROPERTY_TUPES, m)) + } + } + var suggestions = allPossibleFields.stream.filter[it.startsWith(context.prefix)].collect(Collectors.toSet) + suggestions.forEach [ + { + val proposal = new ConfigurableCompletionProposal((isKeyword(it) + ? '''^«it»''' : it) + " = ", context.replaceRegion.offset, context.replaceRegion.length, + it.length + 3) + proposal.displayString = it + proposal.priority = 1 + acceptor.accept(proposal) + } + ] + if (suggestions.empty) { + super.complete_Assignment(model, ruleCall, context, acceptor) + + } + } + + @Inject + @Named(value="jvmtypes") + private IJvmTypeProvider.Factory jvmTypeProviderFactory; + @Inject + @Named(value="jvmtypes") + private ITypesProposalProvider typeProposalProvider; + + override completeGaugeTypeBody_Mcf(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(model.eResource.resourceSet) + val subclass = jvmTypeProvider.findTypeByName(ModelCommandFactory.name) + typeProposalProvider.createSubTypeProposals(subclass, this, context, RclPackage.Literals.GAUGE_TYPE_BODY__MCF, + TypeMatchFilters.canInstantiate, acceptor); + val v = model.eResource.resourceSet.resources + val models = new HashSet(); + for (r : v) { + val res = r.allContents + res.forEach [ + if (it instanceof Factory) { + models.add((it as Factory).name) + } + ] + } + fillInProposals(models, acceptor, context) + + } + + override completeFactoryDefinition_LoadCmd(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(model.eResource.resourceSet) + val subclass = jvmTypeProvider.findTypeByName(AbstractLoadModelCmd.name) + typeProposalProvider.createSubTypeProposals(subclass, this, context, + RclPackage.Literals.FACTORY_DEFINITION__LOAD_CMD, TypeMatchFilters.canInstantiate, acceptor); + + } + + override completeFactoryDefinition_SaveCmd(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(model.eResource.resourceSet) + val subclass = jvmTypeProvider.findTypeByName(AbstractSaveModelCmd.name) + typeProposalProvider.createSubTypeProposals(subclass, this, context, + RclPackage.Literals.FACTORY_DEFINITION__SAVE_CMD, TypeMatchFilters.canInstantiate, acceptor); + + } + + override completeFactoryDefinition_Extends(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(model.eResource.resourceSet) + val subclass = jvmTypeProvider.findTypeByName(ModelCommandFactory.name) + typeProposalProvider.createSubTypeProposals(subclass, this, context, + RclPackage.Literals.FACTORY_DEFINITION__EXTENDS, TypeMatchFilters.canInstantiate, acceptor); + } + + override completeFactoryDefinition_ModelClass(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(model.eResource.resourceSet) + val subclass = jvmTypeProvider.findTypeByName(IModelInstance.name) + typeProposalProvider.createSubTypeProposals(subclass, this, context, + RclPackage.Literals.FACTORY_DEFINITION__MODEL_CLASS, TypeMatchFilters.canInstantiate, acceptor); + + } + + override completeEffectorBody_Ref(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + val v = model.eResource.resourceSet.resources + val models = new HashSet(); + for (r : v) { + val res = r.allContents + res.forEach [ + if (it instanceof DeclaredProperty && (it as DeclaredProperty).component == ComponentType.MODEL) { + models.add((it as DeclaredProperty).name) + } + ] + } + if (!models.empty) { + models.forEach [ + acceptor.accept( + new ConfigurableCompletionProposal("\u00AB\u00AB" + it + "\u00BB\u00BB", + context.replaceRegion.offset, context.replaceRegion.length, it.length + 4, null, + new StyledString(it), null, null)) + ] + acceptor.accept( + new ConfigurableCompletionProposal("\u00AB\u00AB\u00BB\u00BB", context.getOffset(), + context.getSelectedText().length(), 2)); + } + } + + override completeGaugeBody_Ref(EObject model, org.eclipse.xtext.Assignment assignment, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + val v = model.eResource.resourceSet.resources + val models = new HashSet(); + for (r : v) { + val res = r.allContents + res.forEach [ + if (it instanceof DeclaredProperty && (it as DeclaredProperty).component == ComponentType.MODEL) { + models.add((it as DeclaredProperty).name) + } + ] + } + fillInProposals(models, acceptor, context) + } + + protected def void fillInProposals(HashSet names, ICompletionProposalAcceptor acceptor, + ContentAssistContext context) { + if (!names.empty) { + names.forEach [ + acceptor.accept( + new ConfigurableCompletionProposal("\u00AB\u00AB" + it + "\u00BB\u00BB", + context.replaceRegion.offset, context.replaceRegion.length, it.length + 4, null, + new StyledString(it), null, null)) + ] + acceptor.accept( + new ConfigurableCompletionProposal("\u00AB\u00AB\u00BB\u00BB", context.getOffset(), + context.getSelectedText().length(), 2)); + } + } + + + + override completeAssignment_Value(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + val dp = EcoreUtil2.getContainerOfType(model, DeclaredProperty) + if (dp?.name?.matches(".*class_[0-9]+$")) { + val checkName = dp.name.substring(0, dp.name.lastIndexOf('_')) + "*" + val subclass = ConfigAttributeConstants.PROPERTY_VALUE_CLASSES.get(checkName) + if (subclass !== null) { + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(model.eResource.resourceSet) + val sc = jvmTypeProvider.findTypeByName(subclass) + if (sc !== null) { + typeProposalProvider.createSubTypeProposals(sc, this, context, + RclPackage.Literals.ASSIGNMENT__VALUE, TypeMatchFilters.canInstantiate, acceptor); + pauseAssisting(acceptor); + return + } + } + } + if (ConfigAttributeConstants.PROPERTY_VALUE_TYPES.get(dp.name)!==null) { + val info = ConfigAttributeConstants.PROPERTY_VALUE_TYPES.get(dp.name) + processPropertySuggestionsBasedOnClass(info?.get('extends') as List, dp, context, acceptor) + + return + } + val ass = EcoreUtil2.getContainerOfType(model, Assignment) + if (ass.name == "javaClass") { + val gtc = EcoreUtil2.getContainerOfType(ass, GaugeType) + val gc = EcoreUtil2.getContainerOfType(ass, Gauge) + if (gtc !== null || gc !== null) { + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(model.eResource.resourceSet) + val subclass = jvmTypeProvider.findTypeByName(AbstractGauge.name) + if (subclass != null) { + typeProposalProvider.createSubTypeProposals(subclass, this, context, + RclPackage.Literals.ASSIGNMENT__VALUE, TypeMatchFilters.canInstantiate, acceptor); + pauseAssisting(acceptor); + return + + } + } + val pc = EcoreUtil2.getContainerOfType(ass, Probe); + if (pc !== null) { + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(model.eResource.resourceSet) + val subclass = jvmTypeProvider.findTypeByName(AbstractProbe.name) + if (subclass !== null) { + typeProposalProvider.createSubTypeProposals(subclass, this, context, + RclPackage.Literals.ASSIGNMENT__VALUE, TypeMatchFilters.canInstantiate, acceptor); + pauseAssisting(acceptor); + return + } + + } + } + val parentProp = EcoreUtil2.getContainerOfType(ass, DeclaredProperty) + if (ComponentType.GUI == parentProp?.component) { + var parent = EcoreUtil2.getContainerOfType(model.eContainer, Assignment); + var name = ass.name + while (parent !== null) { + name = parent.name + ":" + name + parent = EcoreUtil2.getContainerOfType(parent.eContainer, Assignment); + } + val valVunc = ConfigAttributeConstants.GUI_PROPERTY_TUPES.get(name)?.get( + 'values') as Function1> + if (valVunc !== null) { + val values = (valVunc).apply(ass) + if (values !== null) { + values.forEach [ + acceptor.accept( + new ConfigurableCompletionProposal(it, context.replaceRegion.offset, + context.replaceRegion.length, it.length)) + ] + } + + } + + val extends = ConfigAttributeConstants.GUI_PROPERTY_TUPES.get(name)?.get('extends') as List + processPropertySuggestionsBasedOnClass(extends, model, context, acceptor) + } else if (parentProp?.component !== null) { + var extends = ConfigAttributeConstants.COMPONENT_PROPERTY_TYPES.get(parentProp.component)?.get(ass.name)?. + get('extends') as List + if (extends != null) { + processPropertySuggestionsBasedOnClass(extends, model, context, acceptor) + } else if (parentProp.component === ComponentType.UTILITY) { + val sb = new StringBuffer(ass.name) + var eContainer = ass as EObject + while (eContainer !== null) { + eContainer = eContainer.eContainer + if (eContainer instanceof Assignment) { + sb.insert(0, ':') + val par = (eContainer as Assignment) + if (ConfigAttributeConstants.UTILITY_PROPERTY_TYPES.containsKey(par.name)) { + sb.insert(0, par.name) + } + } + } + extends = ConfigAttributeConstants.UTILITY_PROPERTY_TYPES.containsKey(sb.toString) + ? ConfigAttributeConstants.UTILITY_PROPERTY_TYPES.get(sb.toString).get("extends") as List + : null + processPropertySuggestionsBasedOnClass(extends, model, context, acceptor) + } + return + } + val probe = EcoreUtil2.getContainerOfType(model, Probe) + if (probe !== null) { + val parent = EcoreUtil2.getContainerOfType(model.eContainer, Assignment) + var name = ass.name + if (parent !== null) { + name = parent.name + ":" + ass.name + } + val extends = ConfigAttributeConstants.PROBE_PROPERTY_TYPES.get(name)?.get('extends') as List + processPropertySuggestionsBasedOnClass(extends, model, context, acceptor) + return + } + val gauge = EcoreUtil2.getContainerOfType(model, Gauge) + val gaugeType = EcoreUtil2.getContainerOfType(model, GaugeType) + if (gauge !== null || gaugeType !== null) { + val parent = EcoreUtil2.getContainerOfType(model.eContainer, Assignment) + var name = ass.name + if (parent !== null) { + name = parent.name + ":" + ass.name + } + val extends = ConfigAttributeConstants.GAUGE_PROPERTY_TYPES.get(name)?.get('extends') as List + processPropertySuggestionsBasedOnClass(extends, model, context, acceptor) + return + } + val effector = EcoreUtil2.getContainerOfType(model, Effector) + if (effector !== null) { + val parent = EcoreUtil2.getContainerOfType(model.eContainer, Assignment); + var name = ass.name + if (parent !== null) { + name = parent.name + ":" + ass.name + } + val extends = ConfigAttributeConstants.EFFECTOR_PROPERTY_TYPES.get(name)?.get('extends') as List + processPropertySuggestionsBasedOnClass(extends, model, context, acceptor) + return + } + + super.completeAssignment_Value(model, assignment, context, acceptor) + } + + def processPropertySuggestionsBasedOnClass(List ext, EObject model, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + if (ext !== null) { + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(model.eResource.resourceSet) + for (class : ext) { + if (class == StringLiteral) { + acceptor.accept( + new ConfigurableCompletionProposal('""', context.replaceRegion.offset, + context.replaceRegion.length, 1)) + } else if (class == BooleanLiteral) { + acceptor.accept( + new ConfigurableCompletionProposal('true', context.replaceRegion.offset, + context.replaceRegion.length, 4)) + acceptor.accept( + new ConfigurableCompletionProposal('false', context.replaceRegion.offset, + context.replaceRegion.length, 4)) + } else if (class == PropertyReference) { + acceptor.accept( + new ConfigurableCompletionProposal("\u00AB\u00AB\u00BB\u00BB", context.getOffset(), + context.getSelectedText().length(), 2)); + } else if (class == Probe) { + val v = model.eResource.resourceSet.resources + val probes = newHashSet + for (r : v) { + val res = r.allContents + res.forEach [ + if (it instanceof Probe) { + probes.add((it as Probe).name) + } + ] + + } + fillInProposals(probes, acceptor, context) + } else if (class == Factory) { + val names = newHashSet + val v = model.eResource.resourceSet.resources + for (r : v) { + val res = r.allContents + res.forEach [ + if (it instanceof Factory) { + names.add((it as Factory).name) + } + ] + } + fillInProposals(names, acceptor, context) + } else if (class == GaugeType) { + val names = newHashSet + val v = model.eResource.resourceSet.resources + for (r : v) { + val res = r.allContents + res.forEach [ + if (it instanceof GaugeType) { + names.add((it as GaugeType).name) + } + ] + } + fillInProposals(names, acceptor, context) + /* } else if (class == ProbeReference) { + * acceptor.accept( + * new ConfigurableCompletionProposal("probe ", context.getOffset(), + * context.getSelectedText().length(), 6)); + */ + } else if (class == Array) { + acceptor.accept( + new ConfigurableCompletionProposal("[]", context.getOffset(), + context.getSelectedText().length(), 1)); + } else if (class == Component) { + acceptor.accept( + new ConfigurableCompletionProposal("{}", context.getOffset(), + context.getSelectedText().length(), 1)); + } else if (class == DoubleLiteral || class == IntegerLiteral || class == IPLiteral) { + } else { + val sc = jvmTypeProvider.findTypeByName(class.name) + if (sc !== null) { + typeProposalProvider.createSubTypeProposals(sc, this, context, + RclPackage.Literals.ASSIGNMENT__VALUE, TypeMatchFilters.canInstantiate, acceptor); + } + } + + } + pauseAssisting(acceptor); + return + } + } + + override completeCommandDefinition_Cmd(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(model.eResource.resourceSet) + val sc = jvmTypeProvider.findTypeByName(typeof(AcmeModelOperation).name) + if (sc !== null) { + typeProposalProvider.createSubTypeProposals(sc, this, context, RclPackage.Literals.COMMAND_DEFINITION__CMD, + TypeMatchFilters.canInstantiate, acceptor); + } + pauseAssisting(acceptor) + + } + + override completeCommandReference_Command(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + super.completeCommandReference_Command(model, assignment, context, acceptor) + } + +// @Inject +// ITemplateProposalProvider tpp; + + + override complete_CommandCall(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + super.complete_CommandCall(model, ruleCall, context, acceptor) +// val template = new Template("name::type", +// "Old style model reference", +// "modeelRefNameAndType", +// "${modelName}::${modeltype}", +// false); +// tpp.createTemplates(context, acceptor as ITemplateAcceptor) +// val tp = new XtextTemplateProposal(template, context, context.getReplaceRegion(), null, 1); + +// acceptor.accept(tp); + } + +// override completeGaugeBody_Ref(EObject model, org.eclipse.xtext.Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { +// super.completeGaugeBody_Ref(model, assignment, context, acceptor) +// } + override completePropertyReference_Referable(EObject model, org.eclipse.xtext.Assignment assignment, + ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + val parentProp = EcoreUtil2.getContainerOfType(model, DeclaredProperty) + var myProp = EcoreUtil2.getContainerOfType(model, Assignment) + if ('model' == myProp?.name && + (parentProp?.component === ComponentType.EXECUTOR || parentProp?.component === ComponentType.MANAGER)) { + val v = model.eResource.resourceSet.resources + val models = new HashSet(); + for (r : v) { + val res = r.allContents + res.forEach [ + if (it instanceof DeclaredProperty && (it as DeclaredProperty).component == ComponentType.MODEL) { + models.add((it as DeclaredProperty).name) + } + ] + } + if (!models.empty) { + models.forEach [ + acceptor.accept( + new ConfigurableCompletionProposal(it, context.replaceRegion.offset, + context.replaceRegion.length, it.length)) + ] + } + return; + } + val ass = EcoreUtil2.getContainerOfType(model, Assignment) + val gauge = EcoreUtil2.getContainerOfType(model, Gauge) + val gaugeType = EcoreUtil2.getContainerOfType(model, GaugeType) + if (gauge !== null || gaugeType !== null) { + val parent = EcoreUtil2.getContainerOfType(model.eContainer, Assignment) + var name = ass.name + if (parent !== null) { + name = parent.name + ":" + ass.name + } + val extends = ConfigAttributeConstants.GAUGE_PROPERTY_TYPES.get(name)?.get('extends') as List + for (class : extends) { + lookupCrossReference( + assignment.getTerminal() as CrossReference, + context, + acceptor, + [ IEObjectDescription e | + e.EObjectOrProxy instanceof DeclaredProperty && + class.isAssignableFrom((e.EObjectOrProxy as DeclaredProperty)?.value?.value?.class) + ] + ) + } + return + } + + val effector = EcoreUtil2.getContainerOfType(model, Effector); + if (effector !== null) { + val ass1 = EcoreUtil2.getContainerOfType(model.eContainer, Assignment) + if (ass1 !== null) { + val parent = EcoreUtil2.getContainerOfType(ass1.eContainer, Assignment) + var name = ass.name + if (parent !== null) { + name = parent.name + ":" + ass.name + } + val extends = ConfigAttributeConstants.EFFECTOR_PROPERTY_TYPES.get(name)?.get('extends') as List + for (class : extends) { + lookupCrossReference( + assignment.getTerminal() as CrossReference, + context, + acceptor, + [ IEObjectDescription e | + if (e.EObjectOrProxy instanceof DeclaredProperty) { + val class2 = (e.EObjectOrProxy as DeclaredProperty)?.value.value?.class + return class2 !== null && class.isAssignableFrom(class2) + } + return false; + ] + ) + } + return + + } + } + + super.completePropertyReference_Referable(model, assignment, context, acceptor) + } + + def pauseAssisting(ICompletionProposalAcceptor acceptor) { + if (acceptor instanceof NonContinuingAcceptor) { + (acceptor as NonContinuingAcceptor).acceptMoreProposals = false + } + } + +// override completeReference_Referable(EObject model, org.eclipse.xtext.Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { +// val ass = EcoreUtil2.getContainerOfType(model, Assignment) +// if (ass.name != "javaClass") +// super.completeReference_Referable(model, assignment, context,acceptor); +// } + def Predicate subclassFilter(Class superclass) { + return new Predicate() { + + override apply(IEObjectDescription subclass) { + return true; + } + + } + } + + private Set> handledArguments; + + override createProposals(ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + try { + handledArguments = Sets.newHashSet(); + val myAcceptor = new NonContinuingAcceptor(acceptor); + val selector = createSelector(context, myAcceptor) + context.firstSetGrammarElements.takeWhile[myAcceptor.canAcceptMoreProposals].forEach[selector.accept(it)] + + } finally { + handledArguments = null + } + + } + + override protected announceProcessing(List key) { + return handledArguments.add(key); + } + + // Keyword group stuff + @Inject extension RclGrammarAccess + + override complete_ModelFactory(EObject model, RuleCall ruleCall, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + modelFactoryAccess.group.createKeywordProposal(context, acceptor) + } + + override complete_CommandLoad(EObject model, RuleCall ruleCall, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + commandLoadAccess.group.createKeywordProposal(context, acceptor) + } + + override complete_CommandSave(EObject model, RuleCall ruleCall, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + commandSaveAccess.group.createKeywordProposal(context, acceptor) + } + + override complete_ModelTypeKW(EObject model, RuleCall ruleCall, ContentAssistContext context, + ICompletionProposalAcceptor acceptor) { + modelTypeKWAccess.group.createKeywordProposal(context, acceptor) + } + + def createKeywordProposal(Group group, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { + if (group === null) { + return null + } + val proposalString = group.elements.filter(Keyword).map[value].join(" ") + " " + acceptor.accept(createCompletionProposal(proposalString, proposalString, null, context)) + } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/labeling/RclDescriptionLabelProvider.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/labeling/RclDescriptionLabelProvider.xtend new file mode 100644 index 000000000..8a2175f9f --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/labeling/RclDescriptionLabelProvider.xtend @@ -0,0 +1,24 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.ui.labeling + +import org.eclipse.xtext.ui.label.DefaultDescriptionLabelProvider + +/** + * Provides labels for IEObjectDescriptions and IResourceDescriptions. + * + * See https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#label-provider + */ +class RclDescriptionLabelProvider extends DefaultDescriptionLabelProvider { + + // Labels and icons can be computed like this: + +// override text(IEObjectDescription ele) { +// ele.name.toString +// } +// +// override image(IEObjectDescription ele) { +// ele.EClass.name + '.gif' +// } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/labeling/RclLabelProvider.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/labeling/RclLabelProvider.xtend new file mode 100644 index 000000000..5966f00e1 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/labeling/RclLabelProvider.xtend @@ -0,0 +1,31 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.ui.labeling + +import com.google.inject.Inject +import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider +import org.eclipse.xtext.ui.label.DefaultEObjectLabelProvider + +/** + * Provides labels for EObjects. + * + * See https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#label-provider + */ +class RclLabelProvider extends DefaultEObjectLabelProvider { + + @Inject + new(AdapterFactoryLabelProvider delegate) { + super(delegate); + } + + // Labels and icons can be computed like this: + +// def text(Greeting ele) { +// 'A greeting to ' + ele.name +// } +// +// def image(Greeting ele) { +// 'Greeting.gif' +// } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/outline/RclOutlineTreeProvider.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/outline/RclOutlineTreeProvider.xtend new file mode 100644 index 000000000..d41b9deb6 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/outline/RclOutlineTreeProvider.xtend @@ -0,0 +1,174 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.ui.outline + +/* + * Copyright 2020 Carnegie Mellon University + + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR + * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE + * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +import org.eclipse.emf.ecore.EStructuralFeature +import org.eclipse.swt.graphics.Image +import org.eclipse.xtext.common.types.JvmType +import org.eclipse.xtext.ui.editor.outline.IOutlineNode +import org.eclipse.xtext.ui.editor.outline.impl.DefaultOutlineTreeProvider +import org.sa.rainbow.configuration.rcl.Assignment +import org.sa.rainbow.configuration.rcl.CommandCall +import org.sa.rainbow.configuration.rcl.CommandReference +import org.sa.rainbow.configuration.rcl.Component +import org.sa.rainbow.configuration.rcl.EffectorBody +import org.sa.rainbow.configuration.rcl.Factory +import org.sa.rainbow.configuration.rcl.GaugeBody +import org.sa.rainbow.configuration.rcl.GaugeTypeBody +import org.sa.rainbow.configuration.rcl.Probe +import org.sa.rainbow.configuration.rcl.PropertyReference +import org.sa.rainbow.configuration.rcl.RclPackage +import org.sa.rainbow.configuration.rcl.Reference + +/** + * Customization of the default outline structure. + * + * See https://www.eclipse.org/Xtext/documentation/310_eclipse_support.html#outline + */ +class RclOutlineTreeProvider extends DefaultOutlineTreeProvider { + + def Image nullImage() { + return null; + } + + def _createChildren(IOutlineNode parentNode, Component setup) { + for (Assignment a : setup.assignment) { + createNode(parentNode, a); + } + } + + def _createChildren(IOutlineNode parentNode, Assignment ass) { + if (ass.value !== null && ass.value.value !== null && ass.value.value instanceof Component) { + for (Assignment a : (ass.value.value as Component).assignment) { + createNode(parentNode, a) + } + } else + super._createChildren(parentNode, ass); + } + + def _createNode(IOutlineNode parentNode, GaugeTypeBody gtb) { + + var model = "" + val mcf = gtb.mcf + if (mcf instanceof Reference) { + if (mcf.referable instanceof JvmType) { + model = '''...«(mcf.referable as JvmType).simpleName»''' + } else if (mcf.referable instanceof Factory) { + model = '''...«(mcf.referable as Factory).name»''' + } + } if (mcf instanceof PropertyReference) { + if (mcf.referable instanceof Factory) { + model = '''...«(mcf.referable as Factory).name»''' + } + } else + createEObjectNode(parentNode, gtb.eContainer, nullImage(), model, true) + for (cmd : gtb.commands) { + super._createNode(parentNode, cmd) + } + for (ass : gtb.assignment) { + super._createNode(parentNode, ass) + } + } + + def _CreateNode(IOutlineNode parentNode, GaugeBody gtb) { + var model = "" + var EStructuralFeature ref = null + if (gtb.modelName != null || gtb.modeltype != null) { + model = '''«gtb.modelName===null?"":gtb.modelName»::«gtb.modeltype!=null?"":gtb.modeltype»''' + ref = RclPackage.Literals.GAUGE_BODY__MODEL_NAME + } else if (gtb.ref?.referable != null) { + model = '''«gtb.ref.referable.name»''' + ref = RclPackage.Literals.GAUGE_BODY__REF + } + if (ref !== null) { + createEStructuralFeatureNode(parentNode, gtb.eContainer, ref, nullImage(), model, true) + } else { + createEObjectNode(parentNode, gtb.eContainer, nullImage, model, true) + } + for (cmd : gtb.commands) { + super._createNode(parentNode, cmd) + } + for (ass : gtb.assignment) { + super._createNode(parentNode, ass) + } + } + + def _createNode(IOutlineNode parentNode, Probe probe) { + for (ass : probe?.properties?.assignment) { + super._createNode(parentNode, ass) + } + } + + def _createNode(IOutlineNode parentNode, EffectorBody body) { + var model = "" + var EStructuralFeature ref = null + if (body.modelName != null || body.modeltype != null) { + model = '''«body.modelName===null?"":body.modelName»::«body.modeltype!=null?"":body.modeltype»''' + ref = RclPackage.Literals.EFFECTOR_BODY__MODEL_NAME + } else if (body.ref?.referable != null) { + model = '''«body.ref.referable.name»''' + ref = RclPackage.Literals.EFFECTOR_BODY__REF + } + if (ref !== null) + createEStructuralFeatureNode(parentNode, body, ref, nullImage(), model, true) + else + createEObjectNode(parentNode, body.eContainer, nullImage, model, true) + for (ass : body.assignment) { + super._createNode(parentNode, ass) + } + } + + def _createNode(IOutlineNode parentNode, CommandReference cr) { + createEStructuralFeatureNode(parentNode, cr, RclPackage.Literals.COMMAND_REFERENCE__NAME, nullImage(), cr.name, + true) + } + + def _createNode(IOutlineNode parentNode, CommandCall cr) { + createEStructuralFeatureNode(parentNode, cr, RclPackage.Literals.COMMAND_CALL__NAME, nullImage(), cr.name, true) + } + + def _createNode(IOutlineNode parentNode, Assignment ass) { + if (ass.value !== null && ass.value.value !== null && ass.value.value instanceof Component) { + super._createNode(parentNode, ass); + + } else { + createEStructuralFeatureNode(parentNode, ass, RclPackage.Literals.ASSIGNMENT__NAME, nullImage(), ass.name, + true); + } + } + +// def _createChildren(IOutlineNode parentNode, Value v) { +// var value = v.value; +// if (value instanceof Component) { +// var comp = value as Component; +// for (Assignment a : comp.assignment) { +// createNode(parentNode, a) +// } +// } +// else { +// super._createChildren(parentNode,v); +// } +// +// } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/quickfix/RclQuickfixProvider.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/quickfix/RclQuickfixProvider.xtend new file mode 100644 index 000000000..becf25397 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/quickfix/RclQuickfixProvider.xtend @@ -0,0 +1,375 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.ui.quickfix + +/* + * Copyright 2020 Carnegie Mellon University + + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR + * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE + * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +import java.util.ArrayList +import java.util.LinkedList +import java.util.regex.Pattern +import org.eclipse.emf.ecore.EObject +import org.eclipse.xtext.nodemodel.ICompositeNode +import org.eclipse.xtext.nodemodel.ILeafNode +import org.eclipse.xtext.nodemodel.util.NodeModelUtils +import org.eclipse.xtext.ui.editor.model.IXtextDocument +import org.eclipse.xtext.ui.editor.model.edit.IModificationContext +import org.eclipse.xtext.ui.editor.model.edit.ISemanticModification +import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider +import org.eclipse.xtext.ui.editor.quickfix.Fix +import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionAcceptor +import org.eclipse.xtext.validation.Issue +import org.sa.rainbow.configuration.rcl.Component +import org.sa.rainbow.configuration.rcl.DeclaredProperty +import org.sa.rainbow.configuration.rcl.Effector +import org.sa.rainbow.configuration.rcl.EffectorBody +import org.sa.rainbow.configuration.rcl.Gauge +import org.sa.rainbow.configuration.rcl.GaugeBody +import org.sa.rainbow.configuration.rcl.Probe +import org.sa.rainbow.configuration.rcl.RclPackage +import org.sa.rainbow.configuration.validation.RclValidator + +/** + * Custom quickfixes. + * + * See https://www.eclipse.org/Xtext/documentation/310_eclipse_support.html#quick-fixes + */ +class RclQuickfixProvider extends DefaultQuickfixProvider { + + @Fix(RclValidator.COMMAND_NOT_IN_GAUGE_TYPE) + @Fix(RclValidator.NOT_VALID_GAUGE_COMMAND) + def renameCommand(Issue issue, IssueResolutionAcceptor acceptor) { + if (issue?.data?.length === 0) { + return + } + val possibleRenames = new LinkedList(); + for (name : issue.data.get(0).split(",")) { + possibleRenames.add(name) + } + + for (name : possibleRenames) { + acceptor.accept(issue, "Rename to " + name, "Rename the command", null) [ context | + val xtextDocument = context.xtextDocument + xtextDocument.replace(issue.offset, issue.length, name); + ] + } + } + + @Fix(RclValidator.ONLY_EXTEND_PROBE_TYPES) + @Fix(RclValidator.ONLY_EXTEND_EFFECTOR_TYPES) + def renameToProbeType(Issue issue, IssueResolutionAcceptor acceptor) { + if (issue?.data?.length == 0) { + return + } + var reference = "type" + if(issue.data.length == 2) reference = issue.data.get(1) + val possiblePTs = new LinkedList(); + for (name : issue.data.get(0).split(",")) { + acceptor.accept(issue, "Rename to " + name, "Refer to " + reference, null) [ context | + context.xtextDocument.replace(issue.offset, issue.length, name) + ] + + } + } + +// @Inject +// @Named(value="jvmtypes") +// private IJvmTypeProvider.Factory jvmTypeProviderFactory; +// +// @Inject +// private IJavaProjectProvider projectProvider +// +// @Inject +// private RawSuperTypes superTypeCollector; +// # From JdtTypesProvider +// @Fix(RclValidator.MUST_SUBCLASS) +// def getSubclasses(Issue issue, IssueResolutionAcceptor acceptor) { +// if (issue?.data?.length == 0) { +// return +// } +// val scName = issue.data.get(0) +// +// val modificationContext = modificationContextFactory.createModificationContext(issue); +// val xtextDocument = modificationContext.xtextDocument +// if(xtextDocument === null) return; +// +// xtextDocument.tryReadOnly(new CancelableUnitOfWork() { +// +// var IssueResolutionAcceptor myAcceptor; +// +// override exec(XtextResource state, CancelIndicator cancelIndicator) throws Exception { +// myAcceptor = getCancelableAcceptor(acceptor, cancelIndicator); +// val target = state.getEObject(issue.uriToProblem.fragment); +// val project = projectProvider.getJavaProject(target.eResource.resourceSet) +// if (project === null) { +// return null +// } +// val typeProvider = jvmTypeProviderFactory.createTypeProvider(target.eResource.resourceSet) +// val superclass = typeProvider.findTypeByName(scName) +// val superTypeIdentifier = superclass.identifier +// try { +// val superTypeNames = newHashSet +// val scope = createSearchScope(project, superclass, superTypeNames); +// searchAndCreateFixes(scope, myAcceptor, issue, new ITypesProposalProvider.Filter() { +// +// override accept(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) { +// if (path == null || path.endsWith(".class") || path.endsWith(".java")) { // Java index match +// val identifier = getIdentifier(packageName, simpleTypeName, enclosingTypeNames); +// if (!superTypeNames.contains(identifier)) { +// return true; +// } +// return false; +// } else { // accept match from dirty state +// val identifier = getIdentifier(packageName, simpleTypeName, enclosingTypeNames); +// if (identifier.equals(superTypeIdentifier)) { +// return true; +// } +// val candidate = typeProvider.findTypeByName(identifier, true); +// if (superTypeCollector.collect(candidate).contains(superclass)) { +// return true; +// } +// return false; +// } +// } +// +// +// +// override getSearchFor() { +// return IJavaSearchConstants.CLASS; +// } +// +// } +// ) +// } +// catch (JavaModelException ex) {} +// return null; +// +// } +// +// +// +// }) +// +// } +// +// def searchAndCreateFixes(IJavaSearchScope scope, IssueResolutionAcceptor acceptor, Issue issue, Filter filter) { +// val prefix = context.prefix +// } +// +// def getIdentifier(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames) { +// val result = new StringBuilder(packageName.length + simpleTypeName.length + 1) +// if (packageName.length !== 0) { +// result.append(packageName) +// result.append('.') +// } +// for (enclosingType : enclosingTypeNames) { +// result.append(enclosingType) +// result.append("$") +// } +// result.append(simpleTypeName) +// result.toString +// } +// +// def createSearchScope(IJavaProject project, JvmType superType, HashSet superTypeNames) { +// val type = project.findType(superType.getIdentifier()) +// if (type == null) { +// return new IntersectingJavaSearchScope +// } +// try { +// val result = SearchEngine.createStrictHierarchyScope(project, type, Boolean.TRUE, Boolean.TRUE, null) +// return result +// } catch (JavaModelException e) { +// val superTypes = superTypeCollector.collect(superType) +// for (collectedSuperType : superTypes) { +// superTypeNames.add(collectedSuperType.identifier) +// } +// superTypeNames.remove(superType.identifier) +// val hierarchyScope = SearchEngine.createHierarchyScope(type) +// val projectScope = SearchEngine.createJavaSearchScope(#[project]) +// return new IntersectingJavaSearchScope(projectScope, hierarchyScope) +// } +// } + +// @Fix(RclValidator.INVALID_NAME) +// def capitalizeName(Issue issue, IssueResolutionAcceptor acceptor) { +// acceptor.accept(issue, 'Capitalize name', 'Capitalize the name.', 'upcase.png') [ +// context | +// val xtextDocument = context.xtextDocument +// val firstLetter = xtextDocument.get(issue.offset, 1) +// xtextDocument.replace(issue.offset, 1, firstLetter.toUpperCase) +// ] +// } +// @Fix(RclValidator.MUST_SUBCLASS) +// def chooseSubclass(Issue issue, IssueResolutionAcceptor acceptor) { +// if (issue.data?.length != 1) return +// val subclasses = new LinkedList (); +// if (!issue.data.get(0).contains(",")) { +// subclasses.add(issue.data.get(0)); +// } +// else { +// for (sc : issue.data.get(0).split(",")) { +// subclasses.add(sc); +// } +// } +// for (sc : subclasses) { +// +// } +// } +// @Inject +// private ReplacingAppendable.Factory appendableFactory; + @Fix(RclValidator.MISSING_PROPERTY) + def addMissingProperty(Issue issue, IssueResolutionAcceptor acceptor) { + if (issue.data?.length === 0) { + return; + } + val possibleProperties = new LinkedList() + for (prop : issue.data.get(0).split(",")) { + possibleProperties.add(prop); + } + for (prop : possibleProperties) { + acceptor.accept( + issue, + "Add '" + prop + '"', + "Add '" + prop + '"', + null, + new ISemanticModification() { + + override apply(EObject element, IModificationContext context) throws Exception { + val document = context.xtextDocument + if (element instanceof Gauge) { + val gb = (element as Gauge).body + val insertOffset = getInsertOffset(gb) + val indent = getIndent(element as Gauge, insertOffset) + var t = "\n" + indent + prop + " = " + if (issue.data.length == 2 && issue.data.get(1) == Component.name) { + t = t + "{\n" + indent + "\t\n" + indent + "}" + + } + document.replace(insertOffset, 0, t); + } else if (element instanceof DeclaredProperty && + (element as DeclaredProperty).value.value instanceof Component) { + insertProperty((element as DeclaredProperty).value.value as Component, element, prop, document) + + } else if (element instanceof Probe) { + insertProperty((element as Probe).properties, element, prop, document) + } else if (element instanceof Effector) { + val eb = (element as Effector).body + val insertOffset = getInsertOffset(eb) + val indent = getIndent(element, insertOffset) + var t = "\n" + indent + prop + " = " + if (issue.data.length == 2 && issue.data.get(1) == Component.name) { + t = t + "{\n" + indent + "\t\n" + indent + "}" + + } + document.replace(insertOffset, 0, t); + } + } + + def insertProperty(Component into, EObject element, String prop, IXtextDocument document) { + val insertOffset = getInsertOffset(into) + val indent = getIndent(element, insertOffset) + var t = "\n" + indent + (into.assignment.empty ? "\t" : "") + prop + " = " + document.replace(insertOffset, 0, t) + } + + def getIndent(EObject g, int insertOffset) { + val root = NodeModelUtils.findActualNodeFor(g) + val r = determineOffset(root, insertOffset) + + // go backwards until first linewrap + val p = Pattern.compile("(\\n|\\r)([ \\t]*)"); + for (var i = r.size() - 1; i >= 0; i--) { + val m = p.matcher(r.get(i).getText()); + if (m.find()) { + var ind = m.group(2); + while (m.find()) + ind = m.group(2); + return ind; + } + } + return ""; + + } + + def determineOffset(ICompositeNode root, int fromOffset) { + val r = new ArrayList(); + // add all nodes until fromOffset + for (l : root.getLeafNodes()) { + if (l.getOffset() >= fromOffset) { + return r; + + } else { + r.add(l); + } + } + } + + def getInsertOffset(Component c) { + if (c.assignment.empty) { + val node = NodeModelUtils.findActualNodeFor(c) + val openingBraceNode = node.leafNodes.findFirst[text == "{"] + if (openingBraceNode !== null) { + openingBraceNode.offset + 1 + } else + node.offset + } else { + NodeModelUtils.findActualNodeFor(c.assignment.last).endOffset + } + } + + def getInsertOffset(EffectorBody gb) { + if (gb.assignment.empty) { + val node = NodeModelUtils.findActualNodeFor(gb) + val openingBraceNode = node.leafNodes.findFirst[text == "{"] + if (openingBraceNode !== null) { + openingBraceNode.offset + 1 + } else + node.offset + } else { + NodeModelUtils.findActualNodeFor(gb.command).endOffset + } + } + + def getInsertOffset(GaugeBody gb) { + if (gb.assignment.empty) { + val node = NodeModelUtils.findActualNodeFor(gb) + val openingBraceNode = node.leafNodes.findFirst[text == "{"] + if (openingBraceNode !== null) { + openingBraceNode.offset + 1 + } else + node.offset + } else if (!gb.commands.empty) { + NodeModelUtils.findActualNodeFor(gb.commands.last).endOffset + } else if (gb.modeltype !== null) { + NodeModelUtils.findNodesForFeature(gb, RclPackage.Literals.GAUGE_BODY__MODELTYPE).last. + endOffset + } + return NodeModelUtils.findNodesForFeature(gb, RclPackage.Literals.GAUGE_BODY__REF).last. + endOffset + + } + + } + ) + } + } +} + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/Messages.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/Messages.java new file mode 100644 index 000000000..7202fa538 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/Messages.java @@ -0,0 +1,26 @@ +package org.sa.rainbow.configuration.ui.wizard; + +import org.eclipse.osgi.util.NLS; + +public class Messages extends NLS { + private static final String BUNDLE_NAME = "org.sa.rainbow.configuration.ui.wizard.messages"; //$NON-NLS-1$ + + public static String HelloWorldProject_Label; + public static String HelloWorldProject_Description; + public static String RainbowProject_Label; + public static String RainbowProject_Description; + public static String RainbowProjectWithTargetDefinition_Label; + public static String RainbowProjectWithTargetDefinition_Description; + public static String HelloWorldFile_Label; + public static String HelloWorldFile_Description; + public static String RainbowTarget_Label; + public static String RainbowTarget_Description; + + static { + // initialize resource bundle + NLS.initializeMessages(BUNDLE_NAME, Messages.class); + } + + private Messages() { + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/ProjectHelper.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/ProjectHelper.xtend new file mode 100644 index 000000000..5e4728df2 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/ProjectHelper.xtend @@ -0,0 +1,124 @@ +package org.sa.rainbow.configuration.ui.wizard +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import java.io.BufferedReader +import java.io.IOException +import java.io.InputStreamReader +import java.net.URL +import java.util.Map +import java.util.regex.Pattern + +class ProjectHelper { + + + + static def generateReplacements(String projectName, String deploymentType, String customDeployment, String mfName, String sgp, String rbg, String rbs, boolean acme) { + val replacements = newLinkedHashMap( + 'rainbow-target' -> projectName, + 'rainbowVersion' -> '3.0', + 'gauges.rbw' -> "model/gauges.rbw", + 'deploymentFactory' -> (deploymentType=="Single Machine"?"org.sa.rainbow.core.ports.guava.GuavaRainbowPortFactory":(deploymentType=="Multiple Machines"?"org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory":customDeployment)), + 'AnalysisName' -> "anAnalysis", + 'AnalysisClass' -> 'org.sa.rainbow.core.analysis.IRainbowAnalysis # Change this to a real class', + 'AdaptationManagerName' -> 'anAdaptationManager', + 'AdaptationClass' -> 'org.sa.rainbow.core.adaptation.org.sa.rainbow.core.adaptation # Change this to a real class', + 'ExecutorName' -> 'anExecutor', + 'ExectorClass' -> 'org.sa.rainbow.core.adaptation.IAdaptationExecutor # Change this to a real class', + 'EffectorManagerName' -> 'anEffectorManager', + 'EffectorManagerClass' -> 'org.sa.rainbow.translator.effectors.EffectorManager # Change this to a real class', + 'GUISpecs' -> '', + 'factoryName' -> mfName, + 'srcGenPackage' -> sgp, + 'rbwGen.value' -> rbg, + 'rbwSrc.value' -> rbs + ) + if (acme) { + val AandSDefaults = newLinkedHashMap( + 'AnalysisName' -> "ArchEvaluator", + 'AnalysisClass' -> 'org.sa.rainbow.evaluator.^acme.ArchEvaluator', + 'AdaptationManagerName' -> 'AdaptationManager', + 'AdaptationManagerClass' -> 'org.sa.rainbow.^stitch.adaptation.AdaptationManager', + 'ExecutorName' -> 'StitchExecutor', + 'ExectorClass' -> 'org.sa.rainbow.^stitch.adaptation.StitchExecutor', + 'EffectorManagerName' -> 'AcmeEffectorManager', + 'EffectorManagerClass' -> 'org.sa.rainbow.effectors.^acme.AcmeEffectorManager', + 'GUISpecs' -> " + analyzers = { + analyzer = { + ^for = ««ArchEvaluator»» + class = org.sa.rainbow.evaluator.^acme.^gui.ArchAnalyzerGUI + } + } + managers = { + manager = { + ^for = ««AdaptationManager»» + class = org.sa.rainbow.^stitch.^gui.manager.ArchStitchAdapationManager + } + } + executors = { + ^executor = { + ^for = ««StitchExecutor»» + class = org.sa.rainbow.^stitch.^gui.^executor.EventBasedStitchExecutorPanel + } + } + details = { + managers = org.sa.rainbow.^stitch.^gui.manager.StitchAdaptationManagerTabbedPane + executors = org.sa.rainbow.^stitch.^gui.^executor.StitchExecutorTabbedPane + }" + ) + replacements.putAll(AandSDefaults) + + } + replacements + } + + static def generatePattern(Map replacements) { + val patternString = "<<(" + replacements.keySet.join("|") + ")>>" + var pattern = Pattern.compile(patternString); + pattern + } + + static def readFile(String fileName, Map replacements, Pattern pattern) { + var sb = new StringBuffer + try (val in = new BufferedReader(new InputStreamReader(new URL("platform:/plugin/org.sa.rainbow.configuration.ui/" + fileName).openConnection.inputStream))) { + var inputLine = "" + while ((inputLine = in.readLine) !== null) { + sb.append(inputLine) + sb.append("\n") + } + } + catch (IOException e) {} + var ret = sb.toString + + val matcher = pattern.matcher(ret) + sb = new StringBuffer(ret.length << 1) + while (matcher.find()) { + matcher.appendReplacement(sb, replacements.get(matcher.group(1))); + } + matcher.appendTail(sb) + + + sb.toString + + + } + + +} \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/RclFileTemplateProvider.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/RclFileTemplateProvider.xtend new file mode 100644 index 000000000..00ecb19ca --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/RclFileTemplateProvider.xtend @@ -0,0 +1,89 @@ +/* + * generated by Xtext 2.20.0 + */ +package org.sa.rainbow.configuration.ui.wizard +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import java.nio.file.Paths +import org.eclipse.xtext.ui.wizard.template.FileTemplate +import org.eclipse.xtext.ui.wizard.template.IFileGenerator +import org.eclipse.xtext.ui.wizard.template.IFileTemplateProvider + +/** + * Create a list with all file templates to be shown in the template new file wizard. + * + * Each template is able to generate one or more files. + */ +class RclFileTemplateProvider implements IFileTemplateProvider { + override getFileTemplates() { + #[new RainbowTarget] + } +} + +@FileTemplate(label="Rainbow Target", icon="file_template.png", description="Create a target definition with default files") +class RainbowTarget { + + val advanced = check("Advanced Properties:", false) + val advancedGroup = group("Properties:") + val deploymentType = combo("Deployment style:", #["Single Machine", "Multiple Machines", "Custom Deployment"], "The deployment type of Rainbow", advancedGroup); + val customDeployment = text("Port Factory", "", "Specify the port factory to use", advancedGroup); + + val useAcmeAndStitch = check('Use Acme and Stitch', true, advancedGroup) + + new() { + super() + } + + override protected updateVariables() { + + advancedGroup.enabled = advanced.value + deploymentType.enabled = advanced.value + customDeployment.enabled = advanced.value && deploymentType.value=="Custom Deployment" + useAcmeAndStitch.enabled = advanced.value + if (!advanced.value) { + deploymentType.value = "Single Machine" + customDeployment.value = deploymentType.value + useAcmeAndStitch.value = true + } + } + + override protected validate() { + super.validate() + } + + override generateFiles(IFileGenerator generator) { + val replacements = ProjectHelper.generateReplacements(name, deploymentType.value, customDeployment.value, "", + "src/main/java", Paths.get(Paths.get(folder).parent.toAbsolutePath.toString, "generated").toAbsolutePath.toString, folder, useAcmeAndStitch.value + ) + val p = ProjectHelper.generatePattern(replacements) + val tgtLoc = folder + "/" + name + generator.generate(tgtLoc + "/rainbow.properties", ProjectHelper.readFile("templates/properties.rbw_template", replacements, p)) + generator.generate(tgtLoc + "/model/gauges.rbw", ProjectHelper.readFile("templates/gauges.rbw_default", replacements, p)) + generator.generate(tgtLoc + "/system/probes.rbw", ProjectHelper.readFile("templates/probes.rbw_default", replacements, p)) + generator.generate(tgtLoc + "/system/effectors.rbw", ProjectHelper.readFile("templates/effectors.rbw_default", replacements, p)) + if (useAcmeAndStitch.value) { + generator.generate(tgtLoc + "/stitch/stitch.s", "// Edit to add StitchsStrategies and tactics") + generator.generate(tgtLoc + "/model/model.acme", "// Edit to add Acme model") + generator.generate(tgtLoc + "/stitch/utilities.rbw", ProjectHelper.readFile('templates/utilities.rbw_default', replacements, p)) + } + } + +} + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/RclProjectTemplateProvider.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/RclProjectTemplateProvider.xtend new file mode 100644 index 000000000..1d5a7dea1 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/RclProjectTemplateProvider.xtend @@ -0,0 +1,159 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.ui.wizard +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import java.io.BufferedReader +import java.io.IOException +import java.io.InputStreamReader +import java.net.URL +import java.util.HashMap +import java.util.regex.Pattern +import org.eclipse.core.runtime.Status +import org.eclipse.xtext.ui.XtextProjectHelper +import org.eclipse.xtext.ui.util.JavaProjectFactory +import org.eclipse.xtext.ui.util.ProjectFactory +import org.eclipse.xtext.ui.wizard.template.IProjectGenerator +import org.eclipse.xtext.ui.wizard.template.IProjectTemplateProvider +import org.eclipse.xtext.ui.wizard.template.ProjectTemplate + +import static org.eclipse.core.runtime.IStatus.* + +/** + * Create a list with all project templates to be shown in the template new project wizard. + * + * Each template is able to generate one or more projects. Each project can be configured such that any number of files are included. + */ +class RclProjectTemplateProvider implements IProjectTemplateProvider { + override getProjectTemplates() { + #[new RainbowProject] + } +} + +@ProjectTemplate(label="Rainbow Deployment", icon="rainbow.png", description="

Rainbow Deployment

+

This is a deployment project for Rainbow. You can set a parameters to modify the src diretories and the rainbow directories.

") +public class RainbowProject { + + + val advanced = check("File Layout:", false) + val advancedGroup = group("Properties:") + val generateJavaCode = check("Generate Java source", true, advancedGroup) + val srcPackage = text("Source package:", "src/main/java/", "The directory to place Java source files.", advancedGroup) + val srcGenPackage = text("Generated source:", "src/main/java-gen", "The directory to place generated Java source files", advancedGroup) + val rbwSrc = text("Target definitions:", "src/main/resources/rbw", "The directory to place Rainbow target definitions", advancedGroup) + val rbwGen = text("Generated target files:", "src/main/resources/generated", "The directory to place generated target files", advancedGroup) + val createRCLFiles = check("Generate RCL file templates", true) + val targetSpecifiction = group("Target Contents:") + + val deploymentType = combo("Deployment style:", #["Single Machine", "Multiple Machines", "Custom Deployment"], "The deployment type of Rainbow", targetSpecifiction); + val customDeployment = text("Port Factory", "", "Specify the port factory to use", targetSpecifiction); + val useAcmeAndStitch = check('Use Acme and Stitch', true, targetSpecifiction) + val generateRCLModelFactory = check("Generate RCL model factory", true, targetSpecifiction) + val modelFactoryName = text("Model Factory:", "DefaultModelFactory", targetSpecifiction) + override protected updateVariables () { + generateJavaCode.enabled = advanced.value + srcPackage.enabled = advanced.value && generateJavaCode.value + rbwSrc.enabled = advanced.value + srcGenPackage.enabled = advanced.value + rbwGen.enabled = advanced.value + if (!advanced.value) { + rbwSrc.value = "src/main/resources/rbw" + if (generateJavaCode.value) + srcPackage.value="src/main/java/" + + } + + targetSpecifiction.enabled = createRCLFiles.value + if (!createRCLFiles.value) { + deploymentType.value="Single Machine" + useAcmeAndStitch.value = true + } + deploymentType.enabled = createRCLFiles.value + useAcmeAndStitch.enabled = createRCLFiles.value + customDeployment.enabled = deploymentType.value == "Custom Deployment" + if (deploymentType != "Custom Deployment") { + customDeployment.value = deploymentType.value + } + generateRCLModelFactory.enabled = createRCLFiles.value + modelFactoryName.enabled = createRCLFiles.value && generateRCLModelFactory.value + + } + + override protected validate() { + if (generateJavaCode.value && !srcPackage.value.matches('[a-z][a-z0-9_]*(/[a-z][a-z0-9_]*)*')) + new Status(ERROR, "Wizard", '''Path '«srcPackage»' is not a valid package name''') + if (rbwSrc.value.matches('[a-z][a-z0-9_]*(/[a-z][a-z0-9_]*)*')) + null + else + new Status(ERROR, "Wizard", '''Path '«rbwSrc»' is not a valid package name''') + } + + + + def addProjectFiles(JavaProjectFactory tgt) { + + val replacements = ProjectHelper.generateReplacements(projectInfo.projectName, deploymentType.value, customDeployment.value, modelFactoryName.value, + srcGenPackage.value, rbwGen.value, rbwSrc.value, useAcmeAndStitch.value + ) + + val pattern = ProjectHelper.generatePattern(replacements) + tgt.addFile("pom.xml", ProjectHelper.readFile("templates/pom.xml_default", replacements, pattern)) + if (createRCLFiles.value) { + val tgtLoc = rbwSrc.value + "/" + projectInfo.projectName + tgt.addFile( + tgtLoc + "/properties.rbw", + ProjectHelper.readFile("templates/properties.rbw_template", replacements, pattern) + ) + tgt.addFile(tgtLoc + "/model/gauges.rbw", ProjectHelper.readFile("templates/gauges.rbw_default", replacements, pattern)) + tgt.addFile(tgtLoc + "/system/probes.rbw", ProjectHelper.readFile("templates/probes.rbw_default", replacements, pattern)) + tgt.addFile(tgtLoc + "/system/effectors.rbw", ProjectHelper.readFile("templates/effectors.rbw_default", replacements, pattern)) + + if (useAcmeAndStitch.value) { + tgt.addFile(tgtLoc + "/stitch/stitch.s", "// Edit to add StitchsStrategies and tactics") + tgt.addFile(tgtLoc + "/model/model.acme", "// Edit to add Acme model") + tgt.addFile(tgtLoc + "/stitch/utilities.rbw", ProjectHelper.readFile('templates/utilities.rbw_default', replacements, pattern)) + } + if (generateRCLModelFactory.value) { + tgt.addFile(rbwSrc + "/" + modelFactoryName.value + ".rbw", ProjectHelper.readFile("templates/modelfactory.rbw_default", replacements, pattern)) + } + } + } + + + + override generateProjects(IProjectGenerator generator) { + generator.generate(new JavaProjectFactory => [ + projectName = projectInfo.projectName + location = projectInfo.locationPath + projectNatures += XtextProjectHelper.NATURE_ID + builderIds += XtextProjectHelper.BUILDER_ID + folders += rbwSrc.value + if (generateJavaCode.value) { + projectNatures += #["org.eclipse.jdt.core.javanature", "org.eclipse.m2e.core.maven2Nature"] + builderIds += #["org.eclipse.m2e.core.maven2Builder", "org.eclipse.jdt.core.javabuilder"] + addSourceFolder(srcPackage.value, "target/classes", false) + addSourceFolder(srcGenPackage.value, "target/classes", false) + } + addProjectFiles(it) + ]) + } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/TemplateNewTargetWizard.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/TemplateNewTargetWizard.java new file mode 100644 index 000000000..ae20108b7 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/TemplateNewTargetWizard.java @@ -0,0 +1,113 @@ +package org.sa.rainbow.configuration.ui.wizard; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.util.Map; +import java.util.SortedMap; +import java.util.Stack; +import java.util.TreeMap; + +import org.apache.log4j.Logger; +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.SubMonitor; +import org.eclipse.ui.actions.WorkspaceModifyOperation; +import org.eclipse.xtext.ui.wizard.template.AbstractFileTemplate; +import org.eclipse.xtext.ui.wizard.template.IFileGenerator; +import org.eclipse.xtext.ui.wizard.template.TemplateFileInfo; +import org.eclipse.xtext.ui.wizard.template.TemplateNewFileWizard; +import org.eclipse.xtext.util.StringInputStream; + +public class TemplateNewTargetWizard extends TemplateNewFileWizard { + public class TargetFileGenerator extends WorkspaceModifyOperation implements IFileGenerator { + private final SortedMap files = new TreeMap<>(); + + @Override + public void generate(CharSequence path, CharSequence content) { + files.put(path.toString(), content); + } + + + + @Override + protected void execute(IProgressMonitor monitor) + throws CoreException, InvocationTargetException, InterruptedException { + SubMonitor subMonitor = SubMonitor.convert(monitor, files.size()); + try { + IWorkspace workspace = ResourcesPlugin.getWorkspace(); + for (Map.Entry fileEntry : files.entrySet()) { + + + Path path = new Path(fileEntry.getKey()); + IFile file = workspace.getRoot().getFile(path); + File pt = new File(workspace.getRoot().getLocation().toFile(), file.getFullPath().toFile().getPath()); + + File parent = pt.getParentFile(); + Stack dir = new Stack<>(); + IContainer parent2 = file.getParent(); + while (!parent2.exists()) { + dir.push(parent2.getName()); + parent2 = parent2.getParent(); + } + while (!dir.isEmpty()) { + parent2 = ((IFolder )parent2).getFolder(dir.pop()); + ((IFolder )parent2).create(true, true, subMonitor); + } + + file.create(new StringInputStream(fileEntry.getValue().toString()), true, subMonitor); + } + + } + catch (Exception e) { + System.out.println(e.getMessage()); + } + finally { + subMonitor.done(); + } + + } + + } + + private static final Logger logger = Logger.getLogger(TemplateNewFileWizard.class); + + @Override + protected void doFinish(TemplateFileInfo info, IProgressMonitor monitor) { + try { + AbstractFileTemplate fileTemplate = info.getFileTemplate(); + TargetFileGenerator fileGenerator = new TargetFileGenerator(); + + fileTemplate.generateFiles(fileGenerator); + fileGenerator.run(monitor); + } catch (final InvocationTargetException e) { + logger.error(e.getMessage(), e); + } catch (final InterruptedException e) { + // cancelled by user, ok + return; + } + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/messages.properties b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/messages.properties new file mode 100644 index 000000000..38289e0e1 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/src/org/sa/rainbow/configuration/ui/wizard/messages.properties @@ -0,0 +1,69 @@ +HelloWorldProject_Label=Hello World +HelloWorldProject_Description=

Hello World

This is a parameterized hello world for RCL. You can set a parameter to modify the content in the generated file and a parameter to set the package the file is created in.

+ +RainbowProject_Label=Rainbow Deployment +RainbowProject_Description=

Rainbow Deployment

This is a deployment project for Rainbow. You can set a parameters to modify the src diretories and the rainbow directories.

+ + +RainbowProjectWithTargetDefinition_Label=Rainbow Project with Target +RainbowProjectWithTargetDefinition_Description=

Rainbow Project with Template

This Rainbow project also includes a example target definition, with default files generated in the default positions

+HelloWorldFile_Label=Hello World +HelloWorldFile_Description=Create a hello world for RCL. +RainbowTarget_Label=Rainbow Target +RainbowTarget_Description=Create a target definition with default files + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/effectors.rbw_default b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/effectors.rbw_default new file mode 100644 index 000000000..71308d092 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/effectors.rbw_default @@ -0,0 +1,7 @@ +target <> +import properties "../properties.rbw" + +# Define effectors here + + +export * to "system/effectors.yml" \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/gauges.rbw_default b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/gauges.rbw_default new file mode 100644 index 000000000..1f92f8718 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/gauges.rbw_default @@ -0,0 +1,9 @@ +target <> +import properties "../properties.rbw" + +# Insert gauge types and gauge specifications + + + + +export * to "model/gauges.yml" \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/modelfactory.rbw_default b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/modelfactory.rbw_default new file mode 100644 index 000000000..94a750e9b --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/modelfactory.rbw_default @@ -0,0 +1,5 @@ + +model factory <> yields AFactoryClass { + + command load is ... +} \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/pom.xml_default b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/pom.xml_default new file mode 100644 index 000000000..83cee37e4 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/pom.xml_default @@ -0,0 +1,328 @@ + + 4.0.0 + rainbow + <> + 3.0 + + + utf-8 + + + + + + + org.apache.maven.wagon + wagon-webdav + 1.0-beta-2 + + + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.2 + + + + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.4 + + + http://svn.homenet/svn/projects/incubator/tags + + + + + + + org.codehaus.mojo + buildnumber-maven-plugin + 1.1 + + + validate + + create + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + <> + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + test-jar + + + + + + + + true + + + + + ${buildNumber} + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12.4 + + -XX:-UseSplitVerifier + true + + + ${basedir} + + + + + + + + maven-dependency-plugin + + + install + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + org.eclipse.xtext + xtext-maven-plugin + 2.19.0 + + + + generate + + + + + 1.8 + 1.8 + + + org.sa.rainbow.configuration.RclStandaloneSetup + + + src/main/java-gen + + + <> + true + true + true + + + + + org.sa.rainbow.stitch.StitchStandaloneSetup + + + <> + true + true + true + + + + + org.acme.AcmeStandaloneSetup + + + <> + true + true + true + + + + + + <> + + + + + org.eclipse.emf + org.eclipse.emf.mwe2.launch + 2.11.0 + + + org.eclipse.xtext + org.eclipse.xtext.common.types + 2.19.0 + + + org.eclipse.xtext + org.eclipse.xtext.xtext.generator + 2.19.0 + + + org.eclipse.xtext + org.eclipse.xtext.xbase + 2.19.0 + + + org.eclipse.xtext + xtext-antlr-generator + 2.1.1 + + + + io.typefox.xtext + jflex-fragment + 0.2.1 + + + org.eclipse.xtext + org.eclipse.xtext.xbase.lib + 2.18.0 + + + + org.sa.rainbow.stitch + org.sa.rainbow.stitch + 1.0.0-SNAPSHOT + + + + org.acme.xtext + org.acme.xtext + 1.0.0-SNAPSHOT + + + + org.sa.rainbow.configuration + org.sa.rainbow.configuration + 1.0.0-SNAPSHOT + + + + + + + + + + + rainbow + rainbow-acme-model + <> + + + rainbow + rainbow-stitch + <> + + + rainbow + rainbow-utility-model + <> + + + rainbow + rainbow-gui + <> + + + rainbow + rainbow-mem-comms + <> + + + xerces + xercesImpl + 2.9.1 + + + org.jfree + jfreechart + 1.5.0 + + + \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/probes.rbw_default b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/probes.rbw_default new file mode 100644 index 000000000..93b1e99ad --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/probes.rbw_default @@ -0,0 +1,9 @@ +target <> +import properties "../properties.rbw" +# Define any probe properties + +# Define probe types and probes here + + + +export * to "system/probes.yml" \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/properties.rbw_template b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/properties.rbw_template new file mode 100644 index 000000000..9201eca27 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/properties.rbw_template @@ -0,0 +1,86 @@ +target <> +import properties "<>" + +############################################################################### +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. +def rainbow.path # Default property defined by rainbow + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +def logging.level = DEBUG +def event.log.path = "log" +def logging.path = "«event.log.path»/rainbow.out" +def monitoring.log.path = "«event.log.path»/rainbow-data.log" +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +def rainbow.master.location.host = +#- Location information of the deployed delegate +def rainbow.deployment.location = +#- default registry port; change if port-tunneling +def rainbow.master.location.^port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +def rainbow.deployment.environment = "linux" + +def rainbow.delegate.beaconperiod = 10000 +def rainbow.deployment.^factory.class = <> + +# Define your models here +def model aModel = { + ^type = "" + path = "" + ^factory= +} + +# Define your analysis here +def analysis <> = { + class = <> +} + +# Define your Adaptation Manager here +def adaptation-manager <> = { + ^model = + class= <> +} + +# Define your executors here +def executor <> = { + ^model = + class = <> +} + +# Define effector managers here +def effector-manager <> = { + class = <> +} + +def gui rainbow.^gui = { + class = org.sa.rainbow.^gui.RainbowWindoe + specs = { + <> + } +} + +# Define any system/target-specific properties here + + +export * to "rainbow.properties" \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/utilities.rbw_default b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/utilities.rbw_default new file mode 100644 index 000000000..6c53a70df --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration.ui/templates/utilities.rbw_default @@ -0,0 +1,29 @@ +target <> +import properties "../properties.rbw" +import stitch "stitch.s" + +# Define the utility model +def utility utilityModel = { + ^model = + utilities = { + utility1 = { + label = "some label" + mapping = "how do derive this from the Acme model" + description = "some description" + ^utility = [ [0, 0] ... ] + } + } + scenarios = [ + { + name= "scenario 1", + utility1= 1.0 + } + ] +} + +# For each tactic defined in "stitch.s", define an impact +impact ««utilityModel»» tactic1 = { + utility1 = -1 +} + +export * to "stitch/utilities.yml" \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.antlr-generator-3.2.0-patch.jar b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.antlr-generator-3.2.0-patch.jar new file mode 100644 index 000000000..90516fd7a Binary files /dev/null and b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.antlr-generator-3.2.0-patch.jar differ diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.classpath b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.classpath new file mode 100644 index 000000000..0a639c992 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.classpath @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.launch/Generate ConfigModel (rbw) Language Infrastructure.launch b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.launch/Generate ConfigModel (rbw) Language Infrastructure.launch new file mode 100644 index 000000000..a2215eb62 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.launch/Generate ConfigModel (rbw) Language Infrastructure.launch @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.launch/Launch Runtime Eclipse.launch b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.launch/Launch Runtime Eclipse.launch new file mode 100644 index 000000000..637a2b6ef --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.launch/Launch Runtime Eclipse.launch @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.project b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.project new file mode 100644 index 000000000..98012d64a --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.project @@ -0,0 +1,46 @@ + + + org.sa.rainbow.configuration + + + + + + net.certiv.antlrdt.core.builder + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.xtext.ui.shared.xtextNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.PluginNature + net.certiv.antlrdt.core.nature + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.settings/org.eclipse.jdt.core.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..0c68a61dc --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.settings/org.eclipse.xtend.core.Xtend.prefs b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.settings/org.eclipse.xtend.core.Xtend.prefs new file mode 100644 index 000000000..fdf3191a5 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/.settings/org.eclipse.xtend.core.Xtend.prefs @@ -0,0 +1,7 @@ +//outlet.DEFAULT_OUTPUT.sourceFolder.src/main/java.directory=xtend-gen +//outlet.DEFAULT_OUTPUT.sourceFolder.src/test/java.directory=xtend-gen +BuilderConfiguration.is_project_specific=true +eclipse.preferences.version=1 +outlet.DEFAULT_OUTPUT.hideLocalSyntheticVariables=true +outlet.DEFAULT_OUTPUT.installDslAsPrimarySource=false +outlet.DEFAULT_OUTPUT.userOutputPerSourceFolder=true diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/ANTLRLEXER.md b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/ANTLRLEXER.md new file mode 100644 index 000000000..c658fb6ed --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/ANTLRLEXER.md @@ -0,0 +1 @@ +The custom lexer needs to be regenerated everytime the xtext grammar changes. \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/META-INF/MANIFEST.MF b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/META-INF/MANIFEST.MF new file mode 100644 index 000000000..dc3e09c0d --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/META-INF/MANIFEST.MF @@ -0,0 +1,40 @@ +Manifest-Version: 1.0 +Automatic-Module-Name: org.sa.rainbow.configuration +Bundle-ManifestVersion: 2 +Bundle-Name: org.sa.rainbow.configuration +Bundle-Vendor: My Company +Bundle-Version: 1.0.1.qualifier +Bundle-SymbolicName: org.sa.rainbow.configuration; singleton:=true +Bundle-ActivationPolicy: lazy +Require-Bundle: org.eclipse.xtext, + org.eclipse.xtext.xbase, + org.eclipse.equinox.common;bundle-version="3.5.0", + org.eclipse.emf.ecore, + org.eclipse.xtext.xbase.lib;bundle-version="2.14.0", + org.eclipse.xtext.util, + org.eclipse.emf.common, + org.eclipse.xtend.lib;bundle-version="2.14.0", + org.antlr.runtime;bundle-version="[3.2.0,3.2.1)", + org.objectweb.asm;bundle-version="[7.1.0,7.2.0)";resolution:=optional, + org.eclipse.xtext.common.types, + org.sa.rainbow.stitch;bundle-version="1.0.0", + org.acme.xtext;bundle-version="1.0.0" +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Import-Package: org.apache.log4j +Bundle-ClassPath: ., + lib/rainbow-acme-model.jar, + lib/rainbow-core.jar, + lib/rainbow-gui.jar, + lib/rainbow-stitch.jar, + lib/rainbow-utility-model.jar +Export-Package: org.sa.rainbow.configuration, + org.sa.rainbow.configuration.rcl, + org.sa.rainbow.configuration.rcl.impl, + org.sa.rainbow.configuration.rcl.util, + org.sa.rainbow.configuration.generator, + org.sa.rainbow.configuration.parser.antlr, + org.sa.rainbow.configuration.parser.antlr.internal, + org.sa.rainbow.configuration.scoping, + org.sa.rainbow.configuration.serializer, + org.sa.rainbow.configuration.services, + org.sa.rainbow.configuration.validation diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/antlrworks-1.5.2-complete.jar b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/antlrworks-1.5.2-complete.jar new file mode 100644 index 000000000..9b71ab0c7 Binary files /dev/null and b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/antlrworks-1.5.2-complete.jar differ diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/build.properties b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/build.properties new file mode 100644 index 000000000..5db7aaebf --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/build.properties @@ -0,0 +1,25 @@ +source.. = src/,\ + src-gen/,\ + xtend-gen/ +bin.includes = model/generated/,\ + .,\ + META-INF/,\ + plugin.xml,\ + lib/rainbow-acme-model.jar,\ + lib/rainbow-core.jar,\ + lib/rainbow-gui.jar,\ + lib/rainbow-stitch.jar,\ + lib/rainbow-utility-model.jar +bin.excludes = **/*.mwe2,\ + **/*.xtend +additional.bundles = org.eclipse.xtext.xbase,\ + org.eclipse.xtext.common.types,\ + org.eclipse.xtext.xtext.generator,\ + org.eclipse.emf.codegen.ecore,\ + org.eclipse.emf.mwe.utils,\ + org.eclipse.emf.mwe2.launch,\ + org.eclipse.emf.mwe2.lib,\ + org.objectweb.asm,\ + org.apache.commons.logging,\ + org.apache.log4j,\ + com.ibm.icu diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/plugin.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/plugin.xml new file mode 100644 index 000000000..c35150a16 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/plugin.xml @@ -0,0 +1,10 @@ + + + + + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/pom.xml b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/pom.xml new file mode 100644 index 000000000..1473d2d41 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/pom.xml @@ -0,0 +1,281 @@ + + 4.0.0 + + org.sa.rainbow.configuration + org.sa.rainbow.configuration.parent + 1.0.1-SNAPSHOT + + org.sa.rainbow.configuration + eclipse-plugin + + + + + org.apache.maven.wagon + wagon-webdav + 1.0-beta-2 + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libraries + initialize + + copy + + + ${basedir}/lib/ + true + true + true + true + + + rainbow + rainbow-core + ${rainbowVersion} + + + rainbow + rainbow-utility-model + ${rainbowVersion} + + + rainbow + rainbow-gui + ${rainbowVersion} + + + rainbow + rainbow-acme-model + ${rainbowVersion} + + + rainbow + rainbow-stitch + ${rainbowVersion} + + + org.acme.xtext + org.acme.xtext + 1.0.0-SNAPSHOT + + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + mwe2Launcher + generate-sources + + java + + + + + org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher + + /${project.basedir}/src/org/sa/rainbow/configuration/GenerateRCL.mwe2 + -p + rootPath=/${project.basedir}/.. + + compile + true + false + + + + rainbow + rainbow-core + ${rainbowVersion} + + + rainbow + rainbow-utility-model + ${rainbowVersion} + + + rainbow + rainbow-gui + ${rainbowVersion} + + + rainbow + rainbow-acme-model + ${rainbowVersion} + + + rainbow + rainbow-stitch + ${rainbowVersion} + + + org.eclipse.emf + org.eclipse.emf.mwe2.launch + 2.11.0 + + + org.eclipse.xtext + org.eclipse.xtext.common.types + ${xtextVersion} + + + org.eclipse.xtext + org.eclipse.xtext.xtext.generator + ${xtextVersion} + + + org.eclipse.xtext + org.eclipse.xtext.xbase + ${xtextVersion} + + + org.eclipse.xtext + xtext-antlr-generator + 2.1.1 + + + + io.typefox.xtext + jflex-fragment + 0.2.1 + + + + + + org.eclipse.xtend + xtend-maven-plugin + + + + + + org.apache.maven.plugins + maven-clean-plugin + + + + ${basedir}/../org.sa.rainbow.configuration/src-gen/ + + **/* + + + + ${basedir}/../org.sa.rainbow.configuration.tests/src-gen/ + + **/* + + + + ${basedir}/../org.sa.rainbow.configuration.ide/src-gen/ + + **/* + + + + ${basedir}/../org.sa.rainbow.configuration.ui/src-gen/ + + **/* + + + + ${basedir}/../org.sa.rainbow.configuration.ui.tests/src-gen/ + + **/* + + + + ${basedir}/model/generated/ + + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.codehaus.mojo + + + exec-maven-plugin + + + [1.2.1,) + + + java + + + + + + + + + + + + + + + + + rainbow + rainbow-core + ${rainbowVersion} + + + rainbow + rainbow-utility-model + ${rainbowVersion} + + + rainbow + rainbow-gui + ${rainbowVersion} + + + rainbow + rainbow-acme-model + ${rainbowVersion} + + + rainbow + rainbow-stitch + ${rainbowVersion} + + + org.sa.rainbow.stitch + org.sa.rainbow.stitch + 1.0.0-SNAPSHOT + + + org.acme.xtext + org.acme.xtext + 1.0.0-SNAPSHOT + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/ConfigAttributeConstants.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/ConfigAttributeConstants.xtend new file mode 100644 index 000000000..434111129 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/ConfigAttributeConstants.xtend @@ -0,0 +1,490 @@ +package org.sa.rainbow.configuration +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import com.google.inject.Inject +import com.google.inject.name.Named +import java.util.Collections +import java.util.HashMap +import java.util.HashSet +import java.util.Map +import java.util.Set +import javax.swing.JPanel +import javax.swing.JTabbedPane +import org.eclipse.emf.ecore.EObject +import org.eclipse.emf.ecore.resource.Resource +import org.eclipse.xtext.EcoreUtil2 +import org.eclipse.xtext.common.types.JvmType +import org.eclipse.xtext.common.types.access.IJvmTypeProvider +import org.eclipse.xtext.common.types.util.RawSuperTypes +import org.sa.rainbow.configuration.rcl.Array +import org.sa.rainbow.configuration.rcl.Assignment +import org.sa.rainbow.configuration.rcl.BooleanLiteral +import org.sa.rainbow.configuration.rcl.Component +import org.sa.rainbow.configuration.rcl.ComponentType +import org.sa.rainbow.configuration.rcl.DeclaredProperty +import org.sa.rainbow.configuration.rcl.DoubleLiteral +import org.sa.rainbow.configuration.rcl.Factory +import org.sa.rainbow.configuration.rcl.GaugeType +import org.sa.rainbow.configuration.rcl.IPLiteral +import org.sa.rainbow.configuration.rcl.IntegerLiteral +import org.sa.rainbow.configuration.rcl.Probe +import org.sa.rainbow.configuration.rcl.PropertyReference +import org.sa.rainbow.configuration.rcl.Reference +import org.sa.rainbow.configuration.rcl.RichString +import org.sa.rainbow.configuration.rcl.StringLiteral +import org.sa.rainbow.configuration.rcl.Value +import org.sa.rainbow.core.adaptation.IAdaptationExecutor +import org.sa.rainbow.core.adaptation.IAdaptationManager +import org.sa.rainbow.core.analysis.IRainbowAnalysis +import org.sa.rainbow.core.gauges.AbstractGauge +import org.sa.rainbow.core.models.commands.ModelCommandFactory +import org.sa.rainbow.gui.IRainbowGUI +import org.sa.rainbow.translator.effectors.EffectorManager +import org.sa.rainbow.translator.probes.AbstractProbe +import org.sa.rainbow.configuration.validation.RclValidator +import org.sa.rainbow.core.ports.IRainbowConnectionPortFactory + +class ConfigAttributeConstants { + public static val ALL_OFREQUIRED_PROBE_FIELDS = #{"alias", "location"}; + public static val ONE_OFREQUIRED_PROBE_FIELDS = #{"script", "java"} + public static val ALL_OFREQUIRED_PROBE_SUBFIELDS = #{"script" -> #{"path"}, "java" -> #{"class"}} + public static val OPTIONAL_PROBE_SUBFIELDS = #{"script" -> #{"mode", "argument"}, "java" -> #{"args", "period"}} + + public static val ALL_OFREQUIRED_GAUGE_FIELDS = new HashSet() + public static val ALL_OFREQUIRED_GAUGE_SUBFILEDS = #{'setup' -> #{"targetIP", "beaconPeriod"}, + 'config' -> #{"targetProbe", "samplingFrequency"}} + public static val ONE_OFREQUIRED_GAUGE_SUBFILEDS = #{'setup' -> #{"javaClass", "generatedClass"}} + public static val Set OPTIONAL_GUAGE_FIELDS = #{} + + public static val OPTIONAL_GAUGE_SUBFIELDS = Collections.>emptyMap + + public static val ALL_OFREQUIRED_EFFECTOR_FIELDS = #{'location'} + public static val ONE_OFREQUIRED_EFFECTOR_FIELDS = #{'script', 'java'} + public static val ALL_OFREQUIRED_EFFECTOR_SUBFIELDS = #{'script' -> #{'path'}, 'java' -> #{'class'}} + public static val OPTIONAL_EFFECTOR_SUBFIELDS = #{'script' -> #{'argument'}} + + public static val ALL_OFREQUIRED_MODEL_FIELDS = #{'factory'} + public static val OPTIONAL_MODEL_FIELDS = #{'name', 'path', 'saveOnClose', 'saveLocation'} + + public static val ALL_OFREQUIRED_MANANGER_FIELDS = #{'model', 'class'} + public static val ALL_OFREQUIRED_EXECUTOR_FIELDS = #{'model', 'class'} + public static val ALL_OFREQUIRED_ANALYSIS_FIELDS = #{'class'} + public static val ALL_OFREQUIRED_EFFECTOR_MANAGER_FIELDS = #{'class'} + + public static val MODEL_KEYWORDS = { + val set = new HashSet(); + set.addAll(ALL_OFREQUIRED_MODEL_FIELDS) + set.addAll(OPTIONAL_MODEL_FIELDS) + set + } + + public static val MANAGER_KEYWORDS = ALL_OFREQUIRED_MANANGER_FIELDS + public static val EXECUTOR_KEYWORDS = ALL_OFREQUIRED_EXECUTOR_FIELDS + public static val ANALYSIS_KEYWORDS = ALL_OFREQUIRED_ANALYSIS_FIELDS + public static val EFFECTOR_MANAGER_KEYWORDS = ALL_OFREQUIRED_EFFECTOR_MANAGER_FIELDS + + public static val GAUGE_KEYWORDS = { + val set = new HashSet(); + set.addAll(ALL_OFREQUIRED_GAUGE_FIELDS); + set.addAll(ALL_OFREQUIRED_GAUGE_SUBFILEDS.keySet) + for (e : ALL_OFREQUIRED_GAUGE_SUBFILEDS.values) { + set.addAll(e); + } + for (e : ONE_OFREQUIRED_GAUGE_SUBFILEDS.values) { + set.addAll(e) + } + set + } + public static val PROBE_KEYWORDS = { + val set = new HashSet(); + set.addAll(ALL_OFREQUIRED_PROBE_FIELDS); + set.addAll(ONE_OFREQUIRED_PROBE_FIELDS); + for (e : ALL_OFREQUIRED_PROBE_SUBFIELDS.values) { + set.addAll(e); + } + for (e : OPTIONAL_PROBE_SUBFIELDS.values) { + set.addAll(e); + } + set + } + + public static val EFFECTOR_KEYOWRDS = { + val set = new HashSet() + set.addAll(ALL_OFREQUIRED_EFFECTOR_FIELDS) + set.addAll(ONE_OFREQUIRED_EFFECTOR_FIELDS) + for (e : ALL_OFREQUIRED_EFFECTOR_SUBFIELDS.values) { + set.addAll(e) + } + for (e : OPTIONAL_EFFECTOR_SUBFIELDS.values) { + set.addAll(e) + } + set + } + + static val IS_STRING = #{'extends' -> #[StringLiteral], 'msg' -> 'must be a string'} + static val IS_NUMBER = #{'extends' -> #[IntegerLiteral], 'msg' -> 'must be a number'} + static val IS_COMPONENT = #{'extends' -> #[Component], 'msg' -> 'must be a composite'} + + public static val PROPERTY_VALUE_CLASSES = #{ + + "rainbow.model.load.class*" -> "org.sa.rainbow.core.models.commands.ModelCommandFactory", + "rainbow.analyses*" -> "org.sa.rainbow.core.analysis.IRainbowAnalysis", + "rainbow.adaptation.manager.class*" -> "org.sa.rainbow.core.adaptation.IAdaptationManager", + "rainbow.adaptation.executor.class*" -> "org.sa.rainbow.core.adaptation.IAdaptationExecutor", + "rainbow.effector.manager.class*" -> "org.sa.rainbow.translator.effectors.EffectorManager", + "rainbow.gui" -> "org.sa.rainbow.gui.IRainbowGUI" + } + + public static val PROPERTY_VALUE_TYPES = #{ + "rainbow.deployment.factory.class" -> #{ + 'func' -> [Value v | v?.value instanceof Reference && subclasses(v,IRainbowConnectionPortFactory.name)], + 'extends' -> #[IRainbowConnectionPortFactory], + 'msg' -> 'must implement ' + IRainbowConnectionPortFactory.name + }, + "rainbow.master.location.host" -> #{ + 'extends' -> #[StringLiteral,IPLiteral], + 'msg' -> 'Must be a hostname string or IP' + }, + "rainbow.deployment.location" -> #{ + 'extends' -> #[StringLiteral,IPLiteral], + 'msg' -> 'Must be a hostname string or IP' + }, + "rainbow.master.location.port" -> IS_NUMBER, + "rainbow.deployment.environment" -> #{ + 'func' -> [Value v | v?.value instanceof StringLiteral && #{'linux', 'cygwin'}.contains(XtendUtils.unpackString(v.value as StringLiteral, true, true))], + 'msg' -> 'Must be "linux" or "cygwin"' + }, + 'rainbow.delegate.beaconperiod' -> IS_NUMBER + } + + static val MODEL_TYPES = #{ + 'name' -> + #{'func' -> [Value v|v.value instanceof StringLiteral], 'msg' -> 'must be a String', + 'extends' -> #[StringLiteral]}, + 'path' -> + #{'func' -> [Value v|v.value instanceof StringLiteral], 'msg' -> 'must be a String', + 'extends' -> #[StringLiteral]}, + 'saveOnClose' -> + #{'func' -> [Value v|v?.value instanceof BooleanLiteral], 'msg' -> 'must be true or false', + 'extends' -> #[BooleanLiteral]}, + 'saveLocation' -> + #{'func' -> [Value v|v?.value instanceof StringLiteral], 'msg' -> 'must be a String', + 'extends' -> #[StringLiteral]}, + 'factory' -> #{'func' -> [ Value v | + (v?.value instanceof PropertyReference && (v.value as PropertyReference).referable instanceof Factory) || + (v?.value instanceof Reference && subclasses(v, ModelCommandFactory.name)) + ], 'extends' -> #[Factory, ModelCommandFactory], + 'msg' -> 'must be a model factory or subclass org.sa.rainbow.core.models.commands.ModelCommandFactory'} + } + static val MANAGER_TYPES = #{ + 'model' -> #{'func' -> [ Value v | + v.value instanceof StringLiteral || + (v.value instanceof PropertyReference && + (v.value as PropertyReference).referable instanceof DeclaredProperty && + ((v.value as PropertyReference).referable as DeclaredProperty).component == ComponentType.MODEL) + ], 'msg' -> 'must be a string or refer to a valid "def model" property', + 'extends' -> #[StringLiteral, PropertyReference]}, + 'class' -> + #{'extends' -> #[IAdaptationManager], + 'msg' -> 'must subclass org.sa.rainbow.core.adaptation.IAdaptationManager'} + } + static val EXECUTOR_TYPES = #{ + 'model' -> #{'func' -> [ Value v | + v.value instanceof StringLiteral || + (v.value instanceof PropertyReference && + (v.value as PropertyReference).referable instanceof DeclaredProperty && + ((v.value as PropertyReference).referable as DeclaredProperty).component == ComponentType.MODEL) + ], 'msg' -> 'must be a string or refer to a valid "def model" property'}, + 'class' -> + #{'extends' -> #[IAdaptationExecutor], + 'msg' -> 'must subclass org.sa.rainbow.core.adaptation.IAdaptationExecutor'} + } + public static val COMPONENT_PROPERTY_TYPES = #{ + ComponentType.MODEL -> MODEL_TYPES, + ComponentType.MANAGER -> MANAGER_TYPES, + ComponentType.EXECUTOR -> EXECUTOR_TYPES, + ComponentType.GUI -> new HashMap>(), + ComponentType.ANALYSIS -> #{ + 'class' -> + #{'extends' -> #[IRainbowAnalysis], + 'msg' -> 'must subclass org.sa.rainbow.core.analysis.IRainbowAnalysis'} + }, + ComponentType.EFFECTORMANAGER -> #{ + 'class' -> + #{'extends' -> #[EffectorManager], + 'msg' -> 'must subclass org.sa.rainbow.translator.effectors.EffectorManager'} + } + } + + + + public static val PROBE_PROPERTY_TYPES = #{ + 'location' -> + #{'extends' -> #[StringLiteral, PropertyReference, IPLiteral], + 'msg' -> 'must be a string, property reference, or IP'}, + 'alias' -> IS_STRING, + 'script' -> IS_COMPONENT, + 'java' -> IS_COMPONENT, + 'script:mode' -> IS_STRING, + 'script:path' -> IS_STRING, + 'script:argument' -> IS_STRING, + 'java:args' -> IS_STRING, + 'java:period' -> IS_NUMBER, + 'java:class' -> #{'extends' -> #[AbstractProbe], 'msg' -> 'must extend AbstractProbe'} + } + + public static val GAUGE_PROPERTY_TYPES = #{ + 'setup' -> IS_COMPONENT, + 'config' -> IS_COMPONENT, + 'setup:targetIP' -> + #{'extends' -> #[StringLiteral, PropertyReference, IPLiteral], + 'msg' -> 'must be a string, property reference, or IP'}, + 'setup:beaconPeriod' -> IS_NUMBER, + 'setup:javaClass' -> #{'extends' -> #[AbstractGauge], 'msg' -> 'must extend AbstractGauge'}, + 'setup:generatedClass' -> IS_STRING, + 'config:samplingFrequency' -> IS_NUMBER, + 'config:targetProbe' -> #{'func' -> [ Value v | + (v.value instanceof PropertyReference && (v.value as PropertyReference).referable instanceof Probe) + ], 'extends' -> #[Probe], 'msg' -> 'must refer to a probe'}, + 'generateClass' -> #{'extends' -> #[BooleanLiteral], 'msg' -> 'must be true or false'} + } + + public static val EFFECTOR_PROPERTY_TYPES = #{ + 'location' -> + #{'extends' -> #[StringLiteral, PropertyReference, IPLiteral], + 'msg' -> 'must be a string, property reference, or IP'}, + 'script' -> IS_COMPONENT, + 'script:path' -> IS_STRING, + 'script:argument' -> IS_STRING + } + + static val isValidCommand = [ Value v | + var ass = EcoreUtil2.getContainerOfType(EcoreUtil2.getContainerOfType(v, Assignment).eContainer, Component) + if (ass !== null) { + val type = ass.assignment.findFirst[it.name == 'type'] + var String s = null + if (v.value instanceof StringLiteral) + s = XtendUtils.unpackString(v.value as StringLiteral, true) + val ts = s + if (type != null && type.value.value instanceof PropertyReference && + (type.value.value as PropertyReference).referable instanceof GaugeType) { + return ((type.value.value as PropertyReference).referable as GaugeType).body.commands.exists [ + it.name == ts + ] + } + } + false + ] + + static val validCommands = [ Assignment v | + var ass = EcoreUtil2.getContainerOfType(EcoreUtil2.getContainerOfType(v, Assignment).eContainer, Component) + val Set commands = newHashSet + if (ass !== null) { + val type = ass.assignment.findFirst[it.name == 'type'].value + if (type != null && type.value instanceof PropertyReference && + (type.value as PropertyReference).referable instanceof GaugeType) { + return ((type.value as PropertyReference).referable as GaugeType).body.commands.map [ + "\"" + it.name + "\"" + ] + } + } + return commands + ] + + enum GUICategory { + meter, + timeseries, + onoff + } + + static val validCategories = [ Assignment v | + newArrayList(GUICategory.values).map['''"«it.name»"'''] + ] + + public static val GUI_PROPERTY_TUPES = #{ + 'class' -> #{'extends' -> #[IRainbowGUI], 'msg' -> 'must implement IRainbowGUI'}, + 'specs:gauges:gauge:type' -> #{'extends' -> #[GaugeType], 'func' -> [ Value v | + (v.value instanceof PropertyReference && (v.value as PropertyReference).referable instanceof GaugeType) + ], 'msg' -> 'must refer to a GaugeType'}, + 'specs:gauges:gauge:command' -> #{ + 'func' -> isValidCommand, + 'values' -> validCommands, + 'extends' -> #[StringLiteral], + 'msg' -> 'must be a string containing a command name' + }, + 'specs:gauges:gauge:value.parameter' -> #{ + 'extends' -> #[IntegerLiteral], + 'msg' -> 'must be an integer' + }, + 'specs:gauges:gauge:upper' -> #{ + 'extends' -> #[IntegerLiteral, DoubleLiteral], + 'msg' -> 'must be a number' + }, + 'specs:gauges:gauge:lower' -> #{ + 'extends' -> #[IntegerLiteral, DoubleLiteral], + 'msg' -> 'must be a number' + }, + 'specs:gauges:gauge:category' -> #{ + 'extends' -> #[StringLiteral], + 'msg' -> '''must be one of «validCategories.apply(null).map['''"«it»"'''].join(', ')»''', + 'values' -> validCategories, + 'func' -> [ Value v | + v.value instanceof RichString && + validCategories.apply(null).contains( + "\"" + XtendUtils.unpackString(v.value as RichString, true) + "\"") + ] + }, + 'specs:analyzers:analyzer:for' -> #{ + 'extends' -> #[DeclaredProperty], + 'msg' -> 'must refer to an analysis', + 'func' -> [ Value v | + v.value instanceof PropertyReference && + (v.value as PropertyReference).referable instanceof DeclaredProperty && + ((v.value as PropertyReference).referable as DeclaredProperty).component == ComponentType.ANALYSIS + ], + 'values' -> [ Assignment a | + getAllNamesFor(a, [ EObject o | + o instanceof DeclaredProperty && (o as DeclaredProperty).component == ComponentType.ANALYSIS + ], [EObject o|('««' + (o as DeclaredProperty).name + '»»')]) + ] + }, + 'specs:analyzers:analyzer:class' -> #{ + 'extends' -> #[JPanel], + 'msg' -> 'must subclass JPanel' + }, + 'specs:managers:manager:for' -> #{ + 'extends' -> #[DeclaredProperty], + 'msg' -> 'must refer to an analysis', + 'func' -> [ Value v | + v.value instanceof PropertyReference && + (v.value as PropertyReference).referable instanceof DeclaredProperty && + ((v.value as PropertyReference).referable as DeclaredProperty).component == ComponentType.MANAGER + ], + 'values' -> [ Assignment a | + getAllNamesFor(a, [ EObject o | + o instanceof DeclaredProperty && (o as DeclaredProperty).component == ComponentType.MANAGER + ], [EObject o|('««' + (o as DeclaredProperty).name + '»»')]) + ] + }, + 'specs:managers:manager:class' -> #{ + 'extends' -> #[JPanel], + 'msg' -> 'must subclass JPanel' + }, + 'specs:executors:executor:for' -> #{ + 'extends' -> #[DeclaredProperty], + 'msg' -> 'must refer to an analysis', + 'func' -> [ Value v | + v.value instanceof PropertyReference && + (v.value as PropertyReference).referable instanceof DeclaredProperty && + ((v.value as PropertyReference).referable as DeclaredProperty).component == ComponentType.EXECUTOR + ], + 'values' -> [ Assignment a | + getAllNamesFor(a, [ EObject o | + o instanceof DeclaredProperty && (o as DeclaredProperty).component == ComponentType.EXECUTOR + ], [EObject o|('««' + (o as DeclaredProperty).name + '»»')]) + ] + }, + 'specs:executors:executor:class' -> #{ + 'extends' -> #[JPanel], + 'msg' -> 'must subclass JPanel' + }, + 'specs:details:managers' -> #{ + 'extends' -> #[JTabbedPane], + 'msg' -> 'must extend JTabbedPane' + }, + 'specs:details:executors' -> #{ + 'extends' -> #[JTabbedPane], + 'msg' -> 'must extend JTabbedPane' + } + } + + def static getAllNamesFor(Assignment assignment, (EObject)=>boolean discriminator, (EObject)=>String name) { + val names = newHashSet + val v = assignment.eResource.resourceSet.resources + for (r : v) { + val res = r.allContents + res.forEach [ + if (discriminator.apply(it)) { + names.add(name.apply(it)) + } + ] + } + names + } + + public static val Map> UTILITY_PROPERTY_TYPES = #{ + 'model' -> #{'func' -> [ Value v | + (v.value instanceof PropertyReference && + (v.value as PropertyReference).referable instanceof DeclaredProperty && + ((v.value as PropertyReference).referable as DeclaredProperty).component == ComponentType.MODEL) + ], 'extends' -> #[PropertyReference], 'msg' -> 'must refer to a model property'}, + 'utilities' -> IS_COMPONENT, + 'scenarios' -> + #{'extends' -> #[Array], 'msg' -> 'must be an array', + 'checkEach' -> RclValidator.CHECK_EACH_SCENARIO}, + 'utilities::label' -> IS_STRING, + 'utilities::mapping' -> IS_STRING, + 'utilities::description' -> IS_STRING, + 'utilities::utility' -> + #{'extends' -> #[Array], 'msg' -> 'must be a two dimensionsal array', + 'checkEach' -> RclValidator.CHECK_UTILITY_MONOTONIC} + } + + public static val ALL_OFREQUIRED_UTILITY_FIELDS = #{'model', 'utilities', 'scenarios'} + public static val REQUIRED_UTILITY_SUBFILEDS = #{'utilities:' -> #{'label', 'mapping', 'utility'}} + public static val OPTIONAL_UTILITY_SUBFIELDS = #{'utilities:' -> #{'description'}} + + public static val UTILITY_KEYWORDS = { + val set = new HashSet() + for (key : UTILITY_PROPERTY_TYPES.keySet) { + val kw = key.split(':') + set.add(kw.get(kw.length - 1)) + } + set + } + + @Inject + @Named("jvmtypes") static private IJvmTypeProvider.Factory jvmTypeProviderFactory; + + @Inject + static private RawSuperTypes superTypeCollector; + + public static def subclasses(Value v, String superclass) { + if (v?.value instanceof Reference) { + val ref = v.value as Reference + return subclasses(ref, superclass) + } + return false + } + + public static def subclasses(Reference ref, String superclass) { + val referable = ref.referable + val eResource = ref.eResource + subclasses(referable, superclass, eResource) + } + + public static def subclasses(JvmType referable, String superclass, Resource eResource) { + val jtp = jvmTypeProviderFactory.createTypeProvider(eResource.resourceSet) + val sc = jtp.findTypeByName(superclass) + val sts = superTypeCollector.collect(referable) + return sts.contains(sc) + } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/GenerateRCL.mwe2 b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/GenerateRCL.mwe2 new file mode 100644 index 000000000..13286dad1 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/GenerateRCL.mwe2 @@ -0,0 +1,80 @@ +module org.sa.rainbow.configuration.GenerateConfigModel + +import org.eclipse.xtext.xtext.generator.* +import org.eclipse.xtext.xtext.generator.model.project.* + +var rootPath = ".." + +Workflow { +// bean = StandaloneSetup { +// scanClassPath = true +// platformUri= "${runtimeProject}/.." +// registerGenModelFile = "platform:/resource/org.sa.rainbow.configuration/model/RCL.ecore" +// } + + + component = XtextGenerator { + configuration = { + project = StandardProjectConfig { + baseName = "org.sa.rainbow.configuration" + rootPath = rootPath + runtimeTest = { + enabled = true + } + eclipsePlugin = { + enabled = true + } + eclipsePluginTest = { + enabled = true + } + createEclipseMetaData = true + } + code = { + encoding = "UTF-8" + lineDelimiter = "\n" + fileHeader = "/*\n * generated by Xtext \${version}\n */" + } + + } + language = StandardLanguage { + name = "org.sa.rainbow.configuration.rcl" + fileExtensions = "rbw" + + referencedResource="platform:/resource/org.sa.rainbow.stitch/model/generated/Stitch.genmodel" + referencedResource="platform:/resource/org.acme.xtext/model/generated/Acme.genmodel" + serializer = { + generateStub = false + } + validator = { + // composedCheck = "org.eclipse.xtext.validation.NamesAreUniqueValidator" + // Generates checks for @Deprecated grammar annotations, an IssueProvider and a corresponding PropertyPage + generateDeprecationValidation = true + } + junitSupport = { + junitVersion = "5" + } + parserGenerator = { + options = { + backtrackLexer = false + } + + } + projectWizard = { + generate = true + pluginProject = false + + } + + fileWizard = { + generate = true + } + + fragment = ui.codemining.CodeMiningFragment { + generateStub = true + generateXtendStub = false + } + + + } + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/ModelUtil.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/ModelUtil.xtend new file mode 100644 index 000000000..ac1aab086 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/ModelUtil.xtend @@ -0,0 +1,78 @@ +package org.sa.rainbow.configuration + +import java.util.Collection +import java.util.List +import org.eclipse.xtext.common.types.JvmType +import org.sa.rainbow.configuration.rcl.Component +import org.sa.rainbow.configuration.rcl.ComponentType +import org.sa.rainbow.configuration.rcl.DeclaredProperty +import org.sa.rainbow.configuration.rcl.Factory +import org.sa.rainbow.configuration.rcl.FormalParam +import org.sa.rainbow.configuration.rcl.PropertyReference +import org.sa.rainbow.configuration.rcl.Reference +import org.acme.acme.AnyTypeRef + +class ModelUtil { + + static class CommandRep { + public var String hasTarget = null; + public var List formalNames = newLinkedList() + public var name = "" + + + } + + def static List getCommandsFromReference(PropertyReference reference, Collection include, Collection filterOut, boolean type) { + val referable = reference.referable + val List cmds = newLinkedList() + switch referable { + Factory: { + val mf = referable.defn + val methods = mf.commands.filter[include === null || include.empty?true:include.contains(it.name)].filter[!filterOut?.contains(it.name)] + methods.forEach[ + val rep = new CommandRep() + val tParam = it.formal.findFirst[it.name=='target'] + rep.name = it.name + rep.hasTarget = tParam !== null?(type?getTypeName(tParam):"^target"):null + rep.formalNames = it.formal.filter[it.name != 'target'].map[type?getTypeName(it):it.name].toList + cmds.add(rep) + ] + } + DeclaredProperty : { + if (ComponentType.MODEL == referable.component) { + if (referable?.value?.value instanceof Component) { + val factoryProp = (referable?.value?.value as Component).assignment.findFirst[it.name=='factory'].value.value + if (factoryProp instanceof PropertyReference) { + cmds.addAll(getCommandsFromReference(factoryProp as PropertyReference, include, filterOut, type)) + } + else if (factoryProp instanceof Reference) { + + } + } + } + } + } + cmds + } + + static def getTypeName(FormalParam param) { + if (param.type.ref instanceof JvmType) { + return (param.type.ref as JvmType).simpleName + } + if (param.type.ref instanceof AnyTypeRef) { + return XtendUtils.getAcmeTypeName((param.type.ref as AnyTypeRef)) + } +// if (param.type.acme !== null) { +// val ar = param.type.acme.referable +// return XtendUtils.getAcmeTypeName(ar) +// } +// if (param.type.java != null) { +// return param.type.java.referable.simpleName +// } + if (param.type.base !== null) { + return param.type.base.getName() + } + + } + +} \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RainbowOutputConfigurationProvider.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RainbowOutputConfigurationProvider.java new file mode 100644 index 000000000..44309e0f6 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RainbowOutputConfigurationProvider.java @@ -0,0 +1,64 @@ +package org.sa.rainbow.configuration; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.xtext.generator.IFileSystemAccess; +import org.eclipse.xtext.generator.IOutputConfigurationProvider; +import org.eclipse.xtext.generator.OutputConfiguration; + +public class RainbowOutputConfigurationProvider implements IOutputConfigurationProvider { + + public static final String RAINBOW_TARGET_PROPERTIES_OUTPUT="rainbow-target-properties"; + public static final String RAINBOW_GENERRATED_SOURCE_OUTPUT="rainbow-generated-source"; + + @Override + public Set getOutputConfigurations() { + OutputConfiguration defaultOutput = new OutputConfiguration(RAINBOW_GENERRATED_SOURCE_OUTPUT); + defaultOutput.setDescription("Output Folder"); + defaultOutput.setOutputDirectory("./src/main/java-gen"); + defaultOutput.setOverrideExistingResources(true); + defaultOutput.setCreateOutputDirectory(true); + defaultOutput.setCleanUpDerivedResources(true); + defaultOutput.setSetDerivedProperty(true); + + OutputConfiguration doc = new OutputConfiguration(IFileSystemAccess.DEFAULT_OUTPUT); + doc.setDescription("Output Folder"); + doc.setOutputDirectory("./src/main/java-gen"); + doc.setOverrideExistingResources(true); + doc.setCreateOutputDirectory(true); + doc.setCleanUpDerivedResources(true); + doc.setSetDerivedProperty(true); + + OutputConfiguration propertyOutput = new OutputConfiguration(RAINBOW_TARGET_PROPERTIES_OUTPUT); + propertyOutput.setDescription("Rainbow target property output folder"); + propertyOutput.setOutputDirectory("./src/main/resources/generated"); + propertyOutput.setOverrideExistingResources(true); + propertyOutput.setCreateOutputDirectory(true); + propertyOutput.setCleanUpDerivedResources(true); + propertyOutput.setSetDerivedProperty(true); + + return new HashSet<>(Arrays.asList(new OutputConfiguration []{defaultOutput, propertyOutput})); + + } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclRuntimeModule.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclRuntimeModule.xtend new file mode 100644 index 000000000..c4a75b9fb --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclRuntimeModule.xtend @@ -0,0 +1,66 @@ +/* + * generated by Xtext 2.20.0 + */ +package org.sa.rainbow.configuration +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import com.google.inject.Binder +import com.google.inject.Singleton +import org.eclipse.xtext.generator.IOutputConfigurationProvider +import org.sa.rainbow.configuration.scoping.QualifiedNameProvider +import org.sa.rainbow.configuration.scoping.RclGlobalScopeProvider + +/** + * Use this class to register components to be used at runtime / without the Equinox extension registry. + */ +class RclRuntimeModule extends AbstractRclRuntimeModule { + override configure(Binder binder) { + super.configure(binder) + binder.bind(IOutputConfigurationProvider).to(RainbowOutputConfigurationProvider).in(Singleton) + } + + override bindIValueConverterService() { + return RclValueConverter; + } + + override bindIGlobalScopeProvider() { + return RclGlobalScopeProvider + } + +// override bindLexer() { +// return InternalConfigModelCustomLexer +// } +// +// override configureRuntimeLexer(Binder binder) { +// binder.bind(Lexer).annotatedWith(Names.named(LexerBindings.RUNTIME)).to(InternalConfigModelCustomLexer); +// } +// +// override bindIAntlrTokenFileProvider() { +// return ConfigModelCustomAntlrTokenFileProvider +// } + +// override configureHighlightingLexer(Binder binder) { +// +// } + + override bindIQualifiedNameProvider() { + return QualifiedNameProvider; + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclRuntimeStandaloneModule.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclRuntimeStandaloneModule.xtend new file mode 100644 index 000000000..1c8c1a5a3 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclRuntimeStandaloneModule.xtend @@ -0,0 +1,47 @@ +package org.sa.rainbow.configuration +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import com.google.inject.Binder +import com.google.inject.name.Names +import org.eclipse.emf.ecore.EPackage +import org.eclipse.xtext.common.types.access.CachingClasspathTypeProviderFactory +import org.eclipse.xtext.common.types.access.IJvmTypeProvider +import org.eclipse.xtext.common.types.xtext.AbstractTypeScopeProvider +import org.eclipse.xtext.common.types.xtext.ClasspathBasedTypeScopeProvider +import org.sa.rainbow.stitch.stitch.StitchPackage + +class RclRuntimeStandaloneModule extends RclRuntimeModule { + override configure(Binder binder) { + super.configure(binder) + configureJvmTypeProvider(binder) + if (!EPackage.Registry.INSTANCE.containsKey("http://www.sa.org/rainbow/stitch/Stitch")) { + EPackage.Registry.INSTANCE.put("http://www.sa.org/rainbow/stitch/Stitch", StitchPackage.eINSTANCE) + } + + } + + + def configureJvmTypeProvider(Binder binder) { + binder.requestStaticInjection(ConfigAttributeConstants) + + binder.bind(AbstractTypeScopeProvider).annotatedWith(Names.named("jvmtypes")).to(ClasspathBasedTypeScopeProvider) + binder.bind(IJvmTypeProvider.Factory).annotatedWith(Names.named("jvmtypes")).to(CachingClasspathTypeProviderFactory) + } +} \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclStandaloneSetup.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclStandaloneSetup.xtend new file mode 100644 index 000000000..4986266ce --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclStandaloneSetup.xtend @@ -0,0 +1,55 @@ +/* + * generated by Xtext 2.20.0 + */ +package org.sa.rainbow.configuration +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import com.google.inject.Guice +import com.google.inject.Injector +import org.eclipse.emf.ecore.EPackage +import org.eclipse.emf.ecore.resource.Resource +import org.eclipse.xtext.resource.IResourceFactory +import org.eclipse.xtext.resource.IResourceServiceProvider +import org.sa.rainbow.stitch.stitch.StitchPackage + +/** + * Initialization support for running Xtext languages without Equinox extension registry. + */ +class RclStandaloneSetup extends RclStandaloneSetupGenerated { + + def static void doSetup() { + new RclStandaloneSetup().createInjectorAndDoEMFRegistration() + } + + override createInjector() { + return Guice.createInjector(new RclRuntimeStandaloneModule) + } + + override register(Injector injector) { + super.register(injector) + if (!EPackage.Registry.INSTANCE.containsKey("http://www.sa.org/rainbow/stitch/Stitch")) { + EPackage.Registry.INSTANCE.put("http://www.sa.org/rainbow/stitch/Stitch", StitchPackage.eINSTANCE) + } + val resourceFactory = injector.getInstance(IResourceFactory) + val serviceProvider = injector.getInstance(IResourceServiceProvider) + Resource.Factory.Registry.INSTANCE.extensionToFactoryMap.put("s", resourceFactory) + IResourceServiceProvider.Registry.INSTANCE.extensionToFactoryMap.put("s", serviceProvider) + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclValueConverter.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclValueConverter.java new file mode 100644 index 000000000..70a15a1bb --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/RclValueConverter.java @@ -0,0 +1,129 @@ +package org.sa.rainbow.configuration; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import java.math.BigDecimal; +import java.util.Set; + +import org.eclipse.xtext.GrammarUtil; +import org.eclipse.xtext.common.services.DefaultTerminalConverters; +import org.eclipse.xtext.conversion.IValueConverter; +import org.eclipse.xtext.conversion.ValueConverter; +import org.eclipse.xtext.conversion.ValueConverterException; +import org.eclipse.xtext.conversion.impl.AbstractNullSafeConverter; +import org.eclipse.xtext.conversion.impl.STRINGValueConverter; +import org.eclipse.xtext.nodemodel.INode; +import org.eclipse.xtext.util.Strings; + +import com.google.common.collect.ImmutableSet; +import com.google.inject.Inject; + +public class RclValueConverter extends DefaultTerminalConverters { + + public class FQNConverter extends AbstractNullSafeConverter { + private Set allKeywords = ImmutableSet.copyOf(GrammarUtil.getAllKeywords(getGrammar())); + + @Override + protected String internalToValue(String string, INode node) throws ValueConverterException { + return string.replaceAll("[\\^\\s]", ""); + } + + @Override + protected String internalToString(String value) { + String[] segments = value.split("\\."); + StringBuilder builder = new StringBuilder(value.length()); + boolean first = true; + for (String segment: segments) { + if (!first) + builder.append('.'); + if (allKeywords.contains(segment)) + builder.append("^"); + builder.append(segment); + first = false; + } + return builder.toString(); + } + } + + @ValueConverter(rule="ImportedFQN") + public IValueConverter ImportedFQN() { + return new FQNConverter(); + } + + @ValueConverter(rule="FQN") + public IValueConverter FQN() { + return new FQNConverter(); + } + + @ValueConverter(rule="DoubleValue") + public IValueConverter DoubleValue() { + return new AbstractNullSafeConverter() { + @Override + protected Double internalToValue(String string, INode node) throws ValueConverterException { + try { + return Double.parseDouble(string); + } + catch (NumberFormatException e) { + throw new ValueConverterException(e.getMessage(), node, e); + } + } + + @Override + protected String internalToString(Double value) { + return BigDecimal.valueOf(value).toPlainString(); + } + }; + } + + @ValueConverter(rule="ConstantValue") + public IValueConverter ConstantValue() { + return new AbstractNullSafeConverter() { + + @Override + protected String internalToValue(String string, INode node) { + try { + string = string.replace("\\${", "${"); + return Strings.convertFromJavaString(string, false); + } catch(IllegalArgumentException e) { + throw new ValueConverterException(e.getMessage(), node, e); + } + } + + @Override + protected String internalToString(String value) { + String result = Strings.convertToJavaString(value, false); + result = result.replace("${", "\\${"); + return result; + } + }; + } + + @Inject + STRINGValueConverter stringValueConverter; + + @ValueConverter(rule="RICH_TEXT_DQ") + public IValueConverter RICH_TEXT_DQ() { + return stringValueConverter; + } + + @ValueConverter(rule="RICH_TEXT_SQ") + public IValueConverter RICH_TEXT_SQ() { + return stringValueConverter; + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/Utils.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/Utils.java new file mode 100644 index 000000000..943d6dd78 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/Utils.java @@ -0,0 +1,45 @@ +package org.sa.rainbow.configuration; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import org.eclipse.emf.ecore.EObject; +import org.eclipse.xtext.xbase.lib.Functions.Function1; + +public class Utils { + + public static T getContainerOfType(EObject ele, Class type, Function1 func) { + for (EObject e = ele; e != null; e = e.eContainer()) { + if (type.isInstance(e) && func.apply(type.cast(e))) { + return type.cast(e); + } + } + return null; + } + + public static String removeQuotes(CharSequence cs) { + if (cs == null) return null; + String s = cs.toString(); + s = s.trim(); + if (s.startsWith("\"") && s.endsWith("\"")) { + return s.replaceAll("\"", ""); + } + return s; + } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/XtendUtils.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/XtendUtils.xtend new file mode 100644 index 000000000..0b507baba --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/XtendUtils.xtend @@ -0,0 +1,288 @@ +package org.sa.rainbow.configuration + +/* + * Copyright 2020 Carnegie Mellon University + + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR + * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE + * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +import java.util.Map +import java.util.Set +import java.util.regex.Pattern +import org.acme.acme.AcmeComponentTypeDeclaration +import org.acme.acme.AcmeConnectorTypeDeclaration +import org.acme.acme.AcmeElementTypeDeclaration +import org.acme.acme.AcmeGroupTypeDeclaration +import org.acme.acme.AcmePortTypeDeclaration +import org.acme.acme.AcmeRoleTypeDeclaration +import org.acme.acme.AnyTypeRef +import org.eclipse.emf.ecore.EObject +import org.eclipse.xtext.EcoreUtil2 +import org.eclipse.xtext.common.types.JvmDeclaredType +import org.eclipse.xtext.common.types.JvmPrimitiveType +import org.eclipse.xtext.common.types.JvmType +import org.sa.rainbow.configuration.rcl.Assignment +import org.sa.rainbow.configuration.rcl.BooleanLiteral +import org.sa.rainbow.configuration.rcl.DeclaredProperty +import org.sa.rainbow.configuration.rcl.DoubleLiteral +import org.sa.rainbow.configuration.rcl.FormalParam +import org.sa.rainbow.configuration.rcl.IPLiteral +import org.sa.rainbow.configuration.rcl.IntegerLiteral +import org.sa.rainbow.configuration.rcl.LogLiteral +import org.sa.rainbow.configuration.rcl.PropertyReference +import org.sa.rainbow.configuration.rcl.Reference +import org.sa.rainbow.configuration.rcl.RichString +import org.sa.rainbow.configuration.rcl.RichStringLiteral +import org.sa.rainbow.configuration.rcl.RichStringPart +import org.sa.rainbow.configuration.rcl.StringLiteral + +class XtendUtils { + static def formalTypeName(FormalParam fp, boolean keepSimple) { + if (fp.type.ref instanceof JvmType) { + keepSimple ? (fp.type.ref as JvmType).simpleName:(fp.type.ref as JvmType).qualifiedName + } + else if (fp.type.ref instanceof AnyTypeRef) { + switch fp.type.ref as AnyTypeRef { + AcmeComponentTypeDeclaration: return keepSimple ? "IAcmeComponent" : "org.acmestudio.acme.element.IAcmeComponent" + AcmeConnectorTypeDeclaration: return keepSimple ? "IAcmeConnector" : "org.acmestudio.acme.element.IAcmeConnector" + AcmePortTypeDeclaration: return keepSimple ? "IAcmePort" : "org.acmestudio.acme.element.IAcmePort" + AcmeRoleTypeDeclaration: return keepSimple ? "IAcmeRole" : "org.acmestudio.acme.element.IAcmeRole" + AcmeElementTypeDeclaration: return keepSimple ? "IAcmeElement" : "org.acmestudio.acme.element.IAcmeElement" + AcmeGroupTypeDeclaration: return keepSimple ? "IAcmeGroup" : "org.acmestudio.acme.element.IAcmeGroup" + default: return keepSimple ? "IAcmeElement" : "org.acmestudio.acme.element.IAcmeElement" + } +// } +// +// +// if (fp.type.java !== null) +// keepSimple ? fp.type.java.referable.simpleName : fp.type.java.referable.qualifiedName +// else if (fp.type.acme !== null) { +// switch fp.type.acme.referable { +// AcmeComponentTypeDeclaration: return keepSimple ? "IAcmeComponent" : "org.acmestudio.acme.element.IAcmeComponent" +// AcmeConnectorTypeDeclaration: return keepSimple ? "IAcmeConnector" : "org.acmestudio.acme.element.IAcmeConnector" +// AcmePortTypeDeclaration: return keepSimple ? "IAcmePort" : "org.acmestudio.acme.element.IAcmePort" +// AcmeRoleTypeDeclaration: return keepSimple ? "IAcmeRole" : "org.acmestudio.acme.element.IAcmeRole" +// AcmeElementTypeDeclaration: return keepSimple ? "IAcmeElement" : "org.acmestudio.acme.element.IAcmeElement" +// AcmeGroupTypeDeclaration: return keepSimple ? "IAcmeGroup" : "org.acmestudio.acme.element.IAcmeGroup" +// default: return keepSimple ? "IAcmeElement" : "org.acmestudio.acme.element.IAcmeElement" +// } + } else if(fp.type.base !== null) fp.type.base.name() + } + + def static getAcmeTypeName(AnyTypeRef ref) { + switch ref { + AcmeElementTypeDeclaration: ref.name + AcmeComponentTypeDeclaration: ref.name + AcmeConnectorTypeDeclaration: ref.name + AcmePortTypeDeclaration: ref.name + AcmeRoleTypeDeclaration: ref.name + AcmeGroupTypeDeclaration: ref.name + } + } + + def static convertToString(FormalParam p) { + + if (p.type.ref instanceof AnyTypeRef) { + '''«p.name».getQualifiedName()''' + } else if (p.type.ref instanceof JvmType) { + val type = (p.type.ref as JvmType) + switch type { + JvmPrimitiveType: + switch type.simpleName { + case "double", + case "Double": '''Double.toString(«p.name»)''' + case "int", + case "Integer": '''Integer.toString(«p.name»)''' + case "String": + p.name + case "boolean", + case "Boolean": '''Boolean.toString(«p.name»)''' + case "char": '''Character.toString(«p.name»)''' + } + JvmDeclaredType: '''«p.name».toString()''' + } + } else { + throw new IllegalArgumentException("Don't know how to convert parameter " + p.name) + } + } + + static def boolean isSimpleDeclaredProperty(DeclaredProperty p) { + val value = p?.value?.value + val simple = switch value { + Reference | StringLiteral | BooleanLiteral | IntegerLiteral | DoubleLiteral | IPLiteral | LogLiteral: true + PropertyReference case value.referable instanceof DeclaredProperty: isSimpleDeclaredProperty( + value.referable as DeclaredProperty) + default: false + } + simple + } + + static def String valueOfSimpleDeclaredProperty(DeclaredProperty p) { + val value = p?.value?.value + val sv = switch value { + StringLiteral: unpackString(value, false, true) + BooleanLiteral: Boolean.toString(value.isTrue) + IntegerLiteral: Integer.toString(value.value) + DoubleLiteral: Double.toString(value.value) + PropertyReference case value.referable instanceof DeclaredProperty: valueOfSimpleDeclaredProperty( + value.referable as DeclaredProperty) + IPLiteral: value.value + LogLiteral: value.value.getName + Reference: value.referable.qualifiedName + default: "" + } + sv + } + + static def String unpackString(StringLiteral literal, boolean strip, boolean completeProperties) { + if (!completeProperties) { + unpackString(literal, strip) + } else { + val rich = literal as RichString + var str = new StringBuilder() + for (expr : rich.expressions) { + if (expr instanceof RichStringLiteral) { + val s = (expr as RichStringLiteral)?.value?.replaceAll("«", "")?.replaceAll("»", "") + + if(s !== null) str.append(s) + } else if (expr instanceof RichStringPart) { + val value = (expr as RichStringPart)?.referable?.value?.value + val sv = switch value { + StringLiteral: unpackString(value, true, true) + BooleanLiteral: Boolean.toString(value.isTrue) + IntegerLiteral: Integer.toString(value.value) + DoubleLiteral: Double.toString(value.value) + IPLiteral: value.value + LogLiteral: value.value.getName + Reference: value.referable.qualifiedName + default: '''${«(expr as RichStringPart).referable.name»}''' + } + str.append(sv) + } + } + if (strip) { + var s = str.toString() + s = s.trim() + if ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'"))) { + s = s.substring(1, s.length - 1) + } + return s + } + return str.toString + } + } + + static def unpackString(StringLiteral literal, boolean strip) { +// if (literal instanceof SimpleStringLiteral) { +// val value=(literal as SimpleStringLiteral).value +// return value +// } +// else { + val rich = literal as RichString + var str = new StringBuilder(); + for (expr : rich.expressions) { + if (expr instanceof RichStringLiteral) { + str.append((expr as RichStringLiteral).value.replaceAll("«", "\\${").replaceAll("»", "}")) + } else if (expr instanceof RichStringPart) { + str.append((expr as RichStringPart).referable.name) + } + } + if (strip) { + var s = str.toString() + s = s.trim() + if ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'"))) { + s = s.substring(1, s.length - 1) + } + return s + } + return str.toString + } + + static def fillNamedGroups(String regexp, Set namedGroups) { + var m = Pattern.compile("\\(\\?<([a-zA-Z][a-zA-Z0-9]*)>").matcher(regexp); + while (m.find()) { + namedGroups.add(m.group(1)) + } + m = Pattern.compile("\\(.*?\\)").matcher(regexp) + var i = 1 + while (m.find()) { + namedGroups.add(Integer.toString(i++)) + } + + } + + static def getComponentName(EObject a) { + val st = new StringBuilder(); + if(a instanceof Assignment) st.append((a as Assignment).name) + var parent = EcoreUtil2.getContainerOfType(a.eContainer, Assignment) + while (parent !== null) { + st.insert(0, ':') + st.insert(0, parent.name); + parent = EcoreUtil2.getContainerOfType(parent.eContainer, Assignment) + } + st.toString() + } + + static var COMPOUND_NAME_STORE = newHashMap + + static def updateStore(Map knownCompoundNames) { + // Form all component names + var compoundNames = COMPOUND_NAME_STORE.get(knownCompoundNames) as Set + if (compoundNames === null) { + compoundNames = newHashSet + for (n : knownCompoundNames.keySet()) { + val split = n.split(":") + var st = new StringBuilder() + for (var i = 0; i < split.length - 1; i++) { + if(i != 0) st.append(":") + st.append(split.get(i)) + compoundNames.add(st.toString) + } + compoundNames.add(n) + } + COMPOUND_NAME_STORE.put(knownCompoundNames, compoundNames) + } + compoundNames + } + + static def isKeyProperty(Map knownCompoundNames, Assignment a) { + val compoundNames = updateStore(knownCompoundNames) + // Check if name is there + val cn = getComponentName(a) + return compoundNames.contains(cn) + } + + static def getPropertySuggestions(Map knownCompoundNames, EObject a) { + val compoundNames = updateStore(knownCompoundNames) + val names = newHashSet + val cn = getComponentName(a) + compoundNames.forEach [ + if (it.startsWith(cn)) { + val split2 = it.split(":") + if (it.endsWith(":")) { + names.add((split2).get(split2.length - 2)) + + } else { + names.add((split2).get(split2.length - 1)) + } + + } + ] + names + } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/generator/RclGenerator.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/generator/RclGenerator.xtend new file mode 100644 index 000000000..2aa42f129 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/generator/RclGenerator.xtend @@ -0,0 +1,927 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.generator +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ + +import java.util.HashMap +import org.acme.acme.AnyTypeRef +import org.eclipse.emf.common.util.EList +import org.eclipse.emf.common.util.URI +import org.eclipse.emf.ecore.EObject +import org.eclipse.emf.ecore.resource.Resource +import org.eclipse.xtext.EcoreUtil2 +import org.eclipse.xtext.common.types.JvmType +import org.eclipse.xtext.generator.AbstractGenerator +import org.eclipse.xtext.generator.IFileSystemAccess2 +import org.eclipse.xtext.generator.IGeneratorContext +import org.sa.rainbow.configuration.RainbowOutputConfigurationProvider +import org.sa.rainbow.configuration.Utils +import org.sa.rainbow.configuration.XtendUtils +import org.sa.rainbow.configuration.rcl.Actual +import org.sa.rainbow.configuration.rcl.Array +import org.sa.rainbow.configuration.rcl.Assignment +import org.sa.rainbow.configuration.rcl.BooleanLiteral +import org.sa.rainbow.configuration.rcl.CommandCall +import org.sa.rainbow.configuration.rcl.Component +import org.sa.rainbow.configuration.rcl.ComponentType +import org.sa.rainbow.configuration.rcl.DeclaredProperty +import org.sa.rainbow.configuration.rcl.DoubleLiteral +import org.sa.rainbow.configuration.rcl.Effector +import org.sa.rainbow.configuration.rcl.Factory +import org.sa.rainbow.configuration.rcl.Gauge +import org.sa.rainbow.configuration.rcl.GaugeType +import org.sa.rainbow.configuration.rcl.IPLiteral +import org.sa.rainbow.configuration.rcl.ImpactVector +import org.sa.rainbow.configuration.rcl.IntegerLiteral +import org.sa.rainbow.configuration.rcl.LogLiteral +import org.sa.rainbow.configuration.rcl.Probe +import org.sa.rainbow.configuration.rcl.PropertyReference +import org.sa.rainbow.configuration.rcl.RainbowConfiguration +import org.sa.rainbow.configuration.rcl.Reference +import org.sa.rainbow.configuration.rcl.StringLiteral +import org.sa.rainbow.configuration.rcl.Value +import org.sa.rainbow.configuration.validation.RclValidator + +/** + * Generates code from your model files on save. + * + * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#code-generation + */ +class RclGenerator extends AbstractGenerator { + + override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) { + val model = resource.contents.head as RainbowConfiguration + var String filename = null + if (model.export !== null) { + filename='''«model.targetName»/«model.export.filename»''' + } + if(filename === null) + filename = ("generated-unnamed"); + if (model.probes !== null && !model.probes.isEmpty) { + fsa.generateFile(filename, RainbowOutputConfigurationProvider::RAINBOW_TARGET_PROPERTIES_OUTPUT, + outputProbeSpec(resource.URI, model.probes, model.delcaredProperties)) + } + if ((model.gauges !== null || model.gaugeTypes !== null) && + (!model.gauges.isEmpty || !model.gaugeTypes.isEmpty)) { + fsa.generateFile(filename, RainbowOutputConfigurationProvider::RAINBOW_TARGET_PROPERTIES_OUTPUT, + outputGuageSpec(resource.URI, model.gauges, model.gaugeTypes, model.delcaredProperties)) + for (gauge : model.gaugeTypes) { + val hasRegexp = !gauge.body.commands.filter[it.regexp!==null].empty + if (hasRegexp) { + val clazz = XtendUtils.unpackString((gauge.body.assignment.findFirst[it.name == "setup"].value.value as Component).assignment.findFirst[it.name=="generatedClass"].value.value as StringLiteral, true) + var gCFilename = clazz + gCFilename = gCFilename.replaceAll("\\.", "/") + ".java" + fsa.generateFile(gCFilename, RainbowOutputConfigurationProvider::RAINBOW_GENERRATED_SOURCE_OUTPUT, toJavaCode(resource.URI, gauge, clazz)); + } + } + } + if ((model.effectors !== null || model.effectorTypes !== null) && + (!model.effectors.isEmpty || !model.effectorTypes.isEmpty)) { + fsa.generateFile(filename, RainbowOutputConfigurationProvider::RAINBOW_TARGET_PROPERTIES_OUTPUT, + outputEffectorSpec(resource.URI, model.effectors, model.effectorTypes, model.delcaredProperties)) + } + val utilities = EcoreUtil2.getAllContentsOfType(model, DeclaredProperty).filter[it.component == ComponentType.UTILITY] + if (!utilities.empty && !model.impacts.empty) { + val output = outputUtilityModel(resource.URI,utilities, model.impacts) + fsa.generateFile(filename, RainbowOutputConfigurationProvider::RAINBOW_TARGET_PROPERTIES_OUTPUT, output) + } + val uis = EcoreUtil2.getAllContentsOfType(model, DeclaredProperty).filter[it.component == ComponentType.GUI] + if (!uis.empty) { + val output = outputUIModel(resource.URI, uis); + fsa.generateFile(model.targetName + "/ui.yml", RainbowOutputConfigurationProvider::RAINBOW_TARGET_PROPERTIES_OUTPUT, output) + } + + if (filename.endsWith("properties") || + (model.gauges === null && model.probes == null && model.delcaredProperties != null)) { + var output = outputPropertiesSpec(resource.URI, model.delcaredProperties) + fsa.generateFile(filename, RainbowOutputConfigurationProvider::RAINBOW_TARGET_PROPERTIES_OUTPUT, output); + } + if (model.factories !== null && !model.factories.empty) { + for (f : model.factories) { + outputCommandFactory(resource, fsa, f) + } + } + +// fsa.generateFile('greetings.txt', 'People to greet: ' + +// resource.allContents +// .filter(Greeting) +// .map[name] +// .join(', ')) + } + + def outputUIModel(URI uri, Iterable properties) { + val ui = EcoreUtil2.getAllContentsOfType(properties.get(0), Assignment).findFirst[it.name=='specs'] + val gauges = EcoreUtil2.getAllContentsOfType(ui, Assignment).filter[it.name=='gauge'] + val analyzers = EcoreUtil2.getAllContentsOfType(ui, Assignment).filter[it.name=='analyzers'].map[EcoreUtil2.getAllContentsOfType(it, Assignment)].flatten.filter[it.name=="analyzer"] + val managers = EcoreUtil2.getAllContentsOfType(ui, Assignment).filter[it.name=='managers'].map[EcoreUtil2.getAllContentsOfType(it, Assignment)].flatten.filter[it.name=="manager"] + val executors = EcoreUtil2.getAllContentsOfType(ui, Assignment).filter[it.name=='executors'].map[EcoreUtil2.getAllContentsOfType(it, Assignment)].flatten.filter[it.name=="executor"] + val details = EcoreUtil2.getAllContentsOfType(ui, Assignment).filter[it.name=='details'].map[EcoreUtil2.getAllContentsOfType(it, Assignment)].flatten + ''' + ############################################################# + # Generated by Rainbow XText Configuration DSL -- DO NOT EDIT + # Source: «uri.toString» + ############################################################# + gauges: + «FOR g : gauges» + «(((g.value.value as Component).assignment.findFirst[it.name=='type'].value.value as PropertyReference).referable as GaugeType).name»: + builtin: + category: «XtendUtils.unpackString((g?.value?.value as Component)?.assignment?.findFirst[it.name=='category']?.value?.value as StringLiteral, true)» + command: «getCommand(g)» + value: «((g?.value?.value as Component)?.assignment?.findFirst[it.name=='value.parameter']?.value?.value as IntegerLiteral).value» + «IF (g?.value?.value as Component)?.assignment?.findFirst[it.name=='upper'] !== null» + upper: «((g?.value?.value as Component)?.assignment?.findFirst[it.name=='upper'].value.value as DoubleLiteral).value» + «ENDIF» + «IF (g?.value?.value as Component)?.assignment?.findFirst[it.name=='lower'] !== null» + lower: «((g?.value?.value as Component)?.assignment?.findFirst[it.name=='lower'].value.value as DoubleLiteral).value» + «ENDIF» + «ENDFOR» + analyzers: + «FOR a : analyzers» + «(((((a.value.value as Component).assignment.findFirst[it.name=='for'].value.value as PropertyReference).referable as DeclaredProperty).value.value as Component).assignment.findFirst[it.name=='class'].value.value as Reference).referable.qualifiedName»: «((a.value.value as Component).assignment.findFirst[it.name=='class'].value.value as Reference).referable.qualifiedName» + «ENDFOR» + managers: + «FOR a : managers» + «(((((a.value.value as Component).assignment.findFirst[it.name=='for'].value.value as PropertyReference).referable as DeclaredProperty).value.value as Component).assignment.findFirst[it.name=='class'].value.value as Reference).referable.qualifiedName»: «((a.value.value as Component).assignment.findFirst[it.name=='class'].value.value as Reference).referable.qualifiedName» + «ENDFOR» + executors: + «FOR a : executors» + «(((((a.value.value as Component).assignment.findFirst[it.name=='for'].value.value as PropertyReference).referable as DeclaredProperty).value.value as Component).assignment.findFirst[it.name=='class'].value.value as Reference).referable.qualifiedName»: «((a.value.value as Component).assignment.findFirst[it.name=='class'].value.value as Reference).referable.qualifiedName» + «ENDFOR» + details: + «FOR d : details» + «d.name»: «(d.value.value as Reference).referable.qualifiedName» + «ENDFOR» + ''' + } + + def getCommand(Assignment g) { + val gt = (((g.value.value as Component).assignment.findFirst[it.name=='type'].value.value as PropertyReference).referable as GaugeType) + val cmd = XtendUtils.unpackString((g?.value?.value as Component)?.assignment?.findFirst[it.name=='command']?.value?.value as StringLiteral, true) + val command = gt.body.commands.findFirst[it.name == cmd] + if (command !== null) { + '''«IF command.target !== null»«command.target».«ENDIF»«command.command»«FOR p : command.formal BEFORE '(' SEPARATOR ', ' AFTER ')'»«p.simpleName»«ENDFOR»''' + } + + } + + + def outputCommandFactory(Resource resource, IFileSystemAccess2 fsa, Factory factory) { + var filename = factory.clazz + filename = filename.replaceAll("\\.", "/") + ".java" + fsa.generateFile(filename, RainbowOutputConfigurationProvider::RAINBOW_GENERRATED_SOURCE_OUTPUT, toJavaCode(resource.URI, factory)); + } + + def toJavaCode(URI uri, GaugeType gt, String clazz) ''' + // This file was generated by the Rainbow configuration generator + // Sourcee: «uri.toString» gaugeType = «gt.name» + package «clazz.substring(0, clazz.lastIndexOf("."))»; + import java.util.List; + import java.util.Map; + import java.util.regex.Matcher; + import java.util.regex.Pattern; + + import org.sa.rainbow.core.error.RainbowException; + import org.sa.rainbow.core.models.commands.IRainbowOperation; + import org.sa.rainbow.core.util.TypedAttribute; + import org.sa.rainbow.core.util.TypedAttributeWithValue; + import org.sa.rainbow.core.gauges.ConfigurableRegularPatternGauge; + + public class «clazz.substring(clazz.lastIndexOf(".")+1)» extends ConfigurableRegularPatternGauge { + protected static final String THREAD_NAME = "«gt.name»"; + + «FOR cmd : gt.body.commands» + public static final String «cmd.command.toUpperCase.replaceAll("[\\-.]","_")» = "«cmd.name»"; + public static final String «cmd.command.toUpperCase.replaceAll("[\\-.]","_")»_PATTERN = "«XtendUtils.unpackString(cmd.regexp, true, true).replace("\\", "\\\\")»"; + «ENDFOR» + + public «clazz.substring(clazz.lastIndexOf(".")+1)» ( + String id, + long beaconPeriod, + TypedAttribute gaugeDesc, + TypedAttribute modelDesc, + List setupParams, + Map mappings + ) throws RainbowException { + super(THREAD_NAME, id, beaconPeriod, gaugeDesc, modelDesc, setupParams, mappings); + } + + @Override + protected void loadPatterns () { + «FOR cmd : gt.body.commands» + addPattern(«cmd.command.toUpperCase.replaceAll("[\\-.]","_")», Pattern.compile(«cmd.command.toUpperCase.replaceAll("[\\-.]","_")»_PATTERN)); + «ENDFOR» + } + + + } + ''' + + def toJavaCode(URI uri, Factory factory) ''' + // This file was generated by the Rainbow configuration generator + // Sourcee: «uri.toString» + package «factory.clazz.substring(0, factory.clazz.lastIndexOf("."))»; + import java.io.InputStream; + import org.acmestudio.acme.element.*; + import org.sa.rainbow.core.error.RainbowException; + import org.sa.rainbow.core.models.ModelsManager; + + import «factory.defn.modelClass.qualifiedName»; + «IF factory.defn.extends !== null» + import «factory.defn.extends.qualifiedName»; + «ENDIF» + import «factory.defn.loadCmd.qualifiedName»; + «IF factory.defn.saveCmd !== null» + import «factory.defn.saveCmd.qualifiedName»; + «ENDIF» + + import incubator.pval.Ensure; + + «FOR cmd : factory.defn.commands» + import «cmd.cmd.qualifiedName»; + «ENDFOR» + + public class «factory.clazz.substring(factory.clazz.lastIndexOf(".")+1)» + «IF factory.defn.extends !== null» + extends «factory.defn.extends.simpleName» + «ENDIF» + { + public static «factory.defn.loadCmd.simpleName» loadCommand (ModelsManager modelsManager, + String modelName, + InputStream stream, + String source) { + return new «factory.defn.loadCmd.simpleName» (modelName, modelsManager, stream, source); + } + + public «classFor(factory.clazz)» («factory.defn.modelClass.simpleName» model) throws RainbowException { + super(model); + } + + «FOR cmd : factory.defn.commands» + public static final String «constantName(cmd.name)» = "«cmd.name»"; + «ENDFOR» + + «FOR cmd : factory.defn.commands» + @Operation(name=«constantName(cmd.name)») + public «cmd.cmd.simpleName» «cmd.name»Cmd «FOR p : cmd.formal BEFORE '(' SEPARATOR ',' AFTER ')'»«XtendUtils.formalTypeName(p, false)» «p.name» «ENDFOR» + { + «FOR p : cmd.formal» + «IF p.type instanceof AnyTypeRef» + Ensure.is_true(«p.name».declaresType("«XtendUtils.getAcmeTypeName(p.type as AnyTypeRef)»")); + «ENDIF» + «ENDFOR» + return new «cmd.cmd.simpleName» («constantName(cmd.name)», («factory.defn.modelClass.simpleName» )m_modelInstance, «IF cmd.formal.get(0).name != "target"»"", «ENDIF»«FOR p : cmd.formal SEPARATOR ', '»«XtendUtils.convertToString(p)»«ENDFOR»); + } + + «ENDFOR» + } + + ''' + + def constantName(String string) { + string.replaceAll('([A-Z])', '_$1').toUpperCase + "_CMD" + } + + def classFor(String name) { + if (name.contains(".")) return name.substring(name.lastIndexOf(".")+1) + else return name + } + + def outputUtilityModel(URI uri, Iterable properties, EList list) { + var model = "" + var utilities = "" + var scenarios = "" + for (um : properties) { + val value = um.value.value as Component + val m = value.assignment.findFirst[it.name=='model'].value.value as PropertyReference + val theModel = m.referable as DeclaredProperty + val component = theModel.value.value as Component + val name = stringValue((component).assignment.findFirst[it.name == "name"]?.value) ?: + theModel.name + var type = stringValue(component.assignment.findFirst[it.name == "type"]?.value) + if (type === null) { + type = getModelTypeFromClass( + ((component.assignment.findFirst[it.name == "factory"]?.value.value) as Reference). + referable, "MODELTYPE") + if (type === null) { + type = "???" + } + } + model = ''' + model: + name: «name» + type: «type» + ''' + val us = value.assignment.findFirst[it.name=='utilities'].value.value as Component + + utilities = ''' + utilities: + «FOR u : us.assignment» + «u.name»: + label: «surroundString(XtendUtils.unpackString((u.value.value as Component).assignment.findFirst[it.name=='label']?.value.value as StringLiteral, false), true)» + mapping: «surroundString(XtendUtils.unpackString((u.value.value as Component).assignment.findFirst[it.name=='mapping']?.value.value as StringLiteral, false), true)» + description: «surroundString(XtendUtils.unpackString((u.value.value as Component).assignment.findFirst[it.name=='description']?.value.value as StringLiteral, false), true)» + utility: + «FOR uv : ((u.value.value as Component).assignment.findFirst[it.name=='utility']?.value.value as Array).values» + «RclValidator.getNumber((uv.value as Array).values.get(0))»: «RclValidator.getNumber((uv.value as Array).values.get(1))» + «ENDFOR» + «ENDFOR» + ''' + val scs = value.assignment.findFirst[it.name=='scenarios'].value.value as Array + scenarios = ''' + weights: + «FOR scenario : scs.values» + «XtendUtils.unpackString((scenario.value as Component).assignment.findFirst[it.name=="name"].value.value as StringLiteral, true)»: + «FOR u : (scenario.value as Component).assignment.filter[it.name != "name"]» + «u.name»: «RclValidator.getNumber(u.value)» + «ENDFOR» + «ENDFOR» + ''' + } + + val vectors=''' + vectors: + «FOR iv : list» + «iv.tactic.name»: + «FOR u : (iv.component.assignment)» + «u.name»: «RclValidator.getNumber(u.value)» + «ENDFOR» + «ENDFOR» + ''' + ''' + ############################################################# + # Generated by Rainbow XText Configuration DSL -- DO NOT EDIT + # Source: «uri.toString» + ############################################################# + «model» + «utilities» + «scenarios» + «vectors» + ''' + + } + + def outputPropertiesSpec(URI uri, EList vars) { + val models = vars.filter[it?.component === ComponentType.MODEL] + val analysis = vars.filter[it?.component === ComponentType.ANALYSIS] + val executors = vars.filter[it?.component === ComponentType.EXECUTOR] + val gui = vars.filter[it?.component === ComponentType.GUI] + val manager = vars.filter[it?.component === ComponentType.MANAGER] + val effectors = vars.filter[it?.component == ComponentType.EFFECTORMANAGER] + var properties = vars.filter[ + it?.component === ComponentType.PROPERTY + ] + ''' + ############################################################# + # Generated by Rainbow XText Configuration DSL -- DO NOT EDIT + # Source: «uri.toString» + ############################################################# + + «FOR v : properties» + «IF v.value !== null» + «v.name» = «Utils.removeQuotes(stringValue(v.value,false,false))» + «ENDIF» + «ENDFOR» + «outputModels(models)» + «outputAnalyses(analysis)» + «outputManagers(manager)» + «outputExecutors(executors)» + «outputEffectorManagers(effectors)» + «outputGUI(gui)» + ''' + } + + def outputGUI(Iterable properties) { + if (properties.empty) '''''' + else { + val gui = (properties.get(0).value.value as Component).assignment.findFirst[it.name=='class'] + var p = '''rainbow.gui=«(gui.value.value as Reference).referable.qualifiedName»''' + val guispecs = (properties.get(0).value.value as Component).assignment.findFirst[it.name=='specs'] + if (guispecs !== null) { + p = p +"\nrainbow.gui.specs=ui.yml" + } + p + } + } + + def outputEffectorManagers(Iterable ems) { + if (ems === null || ems.empty) return "" + var i = 0 + var sb = new StringBuffer('''rainbow.effector.manager.size=«ems.size» + ''') + for (e : ems) { + val ass = e.value.value as Component + val class = ass.assignment.findFirst[it.name == "class"] + sb.append('''rainbow.effector.manager.class_«i»=«(class.value.value as Reference).referable.qualifiedName» + ''') + } + sb.toString + } + + def outputAnalyses(Iterable analyses) { + if (analyses === null || analyses.empty) return "" + var i = 0 + var sb = new StringBuffer('''rainbow.analyses.size=«analyses.size» + ''') + for (a : analyses) { + val ass = a.value.value as Component + val class = ass.assignment.findFirst[it.name == "class"] + sb.append('''rainbow.analyses_«i»=«(class.value.value as Reference).referable.qualifiedName» + ''') + } + sb.toString + } + + def outputExecutors(Iterable executors) { + if(executors === null || executors.empty) return "" + var i = 0 + var sb = new StringBuffer('''rainbow.adaptation.executor.size=«executors.size» + ''') + for (e : executors) { + val ass = e.value.value as Component + val class = ass.assignment.findFirst[it.name == "class"] + val model = ass.assignment.findFirst[it.name == "model"] + sb.append('''rainbow.adaptation.executor.class_«i»=«(class.value.value as Reference).referable.qualifiedName» + ''') + sb.append('''rainbow.adaptation.executor.model_«i»=''') + val theModel = (model.value.value as PropertyReference).referable as DeclaredProperty + val component = theModel.value.value as Component + val name = stringValue((component).assignment.findFirst[it.name == "name"]?.value) ?: + theModel.name + var type = stringValue(component.assignment.findFirst[it.name == "type"]?.value) + if (type === null) { + type = getModelTypeFromClass( + ((component.assignment.findFirst[it.name == "factory"]?.value.value) as Reference). + referable, "MODELTYPE") + if (type === null) { + type = "???" + } + } + sb.append('''«name»:«type» + ''') + i = i + 1 + } + sb.toString + } + + def outputManagers(Iterable managers) { + if(managers === null || managers.empty) return "" + var i = 0 + var sb = new StringBuffer('''rainbow.adaptation.manager.size=«managers.size» + ''') + for (m : managers) { + val ass = m.value.value as Component + val class = ass.assignment.findFirst[it.name == "class"] + val model = ass.assignment.findFirst[it.name == "model"] + sb.append('''rainbow.adaptation.manager.class_«i»=«(class.value.value as Reference).referable.qualifiedName» + ''') + sb.append('''rainbow.adaptation.manager.model_«i»=''') + val theModel = (model.value.value as PropertyReference).referable as DeclaredProperty + val component = theModel.value.value as Component + val name = stringValue((component).assignment.findFirst[it.name == "name"]?.value) ?: + theModel.name + var type = stringValue(component.assignment.findFirst[it.name == "type"]?.value) + if (type === null) { + type = getModelTypeFromClass( + ((component.assignment.findFirst[it.name == "factory"]?.value.value) as Reference). + referable, "MODELTYPE") + if (type === null) { + type = "???" + } + } + sb.append('''«name»:«type» + ''') + i = i + 1 + } + sb.toString + } + + def getModelTypeFromClass(JvmType type, String stringConstant) { + // val tp = jvmTypeProviderFactory.createTypeProvider + val class = this.class.classLoader.loadClass(type.qualifiedName) + val typeField = class.getDeclaredField(stringConstant) + if (typeField === null) { + return null + } + val value = typeField.get(null) + return value as String + } + + def outputModels(Iterable models) { + if(models === null || models.empty) return "" + var i = 0 + val sb = new StringBuffer('''rainbow.model.number = «models.size» + ''') + for (m : models) { + val ass = m.value.value as Component + val loadclass = ass.assignment.findFirst[it.name == "factory"] + val path = ass.assignment.findFirst[it.name == "path"] + val saveOnClose = ass.assignment.findFirst[it.name == "saveOnClose"] + val saveLocation = ass.assignment.findFirst[it.name == "saveLocation"] + val name = Utils.removeQuotes(stringValue(ass.assignment.findFirst[it.name == "name"]?.value)) ?: m.name + sb.append('''rainbow.model.name_«i»=«name» + ''') + if (loadclass.value.value instanceof Reference) { + sb.append('''rainbow.model.load.class_«i»=«(loadclass.value.value as Reference).referable.qualifiedName» + ''') + } + else if (loadclass.value.value instanceof PropertyReference && + (loadclass.value.value as PropertyReference).referable instanceof Factory + ) { + val factory = (loadclass.value.value as PropertyReference).referable as Factory + sb.append('''rainbow.model.load.class_«i»=«factory.clazz» + ''') + } + if (path !== null) { + sb.append('''rainbow.model.path_«i»=«Utils.removeQuotes(stringValue(path.value, false, true))» + ''') + } + if (saveOnClose !== null) { + sb.append('''rainbow.model.saveOnClose_«i»=«Utils.removeQuotes(stringValue(saveOnClose.value, false, false))» + ''') + } + if (saveLocation !== null) { + sb.append('''rainbow.model.saveLocation_«i»=«Utils.removeQuotes(stringValue(saveLocation.value, false, false))» + ''') + } + i = i + 1 + } + + sb.toString + } + + def outputGuageSpec(URI uri, EList gauges, EList gaugeTypes, EList vars) ''' + ############################################################# + # Generated by Rainbow XText Configuration DSL -- DO NOT EDIT + # Source: «uri.toString» + ############################################################# + «IF !vars.empty» + vars: + «FOR v : vars» + «IF v.value !== null» + «v.name»: «stringValue(v.value, false,true)» + «ENDIF» + «ENDFOR» + «ENDIF» + gauge-types: + «FOR type : gaugeTypes» + «outputGaugeType(type)» + «ENDFOR» + gauge-instances: + «FOR gauge : gauges» + «outputGauge(gauge)» + «ENDFOR» + + ''' + + def outputProbeSpec(URI uri, EList probes, EList vars) ''' + ############################################################# + # Generated by Rainbow XText Configuration DSL -- DO NOT EDIT + # Source: «uri.toString» + ############################################################# + «IF !vars.empty» + vars: + «FOR v : vars» + «IF v.value !== null» + «v.name» : «stringValue(v.value, false,true)» + «ENDIF» + «ENDFOR» + «ENDIF» + probes: + «FOR probe : probes» + «outputProbe(probe)» + «ENDFOR» + ''' + + def outputEffectorSpec(URI uri, EList effectors, EList effectorTypes, EList vars) ''' + ############################################################# + # Generated by Rainbow XText Configuration DSL -- DO NOT EDIT + # Source: «uri.toString» + ############################################################# + «IF !vars.empty» + vars: + «FOR v : vars» + «IF v.value !== null» + «v.name» : «stringValue(v.value, false, true)» + «ENDIF» + «ENDFOR» + «ENDIF» + effector-types: + «FOR type : effectorTypes» + «outputEffector(type)» + «ENDFOR» + effectors: + «FOR eff : effectors» + «outputEffector(eff)» + «ENDFOR» + ''' + + def outputGauge(Gauge gauge) { + val setup = gauge.body.assignment.stream.filter[it.name == "setup"].findAny + val config = gauge.body.assignment.stream.filter[it.name == "config"].findAny + var CharSequence modelName = '''«gauge.body.modelName»:«gauge.body.modeltype»''' + if (gauge.body.ref !== null) { + var CharSequence internalName = gauge.body.ref.referable.name + var CharSequence type = "" + var gbv = (gauge.body.ref.referable as DeclaredProperty)?.value.value + if (gbv instanceof Component) { + val comp = gbv as Component + type = stringValue(comp.assignment.findFirst[it.name=="type"].value) + val n = comp.assignment.findFirst[it.name=="name"] + if (n !== null) { + internalName = stringValue(n.value) + } + } + modelName = '''«internalName»:«type»''' + } + ''' + «gauge.name»: + «IF gauge.superType !== null» + type: «gauge.superType.name» + «ENDIF» + model: "«modelName»" + commands: + «FOR command : gauge.body.commands» + «command.name»: «outputCall(command)» + «ENDFOR» + «IF setup.present && setup.get.value.value instanceof Component» + setupValues: + «FOR p : (setup.get.value.value as Component).assignment» + «p.name»: «stringValue(p.value,false,true)» + «ENDFOR» + «ENDIF» + «IF config.present && config.get.value.value instanceof Component» + configValues: + «FOR p : (config.get.value.value as Component).assignment» + «IF p.name == 'targetProbe'» + «IF p.value.value instanceof Array» + targetProbeList: «extractProbeAliases(p.value.value as Array)» + «ELSEIF p.value.value instanceof PropertyReference && (p.value.value as PropertyReference).referable instanceof Probe» + targetProbeType: «extractProbeAlias((p.value.value as PropertyReference).referable as Probe)» + «ENDIF» + «ELSE» + «p.name»: «stringValue(p.value,false, true)» + «ENDIF» + «ENDFOR» + «ENDIF» + ''' + } + + def extractProbeAliases(Array array) { + array.values.filter[it.value instanceof PropertyReference && (it.value as PropertyReference).referable instanceof Probe].map[extractProbeAlias((it.value as PropertyReference).referable as Probe)].join(", ") + } + + def extractProbeAlias(Probe probe) { + '''«stringValue(probe.properties.assignment.findFirst[name=='alias']?.value)»''' + } + + def outputCall(CommandCall call) { + var ret = new StringBuilder() + if (call.target !== null) { + ret.append(call.target).append(".") + } else if (call.ref != null) { + ret.append("${").append(call.ref.referable.name).append("}.") + } + ret.append(call.command) + val params = '''(«call.actual.map[actual(it)].join(", ")»)''' + ret.append(params)//.append("\"") + ret + } + + def actual(Actual p) { + if (p.id === null && p.pr === null && p.ng === null && p.value !== null) + stringValue(p.value) + else if (p.pr !== null) + '''${«p.pr.referable.name»}''' + else if (p.ref && p.id !== null) '''$<«p.id»>''' + else if (p.ref && p.ng !== null) '''$<«p.ng»>''' + else if (p.ref ) '''$<«p.ag»>''' + else '''«p.id»''' + } + + def outputGaugeType(GaugeType type) { + val setup = type.body.assignment.stream.filter[it.name == "setup"].findAny + val config = type.body.assignment.stream.filter[it.name == "config"].findAny + ''' + «type.name»: + commands: + «FOR command : type.body.commands» + «command.name»: «IF command.target !== null»«command.target».«ENDIF»«command.command»«FOR p : command.formal BEFORE '(' SEPARATOR ', ' AFTER ')'»«p.simpleName»«ENDFOR» + «ENDFOR» + «IF setup.present && setup.get.value.value instanceof Component» + setupParams: + «FOR p : (setup.get.value.value as Component).assignment» + «IF p.name == "generatedClass"» + javaClass: + «ELSE» + «p.name»: + «ENDIF» + type: «typeValue(p.value)» + default: «stringValue(p.value, false, true)» + «ENDFOR» + «ENDIF» + «IF config.present && config.get.value.value instanceof Component» + configParams: + «FOR p : (config.get.value.value as Component).assignment» + «IF p.name != "targetProbe"» + «p.name»: + «IF p.value?.value instanceof Reference» + type: «(p.value.value as Reference).referable.simpleName» + default: ~ + «ELSE» + type: «typeValue(p.value)» + default: «stringValue(p.value,false,true)» + «ENDIF» + «ENDIF» + «ENDFOR» + «ENDIF» + ''' + + } + + def outputEffector(Effector effector) { + val attsST = getAssignmentsMap(effector?.superType?.body?.assignment) + val atts = getAssignmentsMap(effector?.body?.assignment) + val command = if (effector.body.command !== null) { + effector.body.command + } else if (effector?.superType?.body?.command !== null) { + effector.superType.body.command + } + return ''' + «effector.name»: + «IF command !== null» + command: "«outputCall(command)»" + «ENDIF» + «FOR entry : attsST.entrySet()» + «IF !atts.containsKey(entry.getKey())» + «IF entry.getKey() == "script"» + type: script + scriptInfo: «stringValue(entry.getValue().value, true, null)» + «ELSEIF entry.getKey() == "java"» + type: java + javaInfo: «stringValue(entry.getValue().value, true, null)» + «ELSE» + «entry.getKey()»: «stringValue(entry.getValue().value, true, true)» + «ENDIF» + «ENDIF» + «ENDFOR» + «FOR entry : atts.entrySet()» + «IF entry.getKey() == "script"» + type: script + scriptInfo: «stringValue(entry.getValue().value, true, null)» + «ELSEIF entry.getKey() == "java"» + type: java + javaInfo: «stringValue(entry.getValue().value, true, null)» + «ELSE» + «entry.getKey()»: «stringValue(entry.getValue().value, true, true)» + «ENDIF» + «ENDFOR» + ''' + } + + def outputProbe(Probe probe) { + val attsST = getAssignmentsMap(probe?.superType?.properties?.assignment) + val atts = getAssignmentsMap(probe?.properties?.assignment) + return ''' + «probe.name»: + «FOR entry : attsST.entrySet()» + «IF !atts.containsKey(entry.getKey())» + «IF entry.getKey() == "script"» + type: script + scriptInfo: «stringValue(entry.getValue().value, true, null)» + «ELSEIF entry.getKey() == "java"» + type: java + javaInfo: «stringValue(entry.getValue().value, true, null)» + «ELSE» + «entry.getKey()» : «stringValue(entry.getValue().value, true,true)» + «ENDIF» + «ENDIF» + «ENDFOR» + «FOR entry : atts.entrySet()» + «IF entry.getKey() == "script"» + type: script + scriptInfo: «stringValue(entry.getValue().value, true, attsST.get(entry.getKey())?.value)» + «ELSEIF entry.getKey() == "java"» + type: java + javaInfo: «stringValue(entry.getValue().value, true, attsST.get(entry.getKey())?.value)» + «ELSEIF entry.getKey() == "mode"» + mode: «Utils.removeQuotes(stringValue(entry.getValue().value, true, attsST.get(entry.getKey())?.value))» + «ELSE» + «entry.getKey()» : «stringValue(entry.getValue().value, true, attsST.get(entry.getKey())?.value)» + «ENDIF» + «ENDFOR» + ''' + } + + def getAssignmentsMap(EList assignments) { + val map = new HashMap() + if (assignments !== null) { + for (assignment : assignments) { + map.put(assignment.name, assignment) + } + } + return map + } + + def String stringValue(EObject value) { + switch value { + StringLiteral: + XtendUtils.unpackString(value, true) + IntegerLiteral: '''«value.value»''' + DoubleLiteral: '''«value.value»''' + BooleanLiteral: '''«value.isTrue»''' + Value: stringValue(value.value) + } + + } + + def stringValue(Value value, boolean allowComponent, Value mergeComponentWith) { + if (value.value instanceof Component && allowComponent) { + var comp = value.value as Component + val atts = getAssignmentsMap(comp.assignment) + val attsST = getAssignmentsMap((mergeComponentWith?.value as Component)?.assignment) + return ''' + + «FOR entry : attsST.entrySet()» + «IF !atts.containsKey(entry.getKey())» + «entry.getKey()»: «stringValue(entry.getValue().value, true, false)» + «ENDIF» + «ENDFOR» + «FOR entry : atts.entrySet()» + «entry.getKey()»: «stringValue(entry.getValue().value, true, false)» + «ENDFOR» + ''' + } + else { + stringValue(value.value) + } + } + + def typeValue(Value value) { + val v = value.value + switch v { + StringLiteral: "String" + BooleanLiteral: "Boolean" + IntegerLiteral: "Integer" + DoubleLiteral: "Double" + Reference: "String" + PropertyReference: "String" + default: '''unknown''' + } + + } + + def CharSequence stringValue(Value value, boolean allowComposite, boolean asString) { + var v = value.value + switch v { + StringLiteral: '''"«XtendUtils.unpackString(v,true)»"''' + BooleanLiteral: + surroundString('''«v.isTrue»''', asString) + IntegerLiteral: '''«v.value»''' + DoubleLiteral: '''«v.value»''' + LogLiteral: + surroundString('''«v.value»''', asString) + IPLiteral: + surroundString('''«v.value»''', asString) + Reference: + surroundString('''«v.referable.qualifiedName»''', asString) + PropertyReference: + if (v.referable instanceof DeclaredProperty) { + surroundString('''${«v.referable.name»}''', asString) + } + else { + v.referable.name + } + + Component case allowComposite: '''"Not implemented yet"''' + default: '''"Not implemented yet"''' + } + + } + + def surroundString(String string, boolean b) { + if (b) '''"«string»"''' else string + } + + + +// } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/rcl.xtext b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/rcl.xtext new file mode 100644 index 000000000..08d9d8931 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/rcl.xtext @@ -0,0 +1,593 @@ +grammar org.sa.rainbow.configuration.Rcl hidden (WS, ML_COMMENT, SL_COMMENT) + +import "http://www.eclipse.org/emf/2002/Ecore" as ecore +//import "platform:/resource/org.sa.rainbow.configuration/model/ConfigModel.ecore" +import "http://www.eclipse.org/xtext/common/JavaVMTypes" as types +import "http://www.sa.org/rainbow/stitch/Stitch" as stitch +import "http://www.acme.org/Acme" as acme + +generate rcl "http://www.sa.org/rainbow/configuration/RCL" + +RainbowConfiguration: + ('target' targetName=FQN + imports+=Import* + (delcaredProperties+=DeclaredProperty)* + ( + + (probeTypes+=ProbeType)* + (probes+=Probe)* + ) + ( + (gaugeTypes+=GaugeType)* + (gauges+=Gauge)* + + ) + ( + (effectorTypes+=EffectorType)* + (effectors+=Effector)* + ) + ( + (impacts+=ImpactVector)* + ) + + +// exports+=Export* + export=Export? + ) | + ( + imports+=Import* + factories+=Factory* + ) +; + +Factory: + ModelFactory name=ID 'yields' clazz=FQN defn=FactoryDefinition +; + +ModelFactory: + 'model' 'factory' +; + +FactoryDefinition: + {FactoryDefinition} + '{' + ('extends' extends=[types::JvmType|FQN])? + 'for' modelClass=[types::JvmType|FQN] ';'? + CommandLoad loadCmd=[types::JvmType|FQN] ';'? + (CommandSave saveCmd=[types::JvmType|FQN] ';'?)? + commands+=CommandDefinition* + + '}' +; + +CommandLoad: + 'command' 'load' 'is' +; + +CommandSave: + 'command' 'save' 'is' +; + +CommandDefinition: + 'command' name=ID '(' (formal+=FormalParam (',' formal+=FormalParam)*)?')' 'is' cmd=[types::JvmType|FQN] ';'? +; + +FormalParam: + type=Type name=(ID | 'target') +; + + +Type: + /*{Type} 'int' | {Type} 'boolean' | {Type} 'double' | {Type} 'String' | */base=BaseType | ref=[ecore::EObject|FQN] + //refjava=JavaReference | 'acme''::'acme=AcmeReference +; + +//AcmeReference: +// referable=[acme::AnyTypeRef|FQN] +//; + +enum BaseType: + COMPONENT="component" | COMPONENT="Component" | + CONNECTOR="connector" | CONNECTOR="Connector" | + PORT="port" | PORT="Port" | + ROLE="role" | ROLE="Role" +; + +JavaReference: + referable=[types::JvmType|FQN] +; + +ImpactVector: + 'impact' utilityModel=PropertyReference tactic=[stitch::tactic] '=' component=Component +; + +ModelType: + ModelTypeKW name=ID ('->' superType=[ModelType])? '=' '{' properties=Component '}' + ('commands' '=' '{' (commands+=CommandSignature)+ '}') 'generate' filename=StringLiteral +; + +ModelTypeKW: + 'model' 'type' +; + +CommandSignature: + 'command' +; + +Export: + 'export' references=References 'to' filename=(RICH_TEXT_DQ) +; + +References: + {References} all?='*' | + (refs+=[Ref|FQN]) (',' refs+=[Ref|FQN])* +; + +Ref: + DeclaredProperty | Probe | Gauge | Effector +; + +enum ComponentType: + PROPERTY | + ANALYSIS='analysis' | + EXECUTOR='executor' | + EFFECTORMANAGER= 'effector-manager' | + GUI='gui' | + MANAGER='adaptation-manager' | + MODEL='model' | + UTILITY='utility' + +; + +DeclaredProperty: + 'def' component=(ComponentType)? (type=[types::JvmType|FQN])? name=FQN('=' value=Value)? +; + +ProbeType returns Probe: + 'probe' type?='type' name=ID '=' properties=Component +; + +EffectorType returns Effector: + 'effector' type?='type' name=ID '=' body=EffectorBody +; + +Effector returns Effector: + 'effector' name=ID ('->' superType=[Effector])? ('=' body=EffectorBody) +; + +EffectorBody: + '{' + ('model' ((modelName=ID '::' modeltype=ID) | ref=PropertyReference))? + command=CommandCall + (assignment+=Assignment)* + '}' +; + +Probe returns Probe: + 'probe' name=ID ('->' superType=[Probe])? ('=' properties=Component)? +; + +GaugeType: + 'gauge' type?='type' name=ID '=' body=GaugeTypeBody +; + +Gauge returns Gauge: + 'gauge' name=ID ('->' superType=[GaugeType])? /*('=' properties=Component)?*/ ('=' body=GaugeBody)? +; + + +GaugeBody: + '{' + 'model' ((modelName=ID '::' modeltype=ID) | ref=PropertyReference) + (commands+=CommandCall)* + (assignment+=Assignment)* + '}' +; + +GaugeTypeBody: + '{' + (ModelFactory mcf=(PropertyReference | Reference))? + (commands+=CommandReference)+ + (assignment+=Assignment)* + + '}' +; + +JavaClassOrFactory: + + java=JavaReference | factory=PropertyReference +; + + +CommandReference: + 'command' name=ID '=' (regexp=StringLiteral '->' )? (target=ID'.')? command=ID '(' (formal+=[types::JvmType|FQN] (',' formal+=[types::JvmType|FQN])*)? ')' +; + +CommandCall: + 'command' (name=ID '=')? ((target=ID | ref=PropertyReference) '.')? command=ID '(' (actual+=Actual (',' actual+=Actual)*)? ')' +; + +Actual: + ref?='$<' (ng=ID | ag=INT) '>' | + id=ID | + pr=PropertyReference | + value=StringLiteral | + value=IntegerLiteral | + value=BooleanLiteral | + value=DoubleLiteral +; + + +enum ImportType: + CONFIG='configuration' | + PROPS='properties' | + STITCH="stitch" | + ACME="acme" | + FACTORY="factory" +; + + +Import: +// 'import' importedNamespace=ImportedFQN +'import' type=ImportType importURI=(RICH_TEXT_DQ) +; + +ImportedFQN: + FQN ('.*')? +; + +RootComponent returns Component: + {Component} + assignment+=Assignment* + +; +Component returns Component: + {Component} '{' + assignment+=Assignment* + '}' +; + +Assignment: + name=FQN '=' value=Value +; + +Value: + value=Component | + value=StringLiteral | + value=BooleanLiteral | + value=IntegerLiteral | + value=DoubleLiteral | + value=Reference | + value=IPLiteral | + value=LogLiteral | + value=PropertyReference | +// value=ModelMapping | +// value=ProbeReference | + value=Array // | +// value=ModelFactoryReference + +; + +//ModelMapping: +// mapping=AcmeMapping | +// mapping=JavaMapping +//; +// +//enum MappingType: +// EAVG='EAvg' | +// AVG='Avg' | +// MAX='Max' | +// MIN='Min' | +// EXPR='Expr' +//; +// +// +// +//AcmeMapping: +// type=MappingType expr=(acme::booleanExpression | acme::idExpression | acme::setExpression | acme::pathExpression) +//; + + +AnyRef: + Factory | DeclaredProperty | Gauge | GaugeType | Probe | ProbeType | Effector | EffectorType +; + + +Array: + {Array} '[' (values+=Value (',' values+=Value)*)? ']' +; + +LogLiteral: + value=LOGLEVEL +; + +enum LOGLEVEL: + OFF | FATAL | ERROR | WARN | INFO | DEBUG | TRACE | ALL +; + +IPLiteral: + value=IPValue +; + +IPValue returns ecore::EString: + INT '.' INT '.' INT '.' INT +; + +DoubleLiteral: + value=DoubleValue +; + +DoubleValue returns ecore::EDouble: + IntValue '.' INT +; + +IntegerLiteral: + value=IntValue +; + +IntValue returns ecore::EInt: + ('-' | '+')? INT +; + +BooleanLiteral: + {BooleanLiteral}(isTrue?='true'|'false') +; + +Reference: + (referable=[types::JvmType|FQN]) +; + +PropertyReference: + '««' referable=[AnyRef|FQN] '»»' +; + +//ProbeReference: +// 'probe' referable=[Probe|FQN] +//; +// +ModelFactoryReference: + referable=[Factory|ID] +; + +FQN: + ID ('.' ID)* +; + +StringLiteral: +// SimpleStringLiteral | + RichStringDQ +; + +//SimpleStringLiteral: +// value=STRING +//; + +//RichStringSQ: +// {RichString} ( +// expressions+=RichStringLiteralSQ | +// expressions+=RichStringLiteralStartSQ expressions+=RichStringPart? +// (expressions+=RichStringLiteralInbetweenSQ expression+=RichStringPart?)* +// expressions+=RichStringLiteralEndSQ +// ) +//; +// +//RichStringLiteralSQ: +// {RichStringLiteral} value=RICH_TEXT_SQ +//; +// +//RichStringLiteralStartSQ: +// {RichStringLiteral} +// value=RICH_TEXT_START_SQ +//; +// +//RichStringLiteralInbetweenSQ: +// {RichStringLiteral} +// (value=RICH_TEXT_INBETWEEN_SQ) +//; +// +//RichStringLiteralEndSQ: +// {RichStringLiteral} +// (value=RICH_TEXT_END_SQ) +//; + +RichStringDQ: + {RichString} ( + expressions+=RichStringLiteralDQ | + expressions+=RichStringLiteralStartDQ expressions+=RichStringPart? + (expressions+=RichStringLiteralInbetweenDQ expression+=RichStringPart?)* + expressions+=RichStringLiteralEndDQ + ) +; + +RichStringLiteralDQ: + {RichStringLiteral} value=RICH_TEXT_DQ +; + +RichStringLiteralStartDQ: + {RichStringLiteral} + value=RICH_TEXT_START_DQ +; + +RichStringLiteralInbetweenDQ: + {RichStringLiteral} + (value=RICH_TEXT_INBETWEEN_DQ) +; + +RichStringLiteralEndDQ: + {RichStringLiteral} + (value=RICH_TEXT_END_DQ) +; + +//InteralRichStringSQ: +// {RichString} ( +// expressions+=RichStringLiteralInbetweenSQ (expressions+=RichStringPart? expressions+=RichStringLiteralInbetweenSQ)* +// ) +//; + +RichStringPart: + referable=[DeclaredProperty|FQN] +; + +// +//PropertyRef: +// referable=[Model|STRING] +//; +// +//PropertyReference: +// value=PROPERTY_REFERENCE +//; + +//StringLiteral hidden(): +// begin="'" +// parts+=PlainString? +// (parts+=PropertyReference parts+=PlainString)* +// end="'" +// | +// begin='"' +// parts+=PlainString? +// (parts+=PropertyReference parts+=PlainString)* +// end='"' +//; +// +//PropertyReference hidden(): +// '${' PropertyReferenceImpl '}'; +// +////terminal PROPERTY_REFERENCE: +//// '${' ( '\\' . /* 'b'|'t'|'n'|'f'|'r'|'u'|'"'|"'"|'\\' */ | !('\\'|'"') )* '}' +////; +// +//PropertyReferenceImpl returns PropertyReference hidden(WS,ML_COMMENT,SL_COMMENT): +// referable=[DeclaredProperty|FQN] +//; +// +//PlainString: +// value=ConstantValue +//; +// +//// To identify other keywords or INT as allowed parts in a string, +//// we use a customized lexer with predicates. +//// This allows us to use e.g. single quotes without escape sequences +//// in double quoted strings and vice versa. +//ConstantValue: +// (WS| +// ANY_OTHER| +// ID| +// INT | +// "target" | "var" | "probe" | "type" +//// "true" | +//// "false" | +//// "target" | "setup" | "models" | "analysis" | "managers" | "executors" | "effector-managers" | +//// "system" | "properties" | "var" | "import" | +// "." | +// "\\'" | +// '\\"' | +// "\\${" | +// "\\\\")+; + +terminal ID: + ('^')?('a'..'z' | 'A'..'Z') (('a'..'z' | 'A'..'Z') | '_' | '-' | '0'..'9')* +; + +terminal INT returns ecore::EInt: + ('0'..'9')+ +; + +//terminal STRING returns ecore::EString: +// '"' ( '\\' . /* 'b'|'t'|'n'|'f'|'r'|'u'|'"'|"'"|'\\' */ | !('\\'|'"') )* '"' | +// "'" ( '\\' . /* 'b'|'t'|'n'|'f'|'r'|'u'|'"'|"'"|'\\' */ | !('\\'|"'") )* "'" +//; + +// +//terminal RICH_TEXT : "'''" IN_RICH_STRING* ("'''"| ("'" "'"?)? EOF); +//terminal RICH_TEXT_START : "'''" IN_RICH_STRING* ("'" "'"?)? '«'; +//terminal RICH_TEXT_END : '»' IN_RICH_STRING* ("'''"| ("'" "'"?)? EOF) ; +//terminal RICH_TEXT_INBETWEEN : '»' IN_RICH_STRING* ("'" "'"?)? '«'; +//terminal COMMENT_RICH_TEXT_INBETWEEN: "««" !('\n'|'\r')* ('\r'? '\n' IN_RICH_STRING* ("'" "'"?)? '«')?; +//terminal COMMENT_RICH_TEXT_END: "««" !('\n'|'\r')* (('\r'? '\n' IN_RICH_STRING* ("'''"| ("'" "'"?)? EOF)) | EOF); +// +//terminal fragment IN_RICH_STRING : +// "''" !('«'|"'") +// | "'" !('«'|"'") +// | !('«'|"'"); + +//terminal RICH_TEXT_SQ returns ecore::EString: +// "'" IN_RICH_STRING_SQ* "'" +//; +// +//terminal RICH_TEXT_START_SQ: +// "'" IN_RICH_STRING_SQ* '«' +//; +// +//terminal RICH_TEXT_END_SQ: +// '»' IN_RICH_STRING_SQ* "'" +//; +// +//terminal RICH_TEXT_INBETWEEN_SQ: +// '»' IN_RICH_STRING_SQ* '«' +//; + +terminal RICH_TEXT_DQ returns ecore::EString: + '"' IN_RICH_STRING_DQ* '"' +; + +terminal RICH_TEXT_START_DQ: + '"' IN_RICH_STRING_DQ* '«' +; + +terminal RICH_TEXT_END_DQ: + '»' IN_RICH_STRING_DQ* '"' +; + +terminal RICH_TEXT_INBETWEEN_DQ: + '»' IN_RICH_STRING_DQ* '«' +; + + +//terminal RICH_TEXT : +// "'" IN_RICH_STRING_SQ* ("'"? EOF) | +// '"' IN_RICH_STRING_DQ* ('"'? EOF) +//; +// +//terminal RICH_TEXT_START: +// "'" IN_RICH_STRING_SQ* '«' | +// '"' IN_RICH_STRING_DQ* '«' +//; +// +//terminal RICH_TEXT_END: +// '»' IN_RICH_STRING_SQ* ("'")? EOF | +// '»' IN_RICH_STRING_DQ* ("'")? EOF +// ; +// +//terminal RICH_TEXT_INBETWEEN: +// +//; +//terminal RICH_TEXT_START : "'''" IN_RICH_STRING* ("'" "'"?)? '«'; +//terminal RICH_TEXT_END : '»' IN_RICH_STRING* ("'''"| ("'" "'"?)? EOF) ; +//terminal RICH_TEXT_INBETWEEN : '»' IN_RICH_STRING* ("'" "'"?)? '«'; +//terminal COMMENT_RICH_TEXT_INBETWEEN: "««" !('\n'|'\r')* ('\r'? '\n' IN_RICH_STRING* ("'" "'"?)? '«')?; +//terminal COMMENT_RICH_TEXT_END: "««" !('\n'|'\r')* (('\r'? '\n' IN_RICH_STRING* ("'''"| ("'" "'"?)? EOF)) | EOF); + +//terminal fragment IN_RICH_STRING_SQ : +// !('«'|"'"|"\n"|"\r"); + +terminal fragment IN_RICH_STRING_DQ: + !('«'|'"'|'»'|"\n"|"\r") +; + + + + +terminal ML_COMMENT: + '/*'->'*/'; + +terminal SL_COMMENT: + ('//' | '#') !('\n' | '\r')* ('\r'? '\n')?; + +terminal WS: + (' ' | '\t' | '\r' | '\n')+; + +terminal ANY_OTHER: + .; + + + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/CombinedScope.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/CombinedScope.xtend new file mode 100644 index 000000000..630560b84 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/CombinedScope.xtend @@ -0,0 +1,45 @@ +package org.sa.rainbow.configuration.scoping + +import org.eclipse.xtext.scoping.IScope +import org.eclipse.xtext.naming.QualifiedName +import org.eclipse.emf.ecore.EObject +import org.eclipse.xtext.resource.IEObjectDescription + +class CombinedScope implements IScope { + + IScope[] m_scopes + + new(IScope... scopes) { + m_scopes = scopes; + } + + override getAllElements() { + m_scopes.map[it.getAllElements()].flatten + } + + override getElements(QualifiedName name) { + m_scopes.map[it.getElements(name)].flatten + } + + override getElements(EObject object) { + m_scopes.map[it.getElements(object)].flatten + } + + override getSingleElement(QualifiedName name) { + var IEObjectDescription se = null; + for (var i = 0; i < m_scopes.length && se === null; i++) { + se = m_scopes.get(i).getSingleElement(name); + } + se + } + + override getSingleElement(EObject object) { + var IEObjectDescription se = null; + for (var i = 0; i < m_scopes.length && se === null; i++) { + se = m_scopes.get(i).getSingleElement(object); + } + se + } + +} + diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/QualifiedNameProvider.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/QualifiedNameProvider.java new file mode 100644 index 000000000..a8a14eb9b --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/QualifiedNameProvider.java @@ -0,0 +1,12 @@ +package org.sa.rainbow.configuration.scoping; + +import org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider; +import org.eclipse.xtext.naming.QualifiedName; + +public class QualifiedNameProvider extends DefaultDeclarativeQualifiedNameProvider { + @Override + protected QualifiedName qualifiedName(Object ele) { + // TODO Auto-generated method stub + return super.qualifiedName(ele); + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/RclGlobalScopeProvider.java b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/RclGlobalScopeProvider.java new file mode 100644 index 000000000..d2f729de2 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/RclGlobalScopeProvider.java @@ -0,0 +1,92 @@ +package org.sa.rainbow.configuration.scoping; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.impl.EReferenceImpl; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.xtext.EcoreUtil2; +import org.eclipse.xtext.common.types.TypesPackage; +import org.eclipse.xtext.common.types.xtext.AbstractTypeScopeProvider; +import org.eclipse.xtext.common.types.xtext.ClasspathBasedTypeScopeProvider; +import org.eclipse.xtext.common.types.xtext.TypesAwareDefaultGlobalScopeProvider; +import org.eclipse.xtext.resource.IEObjectDescription; +import org.eclipse.xtext.scoping.IScope; +import org.eclipse.xtext.scoping.impl.ImportUriGlobalScopeProvider; +import org.sa.rainbow.configuration.rcl.RclPackage; + +import com.google.common.base.Predicate; +import com.google.inject.Inject; +import com.google.inject.name.Named; + +/** + * A global scope provider that is both able to process the importURI attributes + * to establish cross links with other EMF models, and to handle references to + * JVM types. This class is a subclass of {@link ImportUriGlobalScopeProvider} + * in order to get the importURI behavior and delegates references to JVM types + * to an instance of AbstractTypeScopeProvider obtained through Guice. + * + * @see TypesAwareDefaultGlobalScopeProvider where part of is getScope() + * function is duplicated here. + * @see ClasspathBasedTypeScopeProvider + * @see org.eclipse.xtext.common.types.xtext.ui.JdtBasedSimpleTypeScopeProvider + * + */ +@SuppressWarnings("restriction") +public class RclGlobalScopeProvider extends ImportUriGlobalScopeProvider { + + + + + /* + * AbstractTypeScopeProvider is bound to + * org.eclipse.xtext.common.types.xtext.ClasspathBasedTypeScopeProvider in the + * "Standalone" setup and to + * org.eclipse.xtext.common.types.xtext.ui.JdtBasedSimpleTypeScopeProvider int + * the IU setup. In both cases, the class AbstractTypeScopeProvider which is the + * usual global scope provider when using the JVM types uses an + * AbstractTypeScopeProvider instance (through Guice) to handle all references + * to JVM types : we do the same here. + */ + @Inject + @Named("jvmtypes")private AbstractTypeScopeProvider typeScopeProvider; + + + @Override + public IScope getScope(Resource resource, EReference reference, Predicate filter) { + if (EcoreUtil2.isAssignableFrom(TypesPackage.Literals.JVM_TYPE, + reference.getEReferenceType()) /* + * || reference.equals(RclPackage.Literals.TYPE__REF) + */) { + IScope typeScope = typeScopeProvider.getScope(resource, reference, filter); + return typeScope; + } else if (reference.equals(RclPackage.Literals.TYPE__REF)) { + EReferenceImpl javaReference = (EReferenceImpl )EcoreUtil.copy(reference); + javaReference.setEType(TypesPackage.eINSTANCE.getJvmType()); + return new CombinedScope(super.getScope(resource, reference, filter), typeScopeProvider.getScope(resource, javaReference, filter)); + } + else { + return super.getScope(resource, reference, filter); + } + } + + + +} \ No newline at end of file diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/RclScopeProvider.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/RclScopeProvider.xtend new file mode 100644 index 000000000..089d3cbe2 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/scoping/RclScopeProvider.xtend @@ -0,0 +1,50 @@ +/* + * generated by Xtext 2.20.0 + */ +package org.sa.rainbow.configuration.scoping + +import org.acme.acme.AcmePackage +import org.eclipse.emf.ecore.EObject +import org.eclipse.emf.ecore.EReference +import org.eclipse.xtext.common.types.TypesPackage +import org.eclipse.xtext.scoping.IScope +import org.eclipse.xtext.scoping.impl.FilteringScope +import org.sa.rainbow.configuration.rcl.RclPackage +import org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider +import org.sa.rainbow.configuration.rcl.Type + +/** + * This class contains custom scoping description. + * + * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#scoping + * on how and when to use it. + */ +class RclScopeProvider extends AbstractDeclarativeScopeProvider { + override getScope(EObject context, EReference reference) { +// if (reference == RclPackage.Literals.REFERENCE__REFERABLE) { +// var ancestor = context; +// while (!(ancestor == null || ancestor instanceof PropertyContainer)) { +// ancestor = ancestor.eContainer(); +// } +// var pc = ancestor as PropertyContainer; +//// if (pc.name=="models") { +////// return getGlobalScope(context.eContainer(), reference); +//// +////// return Scopes.scopeFor(pc.eContainer().); +//// } +// } + + return super.getScope(context, reference); + } + +// def getGlobalScope(EObject context, EReference reference) { +// IScope globalScope = super.getGlobalScope(context, reference, null) +// } + + def IScope scope_EObject(Type context, EReference ref) { + return new FilteringScope(delegateGetScope(context, ref)) [ + return TypesPackage.Literals.JVM_TYPE.isSuperTypeOf(it.EClass) || + AcmePackage.Literals.ANY_TYPE_REF.isSuperTypeOf(it.EClass) + ] + } +} diff --git a/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/validation/RclValidator.xtend b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/validation/RclValidator.xtend new file mode 100644 index 000000000..08cc0a11e --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/org.sa.rainbow.configuration/src/org/sa/rainbow/configuration/validation/RclValidator.xtend @@ -0,0 +1,1380 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.configuration.validation + +/* + * Copyright 2020 Carnegie Mellon University + + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR + * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE + * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +import com.google.inject.Inject +import com.google.inject.name.Named +import java.util.HashSet +import java.util.LinkedList +import java.util.List +import java.util.Map +import java.util.Set +import java.util.regex.Pattern +import java.util.regex.PatternSyntaxException +import java.util.stream.Collectors +import org.eclipse.emf.common.util.EList +import org.eclipse.emf.ecore.EObject +import org.eclipse.emf.ecore.EReference +import org.eclipse.emf.ecore.EStructuralFeature +import org.eclipse.xtext.EcoreUtil2 +import org.eclipse.xtext.common.types.JvmDeclaredType +import org.eclipse.xtext.common.types.JvmOperation +import org.eclipse.xtext.common.types.JvmType +import org.eclipse.xtext.common.types.access.IJvmTypeProvider +import org.eclipse.xtext.common.types.util.Primitives +import org.eclipse.xtext.common.types.util.RawSuperTypes +import org.eclipse.xtext.util.Triple +import org.eclipse.xtext.util.Tuples +import org.eclipse.xtext.validation.Check +import org.eclipse.xtext.xbase.lib.Functions.Function1 +import org.sa.rainbow.configuration.ConfigAttributeConstants +import org.sa.rainbow.configuration.ModelUtil +import org.sa.rainbow.configuration.Utils +import org.sa.rainbow.configuration.XtendUtils +import org.sa.rainbow.configuration.rcl.Array +import org.sa.rainbow.configuration.rcl.Assignment +import org.sa.rainbow.configuration.rcl.BooleanLiteral +import org.sa.rainbow.configuration.rcl.CommandCall +import org.sa.rainbow.configuration.rcl.CommandDefinition +import org.sa.rainbow.configuration.rcl.CommandReference +import org.sa.rainbow.configuration.rcl.Component +import org.sa.rainbow.configuration.rcl.ComponentType +import org.sa.rainbow.configuration.rcl.DeclaredProperty +import org.sa.rainbow.configuration.rcl.DoubleLiteral +import org.sa.rainbow.configuration.rcl.Effector +import org.sa.rainbow.configuration.rcl.Factory +import org.sa.rainbow.configuration.rcl.FactoryDefinition +import org.sa.rainbow.configuration.rcl.Gauge +import org.sa.rainbow.configuration.rcl.GaugeBody +import org.sa.rainbow.configuration.rcl.GaugeTypeBody +import org.sa.rainbow.configuration.rcl.IPLiteral +import org.sa.rainbow.configuration.rcl.ImpactVector +import org.sa.rainbow.configuration.rcl.Import +import org.sa.rainbow.configuration.rcl.IntegerLiteral +import org.sa.rainbow.configuration.rcl.JavaClassOrFactory +import org.sa.rainbow.configuration.rcl.Probe +import org.sa.rainbow.configuration.rcl.PropertyReference +import org.sa.rainbow.configuration.rcl.RclPackage +import org.sa.rainbow.configuration.rcl.Reference +import org.sa.rainbow.configuration.rcl.StringLiteral +import org.sa.rainbow.configuration.rcl.Value +import org.sa.rainbow.core.models.IModelInstance +import org.sa.rainbow.core.models.commands.AbstractLoadModelCmd +import org.sa.rainbow.core.models.commands.AbstractRainbowModelOperation +import org.sa.rainbow.core.models.commands.AbstractSaveModelCmd +import org.sa.rainbow.core.models.commands.ModelCommandFactory + +/** + * This class contains custom validation rules. + * + * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#validation + */ +class RclValidator extends AbstractRclValidator { + + public static val ONLY_EXTEND_PROBE_TYPES_MSG = "A probe can only extend a probe type" + public static val ONLY_EXTEND_PROBE_TYPES = "invalidProbeType" + public static val ONLY_EXTEND_EFFECTOR_TYPES = "invalidEffectorType" + public static val MUST_SUBCLASS = "wrongtype" + public static val MISSING_PROPERTY = "missingRequiredProperty" + public static val COMMAND_NOT_IN_GAUGE_TYPE = "commandNotnGaugeSuperType" + public static val NOT_VALID_GAUGE_COMMAND = "gaugeCommandNotValid" + + + @Check + def checkOnlyProbeAsSupertype(Probe probe) { + var st = probe.superType + if (st !== null) { + if (!st.type) { + val v = probe.eResource.resourceSet.resources + val probeTypes = newHashSet + for (r : v) { + val res = r.allContents + res.forEach[ + if (it instanceof Probe && (it as Probe).type) { + probeTypes.add(it) + } + ] + } + error( + ONLY_EXTEND_PROBE_TYPES_MSG, + RclPackage.Literals.PROBE__SUPER_TYPE, + ONLY_EXTEND_PROBE_TYPES, + probeTypes.join(","), + "probe type" + ) + } + } + + } + + @Check + def checkProbeContainsRequiredAttributes(Probe probe) { + if (!probe.type) { + checkAttributes( + probe?.properties?.assignment, + probe.superType?.properties?.assignment, + ConfigAttributeConstants.ALL_OFREQUIRED_PROBE_FIELDS, + ConfigAttributeConstants.ONE_OFREQUIRED_PROBE_FIELDS, + RclPackage.Literals.PROBE__PROPERTIES + ); + } + for (Assignment a : probe.properties?.assignment) { + checkAssignmentType(a, ConfigAttributeConstants.PROBE_PROPERTY_TYPES, "") + + } + } + + def void checkAssignmentType(Assignment a, Map> types, String prefix) { + if (a.value?.value instanceof Component) { + for (ass : (a.value?.value as Component).assignment) { + checkAssignmentType(ass, types, a.name + ":") + } + } else { + checkTypeRule(types, a, prefix) + } + } + + @Check + def checkOnlyEffectorAsSupertype(Effector effector) { + var st = effector.superType + if (st !== null) { + if (!st.type) { + val v = effector.eResource.resourceSet.resources + val effectorTypes = newHashSet + for (r : v) { + val res = r.allContents + res.forEach[ + if (it instanceof Effector && (it as Effector).type) { + effectorTypes.add(it) + } + ] + } + error( + "An effector can only extend an effector type", + RclPackage.Literals.EFFECTOR__SUPER_TYPE, + ONLY_EXTEND_EFFECTOR_TYPES, + effectorTypes.join(","), + "effector type" + ) + } + } + } + + @Check + def checkEffectorContainsRequiredAttributes(Effector effector) { + if (!effector.type) { + checkAttributes( + effector?.body?.assignment, + effector?.superType?.body?.assignment, + ConfigAttributeConstants.ALL_OFREQUIRED_EFFECTOR_FIELDS, + ConfigAttributeConstants.ONE_OFREQUIRED_EFFECTOR_FIELDS, + RclPackage.Literals.EFFECTOR__BODY + ) + } + for (Assignment a : effector.body?.assignment) { + checkAssignmentType(a, ConfigAttributeConstants.EFFECTOR_PROPERTY_TYPES, "") + + } + } + + @Check + def checkGaugeContainsRequiredAttributes(Gauge gauge) { + checkAttributes( + gauge?.body?.assignment, + gauge?.superType?.body?.assignment, + ConfigAttributeConstants.ALL_OFREQUIRED_GAUGE_FIELDS, + ConfigAttributeConstants.OPTIONAL_GUAGE_FIELDS, + RclPackage.Literals.GAUGE__BODY + ) + checkSubAttributes( + gauge?.body?.assignment, + gauge?.superType?.body?.assignment, + ConfigAttributeConstants.ALL_OFREQUIRED_GAUGE_SUBFILEDS, + ConfigAttributeConstants.ONE_OFREQUIRED_GAUGE_SUBFILEDS, + RclPackage.Literals.GAUGE__BODY + ) + for (Assignment a : gauge.body?.assignment) { + checkAssignmentType(a, ConfigAttributeConstants.GAUGE_PROPERTY_TYPES, "") + + } + if (gauge.superType !== null) { + val setupT = gauge.superType.body.assignment.findFirst[it.name == 'setup']?.value?.value + val setupI = gauge.body.assignment.findFirst[it.name == 'setup']?.value?.value + if (setupT instanceof Component && setupI instanceof Component) { + val setupsInType = (setupT as Component).assignment.filter[!ConfigAttributeConstants.ALL_OFREQUIRED_GAUGE_SUBFILEDS?.get('setup')?.contains(it.name)].filter[!ConfigAttributeConstants.ONE_OFREQUIRED_GAUGE_SUBFILEDS?.get('setup')?.contains(it.name)] + val setupsInInstance = (setupI as Component).assignment.filter[!ConfigAttributeConstants.ALL_OFREQUIRED_GAUGE_SUBFILEDS?.get('setup')?.contains(it.name)].filter[!ConfigAttributeConstants.ONE_OFREQUIRED_GAUGE_SUBFILEDS?.get('setup')?.contains(it.name)] + val setup = gauge.body.assignment.findFirst[it.name == 'setup'] + val noSetupDefaults = setupsInType.filter[it?.value?.value instanceof Reference] + checkWithGaugeType(setupsInType, setupsInInstance, gauge, noSetupDefaults, setup) + } + + val configT = gauge.superType.body.assignment.findFirst[it.name == 'config']?.value?.value + val configI = gauge.body.assignment.findFirst[it.name == 'config']?.value?.value + if (configT instanceof Component && configI instanceof Component) { + var configInType = (configT as Component).assignment.filter[ + !ConfigAttributeConstants.ALL_OFREQUIRED_GAUGE_SUBFILEDS?.get('config')?.contains(it.name) + ] + configInType = configInType.filter[ + !ConfigAttributeConstants.ONE_OFREQUIRED_GAUGE_SUBFILEDS?.get('config')?.contains(it.name) + ] + val configInInstance = (configI as Component).assignment.filter[!ConfigAttributeConstants.ALL_OFREQUIRED_GAUGE_SUBFILEDS?.get('config')?.contains(it.name)].filter[!ConfigAttributeConstants.ONE_OFREQUIRED_GAUGE_SUBFILEDS?.get('config')?.contains(it.name)] + checkWithGaugeType(configInType, configInInstance,gauge, configInType.filter[it?.value?.value instanceof Reference], gauge.body.assignment.findFirst[it.name == 'config']) + + } + } + } + + protected def void checkWithGaugeType(Iterable setupsInType, Iterable setupsInInstance, Gauge gauge, Iterable noSetupDefaults, Assignment setup) { + val TypeSetupNames = newLinkedList + TypeSetupNames.addAll(setupsInType.map[it.name]) + for (p : setupsInInstance) { + if (!TypeSetupNames.contains(p.name)) { + warning('''Property «p.name» is not defined in type «gauge.superType.name»''', p, + RclPackage.Literals.ASSIGNMENT__NAME + ) + } + val pIntype = setupsInType.findFirst[it.name==p.name]?.value?.value + var typechecks = false + if (pIntype instanceof Reference) { + val type = (pIntype as Reference).referable + typechecks = switch type.qualifiedName { + case typeof(Integer).name : p?.value?.value instanceof IntegerLiteral + case typeof(String).name: p?.value?.value instanceof StringLiteral + case typeof(Boolean).name: p?.value?.value instanceof BooleanLiteral + case typeof(Double).name: p?.value?.value instanceof IntegerLiteral || p?.value?.value instanceof DoubleLiteral + default: false + } + } + else if (pIntype instanceof DoubleLiteral) { + typechecks = p?.value?.value instanceof DoubleLiteral || p?.value?.value instanceof IntegerLiteral + } + else { + typechecks = p?.value?.value?.class == pIntype?.class + } + if (!typechecks) { + + error('''The type of «p.name» does not match in the gauge type''', p, + RclPackage.Literals.ASSIGNMENT__NAME + ) + } + TypeSetupNames.remove(p.name) + } + + if (!TypeSetupNames.empty && !noSetupDefaults.empty) { + val badNames = noSetupDefaults.filter[TypeSetupNames.contains(it.name)].map[it.name] + error('''The «(badNames.length > 1)?"properties":"property"» «badNames.join(", ")» need(s) to be given a value in this instance''', setup, RclPackage.Literals.ASSIGNMENT__VALUE, MISSING_PROPERTY, badNames.join(",")) + } + } + +// @Check +// def checkProbeValue(ProbeReference v) { +// var p = v.eContainer +// while (p != null && !(p.eContainer instanceof Probe)) +// p = p.eContainer +// if (p != null) { +// error( +// "A probe cannot refer to another probe", +// RclPackage.Literals.PROBE_REFERENCE__REFERABLE, +// "noProbeReferencesInProbe" +// ) +// } +// } + @Check + def checkUtilityAssignment(Assignment ass) { + val dp = EcoreUtil2.getContainerOfType(ass, DeclaredProperty) + if (dp !== null && dp.component === ComponentType.UTILITY) { + val sb = new StringBuffer() + var eContainer = ass as EObject + while (eContainer !== null) { + eContainer = eContainer.eContainer + if (eContainer instanceof Assignment) { + sb.insert(0, ':') + val par = (eContainer as Assignment) + if (ConfigAttributeConstants.UTILITY_PROPERTY_TYPES.containsKey(par.name)) { + sb.insert(0, par.name) + } + } + } + checkTypeRule(ConfigAttributeConstants.UTILITY_PROPERTY_TYPES, ass, sb.toString) + } + } + + @Check + def checkAttributes(EList list, EList superlist, Set requiredfields, + Set optionalFields, EReference reference) { + for (String req : requiredfields) { + var hasReq = list.exists [ + it.name == req + ]; + if (!hasReq && superlist !== null) { + hasReq = superlist.exists [ + return it.name == req + ]; + } + if (!hasReq) { + warning( + '''Expecting required field "«req»"''', + reference, + MISSING_PROPERTY, + req + ) + } + } + if (!optionalFields.isEmpty) { + var hasOpt = false; + for (String opt : optionalFields) { + hasOpt = hasOpt || list.exists[return it.name == opt] + if (superlist != null) { + hasOpt = hasOpt || superlist.exists[return it.name == opt] + } + } + if (!hasOpt) { + var fields = optionalFields.map([return "\"" + it + "\""]).join(", ") + warning( + '''Expecting one of field «fields»''', + reference, + MISSING_PROPERTY, + optionalFields.map[it].join(",") + ) + } + } + + } + + def checkSubAttributes(EList list, EList superlist, Map> allOfSubfields, + Map> oneOfSubfields, EReference reference) { + for (String key : allOfSubfields.keySet) { + val compoundElement = list.findFirst [ + it.name == key && it?.value !== null && it.value.value instanceof Component + ] + var hasCompoundReq = compoundElement !== null + if (!hasCompoundReq && superlist !== null) { + hasCompoundReq = superlist.exists [ + it.name == key && it?.value !== null && it.value.value instanceof Component + ] + } + if (!hasCompoundReq) { + warning( + '''Expecting required compound attribute "«key»"''', + reference, + MISSING_PROPERTY, + key, + Component.name + ) + } else { + val att = list != null ? list.stream.filter([it.name == key]).findAny : null + val superAtt = superlist != null ? superlist.stream.filter([it.name == key]).findAny : null + val allKeys = new HashSet() + if (att !== null && att.present) { + allKeys.addAll((att.get.value.value as Component).assignment.map([it.name])) + } + if (superAtt !== null && superAtt.present) { + allKeys.addAll((superAtt.get.value.value as Component).assignment.map[it.name]) + } + if (!allKeys.containsAll(allOfSubfields.get(key))) { + var fields = allOfSubfields.get(key).stream.filter([!allKeys.contains(it)]).collect( + Collectors.toList) + var fs = fields.map([return "\"" + it + "\""]).join(", ") + if (compoundElement != null) { + warning( + '''"«key»" is missing the required fields «fs».''', + compoundElement, + RclPackage.Literals.ASSIGNMENT__VALUE, + MISSING_PROPERTY, + fields.map[it].join(",") + ) + } else { + warning( + '''"«key»" is missing the required fields «fs».''', + reference, + MISSING_PROPERTY, + fields.map[it].join(","), + key + ) + } + } + val oneof = oneOfSubfields.get(key) + if (oneof !== null) { + var hasOneOf = false + for (sk : oneof) { + hasOneOf = hasOneOf || allKeys.contains(sk) + } + if (!hasOneOf) { + warning( + '''"«key»" should have one of «oneof.map["'" + key + "'"].join(", ")».''', + reference, + MISSING_PROPERTY, + oneof.map[it].join(","), + key + ) + } + } + } + } + + } + + @Inject + @Named("jvmtypes") private IJvmTypeProvider.Factory jvmTypeProviderFactory; + + @Inject + private RawSuperTypes superTypeCollector; + + @Check + def checkGaugeTypeModelFactory(GaugeTypeBody gaugeType) { + var model = gaugeType.mcf + if (model instanceof Reference) { + if (model.referable instanceof JvmType) { + var java = model.referable as JvmType + var jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(gaugeType.eResource.resourceSet); + + var I2I = jvmTypeProvider.findTypeByName(MODEL_COMMAND_FACTORY_SUPERCLASS); + var sts = superTypeCollector.collect(java); + if (!sts.contains(I2I)) { + error( + '''«java.identifier» does not extend «MODEL_COMMAND_FACTORY_SUPERCLASS»''', + RclPackage.Literals.GAUGE_TYPE_BODY__MCF, + RclValidator.MUST_SUBCLASS, + MODEL_COMMAND_FACTORY_SUPERCLASS, + sts.map[it.qualifiedName].join(","), + "factory type" + ) + } + } + + } + } + + @Check + def checkGaugeBody(GaugeTypeBody gb) { + var Boolean hasRegExpCommand = null; + for (cmd : gb.commands) { + if (hasRegExpCommand === null) { + hasRegExpCommand = cmd.regexp !== null + } else { + if (hasRegExpCommand && (cmd.regexp === null)) { + error( + '''Mixing commands with and without regular expression is not supported.''', + cmd, + RclPackage.Literals.COMMAND_REFERENCE__NAME, + "mixedcommands" + ) + } + } + } + if (hasRegExpCommand != null && hasRegExpCommand) { + var noGeneratedClass = true + var additional = "" + val setupProp = gb.assignment.findFirst[it.name == "setup"] + val setup = setupProp?.value.value + if (setup instanceof Component) { + val gcProp = (setup as Component).assignment.findFirst[it.name == "generatedClass"] + if (gcProp == null) { + val javaClass = (setup as Component).assignment.findFirst[it.name == "javaClass"] + if (javaClass !== null) { + additional = " Perhaps change javaClass to generatedClass?" +// error("Gauges with regular expressions should have generatedClass", +// javaClass, +// RclPackage.Literals.ASSIGNMENT, +// "noGeneratedClass", +// "generatedClass" +// +// ) + } +// else { + error( + '''Gauge has regular expression, so "generatedClass" should be specified.''', + setupProp, + RclPackage.Literals.ASSIGNMENT__VALUE, + MISSING_PROPERTY, + "generatedClass" + ) +// } + } else { + val gc = gcProp?.value?.value + if (gc instanceof StringLiteral) { + noGeneratedClass = false; + try { + val className = XtendUtils.unpackString(gc as StringLiteral, true, true) + val clazz = Class.forName(className) + warning( + '''"«className»" already exists''', + gcProp, + RclPackage.Literals.ASSIGNMENT__VALUE, + "badclass" + ) + } catch (Exception e) { + } + } else { + error( + '''Value should be a string''', + gcProp, + RclPackage.Literals.ASSIGNMENT__VALUE, + "badclass" + ) + } + } + } else { + error( + '''Gauge has regular expression, so "generatedClass" should be specified in setup''', + setup, + RclPackage.Literals.ASSIGNMENT__VALUE, + MISSING_PROPERTY, + "generatedClass" + ) + } + } + for (Assignment a : gb.assignment) { + checkAssignmentType(a, ConfigAttributeConstants.GAUGE_PROPERTY_TYPES, "") + + } + + } + + @Check + def checkCommandCall(CommandCall cc) { + val gb = EcoreUtil2.getContainerOfType(cc, GaugeBody) + if (gb !== null) { + val g = EcoreUtil2.getContainerOfType(gb, Gauge) + var Object modelFactory = null + if (gb.ref?.referable instanceof DeclaredProperty && + (gb.ref?.referable as DeclaredProperty)?.component == ComponentType.MODEL && + (gb.ref?.referable as DeclaredProperty)?.value.value instanceof Component) { + modelFactory = ((gb.ref.referable as DeclaredProperty).value.value as Component).assignment.findFirst [ + it.name == "factory" + ] +// if (factory ) +// if (factory?.value?.value instanceof Reference && (factory.value.value as Reference).referable instanceof JvmDeclaredType) { +// modelFactory = (factory.value.value as Reference).referable as JvmDeclaredType +// } + } else { + if (g.superType !== null) { + modelFactory = g.superType.body.mcf +// if (g.superType.body.mcf.java.refera instanceof JvmDeclaredType) +// modelFactory = g.superType.body.mcf as JvmDeclaredType + } + } + if (modelFactory === null) { + warning( + '''Cannot check "«cc.command»" because no referenced model''', + RclPackage.Literals.COMMAND_CALL__COMMAND, + "cannotCheckCommand" + ) + } + if (g.superType !== null) { + if (g.superType.body.commands.findFirst [ + it.name == cc.name + ] === null) { + val commandNamesInGauge = g.body.commands.map[it.name] + val possibleRenamesInGauge = g.superType.body.commands.map[it.name].filter[!commandNamesInGauge.contains(it)].join(",") + error( + '''The command "«cc.name»" does not exists in «g.superType.name»''', + RclPackage.Literals.COMMAND_CALL__NAME, + RclValidator.COMMAND_NOT_IN_GAUGE_TYPE, + possibleRenamesInGauge + ) + } + } + checkCommandCallElements(cc, modelFactory) + return + + } + val ef = EcoreUtil2.getContainerOfType(cc, Effector) + if (ef !== null) { + var Object modelFactory = null + if (ef.body?.ref?.referable instanceof DeclaredProperty && + (ef.body?.ref?.referable as DeclaredProperty)?.component == ComponentType.MODEL && + (ef.body?.ref?.referable as DeclaredProperty)?.value.value instanceof Component) { + val factory = ((ef.body?.ref.referable as DeclaredProperty).value.value as Component).assignment. + findFirst[it.name == "factory"] +// if (factory?.value?.value instanceof Reference) { +// modelFactory = (factory.value.value as Reference).referable as JvmDeclaredType +// } +// else if (factory instanceof Assignment && factory?.value?.value instanceof PropertyReference) { +// modelFactory = (factory?.value?.value as PropertyReference).referable +// if (modelFactory instanceof DeclaredProperty && (factory as +// } + modelFactory = factory + } + + if (modelFactory === null) { + warning( + '''Cannot check "«cc.command»" because no referenced model''', + RclPackage.Literals.COMMAND_CALL__COMMAND, + "cannotCheckCommand" + ) + } + checkCommandCallElements(cc, modelFactory) + return + } + } + + @Check + def checkGaugeTypeCommandReferenceRegexp(CommandReference cr) { + if (cr.regexp !== null) { + val regexp = XtendUtils.unpackString(cr.regexp, true, true) + val Set namedGroups = newHashSet + + try { + Pattern.compile(regexp) + XtendUtils.fillNamedGroups(regexp, namedGroups) + if (namedGroups.empty) { + warning( + '''""«regexp»" should contain at least one captured group''', + RclPackage.Literals.COMMAND_REFERENCE__REGEXP, + "badregexp" + ) + } + } catch (PatternSyntaxException e) { + error( + '''«e.message»''', + RclPackage.Literals.COMMAND_REFERENCE__REGEXP, + "badregexp" + ) + } + } + } + + @Check + def checkGaugeCommands(Gauge g) { + if (g.superType !== null) { + val typeCommands = g.superType.body.commands + for (cmd : g.body.commands) { + val tcmd = typeCommands.findFirst[it.name == cmd.name] + if (tcmd?.regexp !== null) { + val Set namedGroups = newHashSet + val regexp = XtendUtils.unpackString(tcmd.regexp, true) + XtendUtils.fillNamedGroups(regexp, namedGroups) + } + } + } + } + + def hasTarget(CommandCall cc) { + cc.ref !== null || cc.target !== null + } + + def checkCommandCallElements(CommandCall cc, Object modelFactory) { + var Object cmf = null + if (modelFactory instanceof Assignment) { + cmf = (modelFactory as Assignment).value.value + } else if (modelFactory instanceof JavaClassOrFactory) { + val jcof = (modelFactory as JavaClassOrFactory) + if(jcof.java !== null) cmf = jcof.java else cmf = jcof.factory + } + val command = cc.command + val Set namedGroups = newHashSet + + val re = EcoreUtil2.getContainerOfType(cc, Gauge)?.superType?.body?.commands?.findFirst[it.name == cc.name]?. + regexp + if (re !== null) { + val regexp = XtendUtils.unpackString(re, true, true) + + try { + XtendUtils.fillNamedGroups(regexp, namedGroups) + } catch (PatternSyntaxException e) { + // Handled in checkGaugeType + } + } + + switch cmf { + Reference case cmf.referable instanceof JvmDeclaredType: + checkCommandCallElements(cc, command, cmf.referable as JvmDeclaredType) + PropertyReference case cmf.referable instanceof Factory: { + + val factory = cmf.referable as Factory + val mf = factory.defn + var commandMethod = mf.commands.filter[it.name.equalsIgnoreCase(command)] + + if (commandMethod.empty) { + val validCommands = new LinkedList(); + val gauge = EcoreUtil2.getContainerOfType(cc, Gauge) + if (gauge !== null) { + val superTypeCmd =gauge?.superType?.body?.commands?.findFirst[it.name.equalsIgnoreCase(cc.name)] + if (superTypeCmd !== null) { + validCommands.add(superTypeCmd.command) + } + else { + validCommands.addAll(mf.commands.filter[it.formal.length == cc.actual.length].map[it.name]) + } + } + error( + '''"«command»" is not a valid command in «(cmf as PropertyReference).referable.name» ''', + RclPackage.Literals.COMMAND_CALL__COMMAND, + NOT_VALID_GAUGE_COMMAND, + validCommands.join(",") + ) + } else { + val factoryCommand = commandMethod.get(0) + if (factoryCommand.formal.size != cc.actual.size + (cc.hasTarget ? 1 : 0)) { + if (cc.actual === null && factoryCommand.formal.size > 0) { + } else { + error( + '''"«command»" wrong number of parameters defined. Expecting «factoryCommand.formal.size-(cc.hasTarget?1:0)» got «cc.actual.size»''', + RclPackage.Literals.COMMAND_CALL__ACTUAL, + "wrongparamnumbers" + ) + + } + } else { + for (actual : cc.actual) { + if (actual.ref && re !== null) { + var name = actual.ng + var lit = RclPackage.Literals.ACTUAL__NG + if (name === null) { + name = Integer.toString(actual.ag) + lit = RclPackage.Literals.ACTUAL__AG + } + if (!namedGroups.contains(name)) { + warning( + '''«name» should be a valid group from «XtendUtils.unpackString(re, true)»''', + actual, + lit, + "badregexpreference" + ) + } + } + } + } +// else { +// var i = 0 +// for (param : factoryCommand.formal) { +// if (param.name != "target") { +// val paramTypeName = getTypeName(param) +// if (paramTypeName != cc.actual.get(i).) { +// error( +// '''Parameter «i» expecting «paramTypeName», received «cr.formal.get(i).simpleName».''', +// RclPackage.Literals.COMMAND_REFERENCE__FORMAL, +// "wrongType" +// ) +// } +// i = i + 1 +// } +// else { +// val paramTypeName = getTypeName(param) +// if (paramTypeName != cr.target) { +// error( +// '''Target type expecting «paramTypeName», received «cr.target».''', +// RclPackage.Literals.COMMAND_REFERENCE__TARGET, +// "wrongType" +// ) +// } +// } +// } +// } + } + } + } + } + + protected def checkCommandCallElements(CommandCall cc, String command, JvmDeclaredType mf) { + var commandMethod = mf.members.filter[it instanceof JvmOperation].filter [ + it.simpleName.equalsIgnoreCase(command) || it.simpleName.equalsIgnoreCase(command + "cmd") + ] + + if (commandMethod.empty) { + error( + '''"«command»" is not a valid command in «mf.identifier» ''', + RclPackage.Literals.COMMAND_CALL__COMMAND, + "nocommand" + ) + } else { + var method = commandMethod.get(0) as JvmOperation + if (method.parameters.size != cc.actual.size + (cc.hasTarget ? 1 : 0)) { + if (cc.actual == null && method.parameters.size > 0) { + } else { + error( + '''"«command»" wrong number of parameters defined. Expecting «method.parameters.size-(cc.hasTarget?1:0)» got «cc.actual.size»''', + RclPackage.Literals.COMMAND_CALL__ACTUAL, + "wrongparamnumbers" + ) + + } + } + } + } + + @Check + def checkCommandSignature(CommandReference cr) { + if (cr.eContainer.eClass == RclPackage.Literals.GAUGE_TYPE_BODY) { + var gaugeType = cr.eContainer as GaugeTypeBody + if (gaugeType !== null) { + if (gaugeType.mcf !== null) { + val mcf = gaugeType.mcf + if (mcf instanceof Reference && + !((mcf as Reference).referable instanceof JvmDeclaredType || + (mcf as Reference).referable instanceof Factory)) { + warning( + '''"«cr.command» cannot be checked because there is no model defined"''', + RclPackage.Literals.COMMAND_REFERENCE__COMMAND, + "cannotCheckCommand" + ) + return + } + } + } + val command = cr.command + + val java = gaugeType.mcf instanceof Reference && (gaugeType.mcf as Reference).referable instanceof JvmDeclaredType ? (gaugeType.mcf as Reference). + referable as JvmDeclaredType : null + val factory = gaugeType.mcf instanceof PropertyReference && (gaugeType.mcf as PropertyReference).referable instanceof Factory ? (gaugeType.mcf as PropertyReference).referable as Factory : null + + if (java !== null) { + var type = java + + var commandMethod = type.members.filter[it instanceof JvmOperation].filter [ + it.simpleName.equalsIgnoreCase(command) || it.simpleName.equalsIgnoreCase(command + "cmd") + ] + + if (commandMethod.empty) { + error( + '''"«command»" is not a valid command in «type.identifier» ''', + RclPackage.Literals.COMMAND_REFERENCE__COMMAND, + "nocommand" + ) + } else { + var method = commandMethod.get(0) as JvmOperation + if (method.parameters.size != cr.formal.size + (cr.target != null ? 1 : 0)) { + if (cr.formal == null && method.parameters.size > 0) { + } else { + error( + '''"«cr.command»" wrong number of parameters defined. Expecting «method.parameters.size-(cr.target!=null?1:0)» got «cr.formal.size»''', + RclPackage.Literals.COMMAND_REFERENCE__FORMAL, + "wrongparamnumbers" + ) + return + } + } + var first = true + val prim = new Primitives() + var i = 0 + for (param : method.parameters) { + if (first && cr.target != null) { + if (prim.isPrimitive(param.parameterType)) { + warning( + '''«type.simpleName».«method.simpleName» may need a target''', + RclPackage.Literals.COMMAND_REFERENCE__COMMAND, + "mayNeedTarget" + ) + } + } else { + if (param.parameterType.simpleName != cr.formal.get(i).simpleName) { + error( + '''Parameter «i» expecing «param.parameterType.simpleName», received «cr.formal.get(i).simpleName».''', + RclPackage.Literals.COMMAND_REFERENCE__FORMAL, + "wrongType" + ) + } + i = i + 1 + } + first = false + } + } + + } else if (factory != null) { + + val factoryCommands = factory.defn.commands.filter[it.name.equalsIgnoreCase(command)] + if (factoryCommands.empty) { + error( + '''"«command»" is not a valid command in «factory.name» ''', + RclPackage.Literals.COMMAND_REFERENCE__COMMAND, + "nocommand" + ) + } else { + val factoryCommand = factoryCommands.get(0) + if (factoryCommand.formal.size != cr.formal.size + (cr.target != null ? 1 : 0)) { + if (cr.formal == null && factoryCommand.formal.size > 0) { + return + } else { + error( + '''"«cr.command»" wrong number of parameters defined. Expecting «factoryCommand.formal.size-(cr.target!=null?1:0)» got «cr.formal.size»''', + RclPackage.Literals.COMMAND_REFERENCE__FORMAL, + "wrongparamnumbers" + ) + return + } + } + // Check the targets + if (factoryCommand.formal.findFirst[it.name == "target"] !== null && cr.target === null) { + error( + '''"«cr.command»" does not specify a needed target''', + RclPackage.Literals.COMMAND_REFERENCE__FORMAL, + "wrongparamnumbers" + ) + return + } + if (cr.target !== null && factoryCommand.formal.findFirst[it.name == "target"] === null) { + error( + '''«cr.command» specifies a target not in the factory: «cr.target»''', + RclPackage.Literals.COMMAND_REFERENCE__TARGET, + "unknowntarget" + ) + } + var i = 0 + for (param : factoryCommand.formal) { + if (param.name != "target") { + val paramTypeName = ModelUtil.getTypeName(param) + if (paramTypeName != cr.formal.get(i).simpleName) { + error( + '''Parameter «i» expecting «paramTypeName», received «cr.formal.get(i).simpleName».''', + RclPackage.Literals.COMMAND_REFERENCE__FORMAL, + "wrongType" + ) + } + i = i + 1 + } else { + val paramTypeName = ModelUtil.getTypeName(param) + if (paramTypeName != cr.target) { + error( + '''Target type expecting «paramTypeName», received «cr.target».''', + RclPackage.Literals.COMMAND_REFERENCE__TARGET, + "wrongType" + ) + } + } + } + } + } +// var tries=[cr.command, cr.command.toLowerCase, cr.commmand] +// while (method == null) + } + } + + + + @Check + def checkClassAssignments(DeclaredProperty assignment) { + if (assignment?.value?.value instanceof Reference) { + val subType = (assignment.value.value as Reference).referable + if (assignment.name.matches(".*class_[0-9]+$")) { + val checkName = assignment.name.substring(0, assignment.name.lastIndexOf('_')) + "*" + val superClass = ConfigAttributeConstants.PROPERTY_VALUE_CLASSES.get(checkName) + if (superClass !== null) { + val jvmTypeProvider = jvmTypeProviderFactory.createTypeProvider(assignment.eResource.resourceSet) + val superType = jvmTypeProvider.findTypeByName(superClass) + var sts = superTypeCollector.collect(subType) + if (!sts.contains(superType)) { + error( + '''«subType.simpleName» is not a subclass of «superClass»''', + RclPackage.Literals.DECLARED_PROPERTY__VALUE, + RclValidator.MUST_SUBCLASS, + superClass + ) + } + } + } + } + + checkTypeRule(ConfigAttributeConstants.PROPERTY_VALUE_TYPES, "", assignment.name, assignment.value, assignment, RclPackage.Literals.DECLARED_PROPERTY__VALUE) + + } + + @Check + def checkComponentPropertiesAreComponent(DeclaredProperty dp) { + if (dp.component != ComponentType.PROPERTY) { + if (!(dp.value.value instanceof Component)) { + error( + '''Values for «dp.component» must be compound values''', + RclPackage.Literals.DECLARED_PROPERTY__VALUE, + "incorrectValue" + ) + } + } + } + + @Check + def checkComponentPropertyFields(DeclaredProperty dp) { + if (dp.component != ComponentType.PROPERTY) { + switch dp.component { + case ANALYSIS: { + checkAttributes((dp.value.value as Component).assignment, null, + ConfigAttributeConstants.ALL_OFREQUIRED_ANALYSIS_FIELDS, #{}, + RclPackage.Literals.DECLARED_PROPERTY__VALUE) + + } + case EFFECTORMANAGER: { + checkAttributes((dp.value.value as Component).assignment, null, + ConfigAttributeConstants.ALL_OFREQUIRED_EFFECTOR_MANAGER_FIELDS, #{}, + RclPackage.Literals.DECLARED_PROPERTY__VALUE) + + } + case EXECUTOR: { + checkAttributes((dp.value.value as Component).assignment, null, + ConfigAttributeConstants.ALL_OFREQUIRED_EXECUTOR_FIELDS, #{}, + RclPackage.Literals.DECLARED_PROPERTY__VALUE) + } + case GUI: { + } + case MANAGER: { + checkAttributes((dp.value.value as Component).assignment, null, + ConfigAttributeConstants.ALL_OFREQUIRED_MANANGER_FIELDS, #{}, + RclPackage.Literals.DECLARED_PROPERTY__VALUE) + + } + case MODEL: { + checkAttributes((dp.value.value as Component).assignment, null, + ConfigAttributeConstants.ALL_OFREQUIRED_MODEL_FIELDS, #{}, + RclPackage.Literals.DECLARED_PROPERTY__VALUE) + } + case PROPERTY: { + } + case UTILITY: { + checkAttributes((dp.value.value as Component).assignment, null, + ConfigAttributeConstants.ALL_OFREQUIRED_UTILITY_FIELDS, #{}, + RclPackage.Literals.DECLARED_PROPERTY__VALUE) + } + } + } + } + + @Check + def checkComponentPropertyFieldTypes(Assignment dp) { + val parent = EcoreUtil2.getContainerOfType(dp, DeclaredProperty) + if (parent?.component !== null && parent?.component == ComponentType.GUI) { + var rent = EcoreUtil2.getContainerOfType(dp.eContainer, Assignment); + var name = "" + while (rent !== null) { + name = rent.name + ":" + name + rent = EcoreUtil2.getContainerOfType(rent.eContainer, Assignment); + } + checkTypeRule(ConfigAttributeConstants.GUI_PROPERTY_TUPES, dp, name) + } else if (parent?.component !== null && parent?.component != ComponentType.PROPERTY) { + val rule = ConfigAttributeConstants.COMPONENT_PROPERTY_TYPES.get(parent.component) + checkTypeRule(rule, dp) + } + } + + def void checkTypeRule(Map> rule, Assignment dp) { + checkTypeRule(rule, "", dp.name, dp.value, dp, RclPackage.Literals.ASSIGNMENT__VALUE) + } + + protected def void checkTypeRule(Map> rule, Assignment dp, String prefix) { + checkTypeRule(rule, prefix, dp.name, dp.value, dp, RclPackage.Literals.ASSIGNMENT__VALUE) + } + + protected def void checkTypeRule(Map> rule, String prefix, String name, Value value, EObject target, EStructuralFeature feature) { + if (rule !== null) { + val lookupName = prefix == "" ? name : (prefix + name) + val fieldRule = rule.get(lookupName) as Map + if (fieldRule !== null) { + val (Value)=>boolean func = fieldRule.get('func') as (Value)=>boolean + if (func !== null) { + if (!func.apply(value)) { + error( + '''«name» «fieldRule.get('msg')»''', + target, + feature, + "invalidType" + ) + } + } else { + var extends = fieldRule.get('extends') as List + var ok = false + for (class : extends) { + ok = ok || checkClass(value, class) + } + if (!ok) { + error( + '''«name» «fieldRule.get('msg')»''', + target, + feature, + MUST_SUBCLASS, + extends.map[it.name].join(",") + ) + } + if (extends.contains(Array) && value.value instanceof Array) { + val furtherCheck = fieldRule.get( + 'checkEach') as Function1>> + for (e : furtherCheck.apply(value.value as Array)) { + error(e.first, e.second, e.third) + } + } + } + + } + + } + } + + protected def boolean checkClass(Value dp, Class clazz) { + if(clazz == StringLiteral) return dp.value instanceof StringLiteral + if(clazz == BooleanLiteral) return dp.value instanceof BooleanLiteral + if(clazz == IntegerLiteral) return dp.value instanceof IntegerLiteral + if(clazz == DoubleLiteral) return dp.value instanceof DoubleLiteral + if(clazz == Component) return dp.value instanceof Component + if(clazz == IPLiteral) return dp.value instanceof IPLiteral + if(clazz == PropertyReference) return dp.value instanceof PropertyReference +// if(clazz == ProbeReference) return dp.value.value instanceof ProbeReference + if(clazz == Array) return dp.value instanceof Array + ConfigAttributeConstants.subclasses(dp, clazz.name) + } + + public static val CHECK_UTILITY_MONOTONIC = [ Array a | + { + val errors = new LinkedList>() + var first = true + var double lastVal = 0.0 + var goingUp = false + var goingDown = false + for (v : a.values) { + if (!(v.value instanceof Array)) { + errors.add( + Tuples.create('''Array value needs to be an array of two numbers''', v, + RclPackage.Literals.VALUE__VALUE)) + } else { + val pair = v.value as Array + if (pair.values.size != 2) { + errors.add( + Tuples.create('''Array value needs to be an array of two numbers''', v, + RclPackage.Literals.VALUE__VALUE)) + } else { + val thisVal = getNumber(pair.values.get(1)) + if (!first) { + if (lastVal < thisVal) { + goingUp = true + } else if (lastVal > thisVal) { + goingDown = true + } + } else { + first = false + } + lastVal = thisVal + } + + } + } + if (goingUp && goingDown) { + errors.add(Tuples.create('''Utilities need to be monotonic''', a, RclPackage.Literals.ARRAY__VALUES)) + } + errors + + } + ] + + public static val CHECK_EACH_SCENARIO = [ Array a | + { + val errors = new LinkedList>() + val dp = Utils.getContainerOfType(a, Component, [ EObject v | + v instanceof Component && (v as Component).assignment.exists[it.name == "utilities"] + ]) + var definedUtilities = (dp.assignment.findFirst[it.name == "utilities"]?.value.value as Component). + assignment.map[it.name] + for (v : a.values) { + if (!(v.value instanceof Component)) { + errors.add( + Tuples.create('''Scenario should only contain composites''', a, + RclPackage.Literals.ARRAY__VALUES)) + } else { + var sum = 0.0 + val scenario = v.value as Component + for (ass : scenario.assignment) { + if (ass.name != 'name') { + sum += getNumber(ass.value) + if (!definedUtilities.contains(ass.name)) { + errors.add( + Tuples.create('''«ass.name» must refer to a utility defined in utilities''', ass, + RclPackage.Literals.ASSIGNMENT__NAME)) + } + } + } + if (sum != 1.0) { + errors.add( + Tuples.create('''The utilities in a scenario must sum to 1''', scenario, + RclPackage.Literals.COMPONENT__ASSIGNMENT)) + } + } + } + errors + } + ] + + def static getNumber(Value value) { + val v = value.value + switch v { + IntegerLiteral: Double.valueOf(v.value) + DoubleLiteral: Double.valueOf(v.value) + default: 0.0 + } + } + + @Check + def checkImpact(ImpactVector iv) { + if (!(iv.utilityModel.referable instanceof DeclaredProperty) || + (iv.utilityModel.referable as DeclaredProperty)?.component !== ComponentType.UTILITY) { + error( + '''Impact vector referring to non-utility model «iv.utilityModel.referable?.name»''', + iv, + RclPackage.Literals.IMPACT_VECTOR__UTILITY_MODEL + ) + return + } + var definedUtilities = (((iv.utilityModel.referable as DeclaredProperty).value.value as Component). + assignment.findFirst [ + it.name == "utilities" + ]?.value.value as Component).assignment.map[it.name] + for (ass : iv.component.assignment) { + if (!definedUtilities.contains(ass.name)) { + error('''Undefined utility «ass.name»''', ass, RclPackage.Literals.ASSIGNMENT__NAME) + } + } + } + + static val LOAD_MODEL_CMD_SUPERCLASS = typeof(AbstractLoadModelCmd).name + static val SAVE_MODEL_CMD_SUPERCLASS = typeof(AbstractSaveModelCmd).name + static val MODEL_COMMAND_FACTORY_SUPERCLASS = typeof(ModelCommandFactory).name + static val RAINBOW_OPERATION_SUPERCLASS = typeof(AbstractRainbowModelOperation).name + static val MODEL_SUPERCLASS = typeof(IModelInstance).name + + + @Check + def checkFactoryDefinition(FactoryDefinition factory) { + if (!ConfigAttributeConstants.subclasses(factory.loadCmd, RclValidator.LOAD_MODEL_CMD_SUPERCLASS, + factory.eResource)) { + error( + '''«factory.loadCmd.qualifiedName» must subclass «RclValidator.LOAD_MODEL_CMD_SUPERCLASS»''', + factory, + RclPackage.Literals.FACTORY_DEFINITION__LOAD_CMD, + MUST_SUBCLASS, + RclValidator.LOAD_MODEL_CMD_SUPERCLASS + ) + } + if (factory.saveCmd !== null && + !ConfigAttributeConstants.subclasses(factory.saveCmd, SAVE_MODEL_CMD_SUPERCLASS, factory.eResource)) { + error( + '''«factory.saveCmd.qualifiedName» must subclass «SAVE_MODEL_CMD_SUPERCLASS»''', + factory, + RclPackage.Literals.FACTORY_DEFINITION__SAVE_CMD, + MUST_SUBCLASS, + SAVE_MODEL_CMD_SUPERCLASS + ) + } + if (factory.extends !== null && + !ConfigAttributeConstants.subclasses(factory.extends, MODEL_COMMAND_FACTORY_SUPERCLASS, + factory.eResource)) { + error( + '''«factory.saveCmd.qualifiedName» must subclass «MODEL_COMMAND_FACTORY_SUPERCLASS»''', + factory, + RclPackage.Literals.FACTORY_DEFINITION__EXTENDS, + MUST_SUBCLASS, + MODEL_COMMAND_FACTORY_SUPERCLASS + ) + } + if (!ConfigAttributeConstants.subclasses(factory.modelClass, MODEL_SUPERCLASS, factory.eResource)) { + error( + '''«factory.modelClass.qualifiedName» must subclass «MODEL_SUPERCLASS»''', + factory, + RclPackage.Literals.FACTORY_DEFINITION__MODEL_CLASS, + MUST_SUBCLASS, + MODEL_SUPERCLASS + ) + } + } + + @Check + def checkCommandDefinition(CommandDefinition cmd) { + if (!ConfigAttributeConstants.subclasses(cmd.cmd, RAINBOW_OPERATION_SUPERCLASS, cmd.eResource)) { + error( + '''«cmd.cmd.qualifiedName» must extend «RAINBOW_OPERATION_SUPERCLASS»''', + cmd, + RclPackage.Literals.COMMAND_DEFINITION__CMD, + MUST_SUBCLASS, + RAINBOW_OPERATION_SUPERCLASS + ) + } + + val factory = EcoreUtil2.getContainerOfType(cmd, FactoryDefinition) + if (!(cmd.cmd instanceof JvmDeclaredType)) { + return + } + val cmdClass = cmd.cmd as JvmDeclaredType + var compatibleConstructors = cmdClass.declaredConstructors.filter([ + if (it.parameters.size == cmd.formal.size + 2) { + val firstString = it.parameters.get(0).parameterType.qualifiedName == "java.lang.String" + val secondModel = it.parameters.get(1).parameterType.qualifiedName == factory.modelClass.qualifiedName + return firstString && secondModel + } + false + ]) + if (compatibleConstructors.nullOrEmpty) { + var myParams = cmd.formal.map [ + XtendUtils.formalTypeName(it, true) + ].join(", ") + error( + '''«cmdClass.simpleName» must have constructor with parameters String, «factory.modelClass.simpleName», «myParams»''', + cmd, + RclPackage.Literals.COMMAND_DEFINITION__CMD, + "ConstructurIncompatible" + ) + } else { + val cstr = compatibleConstructors.get(0) + for (var i = 0; i < cmd.formal.size; i++) { + if (cstr.parameters.get(i + 2).parameterType.simpleName != "String") { + val cstrType = cstr.parameters.get(i + 2).parameterType + val formalType = cmd.formal.get(i) + if (cstrType.qualifiedName != XtendUtils.formalTypeName(formalType, false)) { + error( + '''Found «XtendUtils.formalTypeName(formalType,false)», expecting «cstr.simpleName»''', + formalType, + RclPackage.Literals.FORMAL_PARAM__TYPE, + "incorrectType" + ) + } + } + } + } + if (cmd.formal.drop(1).exists[it.name == "target"]) { + warning( + '''Only the first argument of a command can be 'target''', + cmd, + RclPackage.Literals.COMMAND_DEFINITION__FORMAL, + "badTarget" + ) + } else if (cmd.formal.get(0).name != "target") { + warning( + '''The first argument of a command should be 'target''', + cmd, + RclPackage.Literals.COMMAND_DEFINITION__FORMAL, + "badTarget" + ) + } + + } + + @Check + def checkImport(Import import_) { + var uri = import_.eResource.URI + uri = uri.trimSegments(1) +// uri = uri.appendSegment("/") + uri = uri.appendSegments(import_.importURI.split("/")) + if (!import_.eResource.resourceSet.URIConverter.exists(uri, null)) { + error( + '''File '«import_.importURI»' not found''', + import_, + RclPackage.Literals.IMPORT__IMPORT_URI, + "badFile" + ) + } + } + +} diff --git a/ide/org.sa.rainbow.configuration.parent/pom.xml b/ide/org.sa.rainbow.configuration.parent/pom.xml new file mode 100644 index 000000000..ab63b5879 --- /dev/null +++ b/ide/org.sa.rainbow.configuration.parent/pom.xml @@ -0,0 +1,353 @@ + + 4.0.0 + org.sa.rainbow.configuration + 1.0.1-SNAPSHOT + org.sa.rainbow.configuration.parent + pom + + + 3.1.0-SNAPSHOT + 2.19.0 + 1.0.1-SNAPSHOT + UTF-8 + 1.8 + 1.8 + + 1.4.0 + + + + + + + + org.sa.rainbow.configuration + org.sa.rainbow.configuration.ide + org.sa.rainbow.configuration.ui + org.sa.rainbow.configuration.target + org.sa.rainbow.configuration.feature + org.sa.rainbow.configuration.repository + org.sa.rainbow.configuration.tests + org.sa.rainbow.configuration.ui.tests + + + + + + org.eclipse.xtext + xtext-dev-bom + ${xtextVersion} + pom + import + + + + + + + + org.eclipse.tycho + tycho-maven-plugin + ${tycho-version} + true + + + org.eclipse.tycho + tycho-source-plugin + ${tycho-version} + + + plugin-source + + plugin-source + + + + + + org.eclipse.tycho.extras + tycho-source-feature-plugin + ${tycho-version} + + + source-feature + package + + source-feature + + + + + + org.eclipse.tycho + tycho-p2-plugin + ${tycho-version} + + + attach-p2-metadata + package + + p2-metadata + + + + + + org.eclipse.tycho + target-platform-configuration + ${tycho-version} + + + + org.sa.rainbow.configuration + org.sa.rainbow.configuration.target + ${project.version} + + + + + macosx + cocoa + x86_64 + + + win32 + win32 + x86_64 + + + linux + gtk + x86_64 + + + + + + + + + org.eclipse.xtend + xtend-maven-plugin + ${xtextVersion} + + + + compile + xtend-install-debug-info + testCompile + xtend-test-install-debug-info + + + + + ${basedir}/xtend-gen + ${basedir}/xtend-gen + + + + org.apache.maven.plugins + maven-clean-plugin + 3.1.0 + + + + ${basedir}/xtend-gen + + **/* + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-resources-plugin + + + [2.4.3,) + + + resources + testResources + + + + + + + + + + org.codehaus.mojo + + + build-helper-maven-plugin + + + [1.9.1,) + + + add-resource + add-source + add-test-resource + add-test-source + + + + + + + + + + org.eclipse.tycho + + + tycho-compiler-plugin + + + [0.23.1,) + + + compile + + + + + + + + + + org.eclipse.tycho + + + tycho-packaging-plugin + + + [0.23.1,) + + + build-qualifier + build-qualifier-aggregator + validate-id + validate-version + + + + + + + + + + + + + org.eclipse.tycho + tycho-compiler-plugin + ${tycho-version} + + -err:-forbidden + false + + + + + org.eclipse.tycho + tycho-surefire-plugin + ${tycho-version} + + + ${platformSystemProperties} ${systemProperties} + ${moduleProperties} ${additionalTestArguments} + false + false + + + + + + + + codehaus-snapshots + disable dead 'Codehaus Snapshots' repository, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=481478 + http://nexus.codehaus.org/snapshots/ + + false + + + false + + + + + able.maven.repository + + dav:http://acme.able.cs.cmu.edu/maven-repository + + + + + + codehaus-snapshots + disable dead 'Codehaus Snapshots' repository, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=481478 + http://nexus.codehaus.org/snapshots/ + + false + + + false + + + + + + macos + + + mac + + + + + -XstartOnFirstThread + + + + jdk9-or-newer + + [9,) + + + --add-modules=ALL-SYSTEM + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/.gitignore b/ide/org.sa.rainbow.stitch.parent/.gitignore new file mode 100644 index 000000000..1c8923942 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/.gitignore @@ -0,0 +1,3 @@ +**/src-gen +**/xtend-gen +**/target/* diff --git a/ide/org.sa.rainbow.stitch.parent/.project b/ide/org.sa.rainbow.stitch.parent/.project new file mode 100644 index 000000000..c366ab4e4 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/.project @@ -0,0 +1,17 @@ + + + org.sa.rainbow.stitch.parent + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/ide/org.sa.rainbow.stitch.parent/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.stitch.parent/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/.project b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/.project new file mode 100644 index 000000000..e62e117c1 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/.project @@ -0,0 +1,17 @@ + + + org.sa.rainbow.stitch.feature + + + + + + org.eclipse.pde.FeatureBuilder + + + + + + org.eclipse.pde.FeatureNature + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/build.properties b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/build.properties new file mode 100644 index 000000000..64f93a9f0 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/build.properties @@ -0,0 +1 @@ +bin.includes = feature.xml diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/feature.xml b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/feature.xml new file mode 100644 index 000000000..192de49b1 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/feature.xml @@ -0,0 +1,46 @@ + + + + + The minimal Xtext feature to support Stitch + + + + Copyright (c) Carnegie Mellon University + + + + Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/pom.xml b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/pom.xml new file mode 100644 index 000000000..138f469db --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.feature/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + + org.sa.rainbow.stitch + org.sa.rainbow.stitch.parent + 1.0.0-SNAPSHOT + + org.sa.rainbow.stitch.feature + eclipse-feature + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.classpath b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.classpath new file mode 100644 index 000000000..8d26fa598 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.gitignore b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.gitignore new file mode 100644 index 000000000..b83d22266 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.project b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.project new file mode 100644 index 000000000..3f1e2069b --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.project @@ -0,0 +1,40 @@ + + + org.sa.rainbow.stitch.ide + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.xtext.ui.shared.xtextNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.PluginNature + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.settings/org.eclipse.jdt.core.prefs b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..0c68a61dc --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/META-INF/MANIFEST.MF b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/META-INF/MANIFEST.MF new file mode 100644 index 000000000..dc15d544c --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/META-INF/MANIFEST.MF @@ -0,0 +1,15 @@ +Manifest-Version: 1.0 +Automatic-Module-Name: org.sa.rainbow.stitch.ide +Bundle-ManifestVersion: 2 +Bundle-Name: org.sa.rainbow.stitch.ide +Bundle-Vendor: My Company +Bundle-Version: 1.0.0.qualifier +Bundle-SymbolicName: org.sa.rainbow.stitch.ide; singleton:=true +Bundle-ActivationPolicy: lazy +Require-Bundle: org.sa.rainbow.stitch, + org.eclipse.xtext.ide, + org.eclipse.xtext.xbase.ide, + org.antlr.runtime;bundle-version="[3.2.0,3.2.1)" +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Export-Package: org.sa.rainbow.stitch.ide.contentassist.antlr.internal, + org.sa.rainbow.stitch.ide.contentassist.antlr diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/build.properties b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/build.properties new file mode 100644 index 000000000..5c6bbf99f --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/build.properties @@ -0,0 +1,6 @@ +source.. = src/,\ + src-gen/,\ + xtend-gen/ +bin.includes = .,\ + META-INF/ +bin.excludes = **/*.xtend diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/pom.xml b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/pom.xml new file mode 100644 index 000000000..1dd1ac54d --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/pom.xml @@ -0,0 +1,21 @@ + + 4.0.0 + + org.sa.rainbow.stitch + org.sa.rainbow.stitch.parent + 1.0.0-SNAPSHOT + + org.sa.rainbow.stitch.ide + eclipse-plugin + + + + + org.eclipse.xtend + xtend-maven-plugin + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/src/org/sa/rainbow/stitch/ide/StitchIdeModule.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/src/org/sa/rainbow/stitch/ide/StitchIdeModule.xtend new file mode 100644 index 000000000..adcf91b3c --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/src/org/sa/rainbow/stitch/ide/StitchIdeModule.xtend @@ -0,0 +1,11 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch.ide + + +/** + * Use this class to register ide components. + */ +class StitchIdeModule extends AbstractStitchIdeModule { +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/src/org/sa/rainbow/stitch/ide/StitchIdeSetup.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/src/org/sa/rainbow/stitch/ide/StitchIdeSetup.xtend new file mode 100644 index 000000000..5a98dd326 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.ide/src/org/sa/rainbow/stitch/ide/StitchIdeSetup.xtend @@ -0,0 +1,20 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch.ide + +import com.google.inject.Guice +import org.eclipse.xtext.util.Modules2 +import org.sa.rainbow.stitch.StitchRuntimeModule +import org.sa.rainbow.stitch.StitchStandaloneSetup + +/** + * Initialization support for running Xtext languages as language servers. + */ +class StitchIdeSetup extends StitchStandaloneSetup { + + override createInjector() { + Guice.createInjector(Modules2.mixin(new StitchRuntimeModule, new StitchIdeModule)) + } + +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/.project b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/.project new file mode 100644 index 000000000..78d0ea17b --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/.project @@ -0,0 +1,17 @@ + + + org.sa.rainbow.stitch.target + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/org.sa.rainbow.stitch.target.target b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/org.sa.rainbow.stitch.target.target new file mode 100644 index 000000000..d3bd8e808 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/org.sa.rainbow.stitch.target.target @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/pom.xml b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/pom.xml new file mode 100644 index 000000000..031457f71 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.target/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + + org.sa.rainbow.stitch + org.sa.rainbow.stitch.parent + 1.0.0-SNAPSHOT + + org.sa.rainbow.stitch.target + eclipse-target-definition + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.classpath b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.classpath new file mode 100644 index 000000000..e08907a80 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.classpath @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.project b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.project new file mode 100644 index 000000000..cb1d622ea --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.project @@ -0,0 +1,40 @@ + + + org.sa.rainbow.stitch.tests + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.xtext.ui.shared.xtextNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.PluginNature + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.settings/org.eclipse.jdt.core.prefs b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..0c68a61dc --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/META-INF/MANIFEST.MF b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/META-INF/MANIFEST.MF new file mode 100644 index 000000000..fddded1a1 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/META-INF/MANIFEST.MF @@ -0,0 +1,15 @@ +Manifest-Version: 1.0 +Automatic-Module-Name: org.sa.rainbow.stitch.tests +Bundle-ManifestVersion: 2 +Bundle-Name: org.sa.rainbow.stitch.tests +Bundle-Vendor: My Company +Bundle-Version: 1.0.0.qualifier +Bundle-SymbolicName: org.sa.rainbow.stitch.tests; singleton:=true +Bundle-ActivationPolicy: lazy +Require-Bundle: org.sa.rainbow.stitch, + org.junit.jupiter.api;bundle-version="[5.0.0,6.0.0)", + org.eclipse.xtext.testing, + org.eclipse.xtext.xbase.testing, + org.eclipse.xtext.xbase.lib;bundle-version="2.14.0" +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Export-Package: org.sa.rainbow.stitch.tests;x-internal=true diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/build.properties b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/build.properties new file mode 100644 index 000000000..5c6bbf99f --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/build.properties @@ -0,0 +1,6 @@ +source.. = src/,\ + src-gen/,\ + xtend-gen/ +bin.includes = .,\ + META-INF/ +bin.excludes = **/*.xtend diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/pom.xml b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/pom.xml new file mode 100644 index 000000000..c9b9ac05b --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/pom.xml @@ -0,0 +1,21 @@ + + 4.0.0 + + org.sa.rainbow.stitch + org.sa.rainbow.stitch.parent + 1.0.0-SNAPSHOT + + org.sa.rainbow.stitch.tests + eclipse-test-plugin + + + + + org.eclipse.xtend + xtend-maven-plugin + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/src/org/sa/rainbow/stitch/tests/StitchParsingTest.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/src/org/sa/rainbow/stitch/tests/StitchParsingTest.xtend new file mode 100644 index 000000000..82a4af3a5 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.tests/src/org/sa/rainbow/stitch/tests/StitchParsingTest.xtend @@ -0,0 +1,30 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch.tests + +import com.google.inject.Inject +import org.eclipse.xtext.testing.InjectWith +import org.eclipse.xtext.testing.extensions.InjectionExtension +import org.eclipse.xtext.testing.util.ParseHelper +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.^extension.ExtendWith +import org.sa.rainbow.stitch.stitch.script + +@ExtendWith(InjectionExtension) +@InjectWith(StitchInjectorProvider) +class StitchParsingTest { + @Inject + ParseHelper + + + + +
+
+

Example Stitch Web Editor

+
+
+
+
+
+ + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/WebRoot/style.css b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/WebRoot/style.css new file mode 100644 index 000000000..9f0724d8f --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/WebRoot/style.css @@ -0,0 +1,56 @@ +body { + width: 100%; + height: 100%; + overflow: hidden; + font: 16px Helvetica,sans-serif; +} + +a { + color: #22a; + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +.container { + display: block; + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + margin: 20px; +} + +.header { + display: block; + position: absolute; + background-color: #e8e8e8; + top: 0; + left: 0; + right: 0; + height: 60px; + padding: 10px; +} + +.content { + display: block; + position: absolute; + top: 90px; + bottom: 0; + left: 0; + width: 640px; +} + +#xtext-editor { + display: block; + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + padding: 4px; + border: 1px solid #aaa; +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/WebRoot/xtext-resources/generated/mode-s.js b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/WebRoot/xtext-resources/generated/mode-s.js new file mode 100644 index 000000000..b3979e385 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/WebRoot/xtext-resources/generated/mode-s.js @@ -0,0 +1,26 @@ +define(["ace/lib/oop", "ace/mode/text", "ace/mode/text_highlight_rules"], function(oop, mText, mTextHighlightRules) { + var HighlightRules = function() { + var keywords = "TNULL|acme|action|and|as|bool|boolean|char|condition|default|define|distinct|do|done|effect|else|enum|error|exists|failure|false|float|for|forall|function|if|import|in|int|lib|model|module|object|op|or|record|select|seq|sequence|set|strategy|string|success|tactic|true|unique|while"; + this.$rules = { + "start": [ + {token: "lparen", regex: "[\\[({]"}, + {token: "rparen", regex: "[\\])}]"}, + {token: "keyword", regex: "\\b(?:" + keywords + ")\\b"} + ] + }; + }; + oop.inherits(HighlightRules, mTextHighlightRules.TextHighlightRules); + + var Mode = function() { + this.HighlightRules = HighlightRules; + }; + oop.inherits(Mode, mText.Mode); + Mode.prototype.$id = "xtext/s"; + Mode.prototype.getCompletions = function(state, session, pos, prefix) { + return []; + } + + return { + Mode: Mode + }; +}); diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/pom.xml b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/pom.xml new file mode 100644 index 000000000..5300ee28c --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/pom.xml @@ -0,0 +1,129 @@ + + 4.0.0 + + org.sa.rainbow.stitch + org.sa.rainbow.stitch.parent + 1.0.0-SNAPSHOT + + org.sa.rainbow.stitch.web + war + + + src + + + src + + **/*.java + **/*.xtend + + + + + + org.eclipse.xtend + xtend-maven-plugin + + + maven-war-plugin + 3.2.3 + + WebRoot + false + + + + org.eclipse.jetty + jetty-maven-plugin + 9.4.14.v20181114 + + WebRoot + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + initialize + + add-source + add-resource + + + + src-gen + + + + src-gen + + **/*.java + + + + + + + + + + + + + ${project.groupId} + org.sa.rainbow.stitch + ${project.version} + + + ${project.groupId} + org.sa.rainbow.stitch.ide + ${project.version} + + + org.eclipse.xtext + org.eclipse.xtext.xbase.web + ${xtextVersion} + + + org.eclipse.xtext + org.eclipse.xtext.web.servlet + ${xtextVersion} + + + org.eclipse.xtend + org.eclipse.xtend.lib + ${xtextVersion} + + + org.webjars + requirejs + 2.3.6 + + + org.webjars + jquery + 3.4.1 + + + org.webjars + ace + 1.3.3 + + + org.eclipse.jetty + jetty-annotations + 9.4.14.v20181114 + provided + + + org.slf4j + slf4j-simple + 1.7.21 + provided + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/ServerLauncher.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/ServerLauncher.xtend new file mode 100644 index 000000000..2aa4e0379 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/ServerLauncher.xtend @@ -0,0 +1,54 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch.web + +import java.net.InetSocketAddress +import org.eclipse.jetty.annotations.AnnotationConfiguration +import org.eclipse.jetty.server.Server +import org.eclipse.jetty.util.log.Slf4jLog +import org.eclipse.jetty.webapp.MetaInfConfiguration +import org.eclipse.jetty.webapp.WebAppContext +import org.eclipse.jetty.webapp.WebInfConfiguration +import org.eclipse.jetty.webapp.WebXmlConfiguration + +/** + * This program starts an HTTP server for testing the web integration of your DSL. + * Just execute it and point a web browser to http://localhost:8080/ + */ +class ServerLauncher { + def static void main(String[] args) { + val server = new Server(new InetSocketAddress('localhost', 8080)) + server.handler = new WebAppContext => [ + resourceBase = 'WebRoot' + welcomeFiles = #["index.html"] + contextPath = "/" + configurations = #[ + new AnnotationConfiguration, + new WebXmlConfiguration, + new WebInfConfiguration, + new MetaInfConfiguration + ] + setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, '.*/org\\.sa\\.rainbow\\.stitch\\.web/.*,.*\\.jar') + setInitParameter("org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false") + ] + val log = new Slf4jLog(ServerLauncher.name) + try { + server.start + log.info('Server started ' + server.getURI + '...') + new Thread[ + log.info('Press enter to stop the server...') + val key = System.in.read + if (key != -1) { + server.stop + } else { + log.warn('Console input is not available. In order to stop the server, you need to cancel process manually.') + } + ].start + server.join + } catch (Exception exception) { + log.warn(exception.message) + System.exit(1) + } + } +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/StitchServlet.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/StitchServlet.xtend new file mode 100644 index 000000000..5f0d83826 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/StitchServlet.xtend @@ -0,0 +1,32 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch.web + +import javax.servlet.annotation.WebServlet +import org.eclipse.xtext.util.DisposableRegistry +import org.eclipse.xtext.web.servlet.XtextServlet + +/** + * Deploy this class into a servlet container to enable DSL-specific services. + */ +@WebServlet(name = 'XtextServices', urlPatterns = '/xtext-service/*') +class StitchServlet extends XtextServlet { + + DisposableRegistry disposableRegistry + + override init() { + super.init() + val injector = new StitchWebSetup().createInjectorAndDoEMFRegistration() + disposableRegistry = injector.getInstance(DisposableRegistry) + } + + override destroy() { + if (disposableRegistry !== null) { + disposableRegistry.dispose() + disposableRegistry = null + } + super.destroy() + } + +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/StitchWebModule.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/StitchWebModule.xtend new file mode 100644 index 000000000..2d17120a9 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/StitchWebModule.xtend @@ -0,0 +1,11 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch.web + + +/** + * Use this class to register additional components to be used within the web application. + */ +class StitchWebModule extends AbstractStitchWebModule { +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/StitchWebSetup.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/StitchWebSetup.xtend new file mode 100644 index 000000000..5d5bcb1e9 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch.web/src/org/sa/rainbow/stitch/web/StitchWebSetup.xtend @@ -0,0 +1,22 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch.web + +import com.google.inject.Guice +import com.google.inject.Injector +import org.eclipse.xtext.util.Modules2 +import org.sa.rainbow.stitch.StitchRuntimeModule +import org.sa.rainbow.stitch.StitchStandaloneSetup +import org.sa.rainbow.stitch.ide.StitchIdeModule + +/** + * Initialization support for running Xtext languages in web applications. + */ +class StitchWebSetup extends StitchStandaloneSetup { + + override Injector createInjector() { + return Guice.createInjector(Modules2.mixin(new StitchRuntimeModule, new StitchIdeModule, new StitchWebModule)) + } + +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.antlr-generator-3.2.0-patch.jar b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.antlr-generator-3.2.0-patch.jar new file mode 100644 index 000000000..90516fd7a Binary files /dev/null and b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.antlr-generator-3.2.0-patch.jar differ diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.classpath b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.classpath new file mode 100644 index 000000000..8d26fa598 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.gitignore b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.gitignore new file mode 100644 index 000000000..b83d22266 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.launch/Generate Stitch (s) Language Infrastructure.launch b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.launch/Generate Stitch (s) Language Infrastructure.launch new file mode 100644 index 000000000..686164340 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.launch/Generate Stitch (s) Language Infrastructure.launch @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.project b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.project new file mode 100644 index 000000000..88fe54334 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.project @@ -0,0 +1,40 @@ + + + org.sa.rainbow.stitch + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.xtext.ui.shared.xtextNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.PluginNature + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.settings/org.eclipse.core.resources.prefs b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.settings/org.eclipse.jdt.core.prefs b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..0c68a61dc --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/META-INF/MANIFEST.MF b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/META-INF/MANIFEST.MF new file mode 100644 index 000000000..980db0225 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/META-INF/MANIFEST.MF @@ -0,0 +1,30 @@ +Manifest-Version: 1.0 +Automatic-Module-Name: org.sa.rainbow.stitch +Bundle-ManifestVersion: 2 +Bundle-Name: org.sa.rainbow.stitch +Bundle-Vendor: My Company +Bundle-Version: 1.0.0.qualifier +Bundle-SymbolicName: org.sa.rainbow.stitch; singleton:=true +Bundle-ActivationPolicy: lazy +Require-Bundle: org.eclipse.xtext, + org.eclipse.xtext.xbase, + org.eclipse.equinox.common;bundle-version="3.5.0", + org.eclipse.emf.ecore, + org.eclipse.xtext.xbase.lib;bundle-version="2.14.0", + org.eclipse.xtext.util, + org.eclipse.emf.common, + org.eclipse.xtend.lib;bundle-version="2.14.0", + org.antlr.runtime;bundle-version="[3.2.0,3.2.1)" +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Export-Package: org.sa.rainbow.stitch.stitch, + org.sa.rainbow.stitch.generator, + org.sa.rainbow.stitch.validation, + org.sa.rainbow.stitch.scoping, + org.sa.rainbow.stitch, + org.sa.rainbow.stitch.stitch.impl, + org.sa.rainbow.stitch.services, + org.sa.rainbow.stitch.stitch.util, + org.sa.rainbow.stitch.serializer, + org.sa.rainbow.stitch.parser.antlr.internal, + org.sa.rainbow.stitch.parser.antlr +Import-Package: org.apache.log4j diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/build.properties b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/build.properties new file mode 100644 index 000000000..18d540bf6 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/build.properties @@ -0,0 +1,20 @@ +source.. = src/,\ + src-gen/,\ + xtend-gen/ +bin.includes = model/generated/,\ + .,\ + META-INF/,\ + plugin.xml +bin.excludes = **/*.mwe2,\ + **/*.xtend +additional.bundles = org.eclipse.xtext.xbase,\ + org.eclipse.xtext.common.types,\ + org.eclipse.xtext.xtext.generator,\ + org.eclipse.emf.codegen.ecore,\ + org.eclipse.emf.mwe.utils,\ + org.eclipse.emf.mwe2.launch,\ + org.eclipse.emf.mwe2.lib,\ + org.objectweb.asm,\ + org.apache.commons.logging,\ + org.apache.log4j,\ + com.ibm.icu diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/model/generated/Stitch.ecore b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/model/generated/Stitch.ecore new file mode 100644 index 000000000..8d3fc34fa --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/model/generated/Stitch.ecore @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/model/generated/Stitch.genmodel b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/model/generated/Stitch.genmodel new file mode 100644 index 000000000..c883f790a --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/model/generated/Stitch.genmodel @@ -0,0 +1,172 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/plugin.xml b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/plugin.xml new file mode 100644 index 000000000..2bd941a3d --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/plugin.xml @@ -0,0 +1,10 @@ + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/plugin.xml_gen b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/plugin.xml_gen new file mode 100644 index 000000000..2bd941a3d --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/plugin.xml_gen @@ -0,0 +1,10 @@ + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/pom.xml b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/pom.xml new file mode 100644 index 000000000..87fc92182 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/pom.xml @@ -0,0 +1,155 @@ + + 4.0.0 + + org.sa.rainbow.stitch + org.sa.rainbow.stitch.parent + 1.0.0-SNAPSHOT + + org.sa.rainbow.stitch + eclipse-plugin + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + mwe2Launcher + generate-sources + + java + + + + + org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher + + /${project.basedir}/src/org/sa/rainbow/stitch/GenerateStitch.mwe2 + -p + rootPath=/${project.basedir}/.. + + compile + true + false + + + + org.eclipse.emf + org.eclipse.emf.mwe2.launch + 2.11.0 + + + org.eclipse.xtext + org.eclipse.xtext.common.types + ${xtextVersion} + + + org.eclipse.xtext + org.eclipse.xtext.xtext.generator + ${xtextVersion} + + + org.eclipse.xtext + org.eclipse.xtext.xbase + ${xtextVersion} + + + org.eclipse.xtext + xtext-antlr-generator + 2.1.1 + + + + + org.eclipse.xtend + xtend-maven-plugin + + + + org.apache.maven.plugins + maven-clean-plugin + + + + ${basedir}/../org.sa.rainbow.stitch/src-gen/ + + **/* + + + + ${basedir}/../org.sa.rainbow.stitch.tests/src-gen/ + + **/* + + + + ${basedir}/../org.sa.rainbow.stitch.ide/src-gen/ + + **/* + + + + ${basedir}/../org.sa.rainbow.stitch.ui/src-gen/ + + **/* + + + + ${basedir}/../org.sa.rainbow.stitch.ui.tests/src-gen/ + + **/* + + + + ${basedir}/../org.sa.rainbow.stitch.web/src-gen/ + + **/* + + + + ${basedir}/model/generated/ + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.codehaus.mojo + + + exec-maven-plugin + + + [1.2.1,) + + + java + + + + + + + + + + + + + + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/GenerateStitch.mwe2 b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/GenerateStitch.mwe2 new file mode 100644 index 000000000..6e4af1b28 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/GenerateStitch.mwe2 @@ -0,0 +1,58 @@ +module org.sa.rainbow.stitch.GenerateStitch + +import org.eclipse.xtext.xtext.generator.* +import org.eclipse.xtext.xtext.generator.model.project.* + +var rootPath = ".." + +Workflow { + + component = XtextGenerator { + configuration = { + project = StandardProjectConfig { + baseName = "org.sa.rainbow.stitch" + rootPath = rootPath + runtimeTest = { + enabled = true + } + eclipsePlugin = { + enabled = true + } + eclipsePluginTest = { + enabled = true + } + web = { + enabled = true + } + createEclipseMetaData = true + } + code = { + encoding = "UTF-8" + lineDelimiter = "\n" + fileHeader = "/*\n * generated by Xtext \${version}\n */" + } + } + language = StandardLanguage { + name = "org.sa.rainbow.stitch.Stitch" + fileExtensions = "s" + + serializer = { + generateStub = false + } + validator = { + // composedCheck = "org.eclipse.xtext.validation.NamesAreUniqueValidator" + // Generates checks for @Deprecated grammar annotations, an IssueProvider and a corresponding PropertyPage + generateDeprecationValidation = true + } + junitSupport = { + junitVersion = "5" + } + parserGenerator ={ + options ={ + backtrack = true + memoize = true + } + } + } + } +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/RainbowOutputConfigurationProvider.java b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/RainbowOutputConfigurationProvider.java new file mode 100644 index 000000000..b415fa858 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/RainbowOutputConfigurationProvider.java @@ -0,0 +1,64 @@ +package org.sa.rainbow.stitch; +/* +Copyright 2020 Carnegie Mellon University + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + */ +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.xtext.generator.IFileSystemAccess; +import org.eclipse.xtext.generator.IOutputConfigurationProvider; +import org.eclipse.xtext.generator.OutputConfiguration; + +public class RainbowOutputConfigurationProvider implements IOutputConfigurationProvider { + + public static final String RAINBOW_TARGET_PROPERTIES_OUTPUT="rainbow-target-properties"; + public static final String RAINBOW_GENERRATED_SOURCE_OUTPUT="rainbow-generated-source"; + + @Override + public Set getOutputConfigurations() { + OutputConfiguration defaultOutput = new OutputConfiguration(RAINBOW_GENERRATED_SOURCE_OUTPUT); + defaultOutput.setDescription("Output Folder"); + defaultOutput.setOutputDirectory("./src/main/java-gen"); + defaultOutput.setOverrideExistingResources(true); + defaultOutput.setCreateOutputDirectory(true); + defaultOutput.setCleanUpDerivedResources(true); + defaultOutput.setSetDerivedProperty(true); + + OutputConfiguration doc = new OutputConfiguration(IFileSystemAccess.DEFAULT_OUTPUT); + doc.setDescription("Output Folder"); + doc.setOutputDirectory("./src/main/java-gen"); + doc.setOverrideExistingResources(true); + doc.setCreateOutputDirectory(true); + doc.setCleanUpDerivedResources(true); + doc.setSetDerivedProperty(true); + + OutputConfiguration propertyOutput = new OutputConfiguration(RAINBOW_TARGET_PROPERTIES_OUTPUT); + propertyOutput.setDescription("Rainbow target property output folder"); + propertyOutput.setOutputDirectory("./src/main/resources/generated"); + propertyOutput.setOverrideExistingResources(true); + propertyOutput.setCreateOutputDirectory(true); + propertyOutput.setCleanUpDerivedResources(true); + propertyOutput.setSetDerivedProperty(true); + + return new HashSet<>(Arrays.asList(new OutputConfiguration []{defaultOutput, propertyOutput})); + + } + +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/Stitch.xtext b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/Stitch.xtext new file mode 100644 index 000000000..d57aa5aae --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/Stitch.xtext @@ -0,0 +1,438 @@ +grammar org.sa.rainbow.stitch.Stitch hidden(WS, ML_COMMENT, SL_COMMENT) +import "http://www.eclipse.org/emf/2002/Ecore" as ecore + +generate stitch "http://www.sa.org/rainbow/stitch/Stitch" + + + +script + : 'module' i=QualifiedIdentifier ';' /*{beh.createModule($i);}*/ + imports+=importSt* /*{beh.doImports();}*/ + functions+=function* + tactics+=tactic* + strategy+=strategy* + ; + + +importSt + : i = 'import' + ( tl = 'lib' + | tm = 'model' + | to = 'op' + | ta = 'acme' + ) + s = STRING /*{beh.createImport($i, $s);}*/ + ('{' renames+=importRename (',' renames+=importRename)* '}')? ';' + ; + +QualifiedIdentifier returns ecore::EString: + ID ('.' ID)* +; + +importRename + : id1=ID 'as' id2=ID /*{beh.addImportRename(id1,id2);}*/ + ; + +function: + ('function' | 'define') var ';' +; +// +////functions +//// : /*{beh.beginVarList();}*/ +//// (var ';')* +//// /*{beh.endVarList();}*/ +//// ; +// +// +tactic + : 'tactic' name=ID /*{beh.beginTactic($id);}*/ + '(' params=tacticParams? ')' '{'( variables+=var ';')* condition=condition action=action effect=effect '}' +// {beh.endTactic();} + ; + +tacticParams + : params+=tacticParam (',' params+=tacticParam)* + ; + +tacticParam + : dataType ID + ; + +////vars +//// : /*{beh.beginVarList();}*/ +//// (var ';')* +//// /*{beh.endVarList();}*/ +//// ; +// +var + : t=dataType name=ID /*{beh.beginStatemetn($i);}*/ '=' expr=expression + /*{beh.createVar ($t, $i); beh.endStatement();}*/ + ; + +condition + : {condition}'condition' '{' (condition+=expression ';')* '}' + ; + +action + : {action}'action' '{' statements+=statement* '}' + ; + +effect + : {effect} 'effect' ('@' '[' settling=expression ']')? '{' (effect+=expression ';')* '}' + ; + + +strategy + : 'strategy' name=ID + '[' applicability=expression ']' + '{' functions+=function* nodes+=strategyNode* '}' + ; + + +strategyNode + : {strategyNode} (name=ID ':')? + condition=strategyCond + '->' + tactic=tacticRef + ; + +strategyCond + : {strategyCond} '(' ('#' probabilityExpre=expression)? + (condition=expression | 'success' | 'failure' | 'default') + ')' + ; + +tacticRef + : {tacticRef} + (tactic=[tactic] '(' (params+=expression (',' params+=expression)*)? ')' ('@' '[' settling=expression ']')? + '{' (strategyBranch=strategyBranch | 'done') '}') + | {tacticRef} 'done' ';' + | {tacticRef} 'TNULL' ';' + | 'do' '[' (v=ID | i=INT)? ']' t2=[tactic] ';' + | {tacticRef} '|' 'done' ';' + | '{' strategyNode+=strategyNode+ '}' + /*| DO_UNSPEC*/ + ; + +strategyBranch + : strategyNode+=strategyNode+ + ; + + +statement + : + '{' block+=statement+ '}' errorHandler=errorHandler? + | var=var ';' + | expression=expression ';' + | if=ifStmt + | while=whileStmt + | for=forStmt + | {statement} ';' + ; + +errorHandler + : {errorHandler} 'error' '{' ('(' expr+=expression ')' stmt+=statement)* '}' + ; + + +ifStmt + : 'if' '(' expression ')' tStmt=statement (=>'else' fStmt=statement)? + ; + +whileStmt + : 'while' '(' expression ')' body=statement + ; + +forStmt + : 'for' '(' + ( id=tacticParam ':' for=expression + | (var+=var+ | initExpr=expression)? ';' cond=expression? ';' (iter+=expression (',' iter+=expression)*)? ')' statement=statement ) + ; + +expression + : assignmentExpr=assignmentExpression + ; + +enum AssignKind: + ASSIGN = '=' | ADD_ASSIGN = '+=' | MINUS_ASSIGN='-=' | + MULT_ASSIGN = '*=' | DIV_ASSIGN="/=" | REM_ASSIGN='%=' +; + +assignmentExpression returns Expr + : booleanExpr= booleanExpression + (assign=AssignKind + assignmentExpr=assignmentExpression)? + ; +// +booleanExpression returns Expr + : impliesExpression + | quantifiedExpression + ; + +impliesExpression returns Expr + : iffExpression ('->' impliesExpr=impliesExpression)? + ; + +iffExpression returns Expr + : logicalOrExpression ('<->' iffExpr=iffExpression)? + ; + +logicalOrExpression returns Expr + : logicalAndExpression (('or' | '||') logicalOrExpr=logicalOrExpression)? + ; + +logicalAndExpression returns Expr + : equalityExpression ( ('and' | '&&') logicalAndExpr=logicalAndExpression)? + ; + + + +equalityExpression returns Expr + : relationalExpression (eq=('!=' | '==') eqExpr=equalityExpression)? + ; + +relationalExpression returns Expr + : additiveExpression (rel=('<' | '<=' | '>' | '>=') relExpr=relationalExpression)? + ; + +additiveExpression returns Expr + : multiplicativeExpression (add=('+' | '-') addExpr=additiveExpression)? + ; + +multiplicativeExpression returns Expr + : unaryExpression (mult=("*" | "/" | "%") multExpr=multiplicativeExpression)? + ; + +unaryExpression returns Expr + : unary=('++' | '--' | '-' | '+' | '!')? primaryExpr=primaryExpression post=('++' | '--')? +// | DECR unaryExpression +// | MINUS unaryExpression +// | PLUS unaryExpression +// | LOGICAL_NOT unaryExpression +// | primaryExpression + ; + +primaryExpression returns Expr + : idExpression + | postIdExpression + | setExpression + | pathExpression + | '(' assignmentExpression ')' + ; + +idExpression returns Expr + : methodCall + | {idExpression} QualifiedIdentifier + | {idExpression} INT + | {idExpression} FLOAT_LIT + | {idExpression} STRING + | {idExpression} "'" ANY_OTHER "'" + | {idExpression} 'true' + | {idExpression} 'false' + | {idExpression} 'TNULL' + ; + +postIdExpression returns Expr + : id=ID "'" + ; + +methodCall returns Expr + : id=QualifiedIdentifier '(' (expressions+=expression (',' expressions+=expression)*)? ')' + ; + +params + : params+=param (',' params+=param)* + ; + +param + : ID declares=(":" | ':!') dataType=dataType + ; + +quantifiedExpression + : 'forall' ('distinct')? + params+=param (',' params+=param)? + 'in' range=(setExpression | idExpression) + '|' expr=expression + | 'exists' ('unique')? + params+=param (',' params+=param)? + 'in' range=(setExpression | idExpression) + "|" expr=expression + | '{'? 'select' + params+=param (',' params+=param)? + 'in' range=(setExpression | idExpression) + '|' expr=expression '}'? + ; + + + + +setExpression + : literalSet + ; + +pathExpression + : '/' (id=QualifiedIdentifier | call=methodCall)( declares=(':' | ':!') QualifiedIdentifier)? ('[' selector=expression ']')? + continuation=pathExpressionContinuation? + ; + +pathExpressionContinuation + : {pathExpressionContinuation} '/' path?='...'? ID ( declares=(':' | ':!') QualifiedIdentifier)? ('[' expression=expression ']')? continue?=pathExpressionContinuation? + ; + +literalSet + : lb='{' + (expr+=expression (',' expr+=expression)*)? + '}' + ; + +dataType + + : {dataType} 'object' + | {dataType} 'int' + | {dataType} 'float' + | {dataType} 'boolean' + | {dataType} 'bool' + | {dataType} 'char' + | {dataType} 'string' + | {dataType} 'set' ('{' dataType=dataType '}')? + | ('seq' | 'sequence') ('{' dataType=dataType '}') + | {dataType} 'record' ('[' (id+=ID (',' id+=ID)* ':' type+=dataType ';')* ']')? + | {dataType} 'enum' ('{' (ID (',' ID)*)? '}')? + | i=QualifiedIdentifier + ; + +//terminal MODULE: 'module'; +//terminal IMPORT: 'import'; +//terminal LIB: 'lib'; +//terminal MODEL: 'model'; +//terminal OP: 'op'; +//terminal ACME: 'acme'; +//terminal AS: 'as'; +//terminal TACTIC_KW: 'tactic'; +//terminal CONDITION_KW: 'condition'; +//terminal ACTION_KW: 'action'; +//terminal EFFECT_KW: 'effect'; +//terminal ERROR: 'error'; +//terminal STRATEGY_KW: 'strategy'; +//terminal DEFINE: 'define'; +//terminal FUNCTION_KW: 'function'; +//terminal SUCCESS: 'success'; +//terminal FAILURE: 'failure'; +//terminal DEFAULT: 'default'; +//terminal NULLTACTIC: 'TNULL'; +//terminal DO: 'do'; +//terminal DONE: 'done'; +// +//terminal IF: 'if'; +//terminal ELSE: 'else'; +//terminal FOR: 'for'; +//terminal WHILE: 'while'; +// +//terminal T_OBJECT: 'object'; +//terminal T_INT: 'int'; +//terminal T_FLOAT: 'float'; +//terminal T_BOOLEAN: 'boolean'; +//terminal T_CHAR: 'char'; +//terminal T_STRING: 'string'; +//terminal SET: 'set'; +//terminal SEQUENCE: 'sequence'; +//terminal RECORD: 'record'; +//terminal ENUM: 'enum'; +// +//terminal FORALL: 'forall'; +//terminal EXISTS: 'exists'; +//terminal UNIQUE: 'unique'; +//terminal SELECT: 'select'; +//terminal AND: 'and'; +//terminal OR: 'or'; +//terminal IN: 'in'; +// +//terminal TRUE: 'true'; +//terminal FALSE: 'false'; +//terminal NULL: 'null'; + +terminal fragment DIGIT: ('0'..'9'); +//terminal fragment LETTER: ('a'..'z' | 'A'..'Z'); + +terminal FLOAT_LIT + : DIGIT+ '.' DIGIT+ + ; + + +//terminal STRING_LIT +// : DQUOTE -> DQUOTE; + +//terminal CHAR_LIT: "'" ('\\'?.) "'"; + +//terminal LPAREN: '('; +//terminal RPAREN: ')'; +//terminal LBRACKET: '['; +//terminal RBRACKET: ']'; +////terminal LBRACE: '{'; +////terminal RBRACE: '}'; +// +//terminal COLON: ':'; +////terminal SEMICOLON: ';'; +////terminal COMMA: ','; +////terminal DOT: '.'; +//terminal ELLIPSIS: '...'; +//terminal DQUOTE: '"'; +//terminal SQUOTE: '\''; +//terminal BSLASH: '\\'; +//terminal BAR: '|'; +//terminal HASH: '#'; +//terminal AT: '@'; +//terminal DOLLAR: '$'; +// +//terminal ASSIGN: '='; +//terminal PLUS_ASSIGN: '+='; +//terminal MINUS_ASSIGN: '-='; +//terminal STAR_ASSIGN: '*='; +//terminal DIV_ASSIGN: '/='; +//terminal MOD_ASSIGN: '%='; +//terminal COLON_BANG: ':!'; +//terminal LOGICAL_OR: '||' | 'or'; +//terminal LOGICAL_AND: '&&' | 'and'; +//terminal EQ: '=='; +//terminal NE: '!='; +//terminal LT: '<'; +//terminal LE: '<='; +//terminal GE: '>='; +//terminal GT: '>'; +//terminal PLUS: '+'; +//terminal MINUS: '-'; +//terminal STAR: '*'; +//terminal SLASH: '/'; +//terminal MOD: '%'; +//terminal INCR: '++'; +//terminal DECR: '--'; +//terminal LOGICAL_NOT: '!'; +//terminal IMPLIES: '->'; +//terminal IFF: '<->'; +// +//terminal UNDERSCORE: '_'; +//terminal ID: '^'?('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*; +//terminal STRING: +// '"' ( '\\' . /* 'b'|'t'|'n'|'f'|'r'|'u'|'"'|"'"|'\\' */ | !('\\'|'"') )* '"' | +// "'" ( '\\' . /* 'b'|'t'|'n'|'f'|'r'|'u'|'"'|"'"|'\\' */ | !('\\'|"'") )* "'" +// ; +//terminal ML_COMMENT : '/*' -> '*/'; +//terminal SL_COMMENT : '//' !('\n'|'\r')* ('\r'? '\n')?; +// +////terminal WS : (' '|'\t'|'\r'|'\n')+; +// +//terminal ANY_OTHER: .; + +terminal ID: ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'-'|'0'..'9')*; +terminal INT returns ecore::EInt: ('0'..'9')+; +terminal STRING: + '"' ( '\\' . /* 'b'|'t'|'n'|'f'|'r'|'u'|'"'|"'"|'\\' */ | !('\\'|'"') )* '"' + ; +terminal ML_COMMENT : '/*' -> '*/'; +terminal SL_COMMENT : '//' !('\n'|'\r')* ('\r'? '\n')?; + +terminal WS : (' '|'\t'|'\r'|'\n')+; + +terminal ANY_OTHER: .; + + diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/StitchRuntimeModule.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/StitchRuntimeModule.xtend new file mode 100644 index 000000000..29d2e05e0 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/StitchRuntimeModule.xtend @@ -0,0 +1,11 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch + + +/** + * Use this class to register components to be used at runtime / without the Equinox extension registry. + */ +class StitchRuntimeModule extends AbstractStitchRuntimeModule { +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/StitchRuntimeStandaloneModule.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/StitchRuntimeStandaloneModule.xtend new file mode 100644 index 000000000..9d19c3946 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/StitchRuntimeStandaloneModule.xtend @@ -0,0 +1,22 @@ +package org.sa.rainbow.stitch + +import com.google.inject.Binder +import com.google.inject.name.Names +import org.eclipse.xtext.common.types.access.CachingClasspathTypeProviderFactory +import org.eclipse.xtext.common.types.access.IJvmTypeProvider +import org.eclipse.xtext.common.types.xtext.AbstractTypeScopeProvider +import org.eclipse.xtext.common.types.xtext.ClasspathBasedTypeScopeProvider + +class StitchRuntimeStandaloneModule extends StitchRuntimeModule { + + override configure(Binder binder) { + super.configure(binder) + configureJvmTypeProvider(binder) + } + + def configureJvmTypeProvider(Binder binder) { + binder.bind(AbstractTypeScopeProvider).annotatedWith(Names.named("jvmtypes")).to(ClasspathBasedTypeScopeProvider) + binder.bind(IJvmTypeProvider.Factory).annotatedWith(Names.named("jvmtypes")).to(CachingClasspathTypeProviderFactory) + } + +} \ No newline at end of file diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/StitchStandaloneSetup.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/StitchStandaloneSetup.xtend new file mode 100644 index 000000000..007682ef5 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/StitchStandaloneSetup.xtend @@ -0,0 +1,15 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch + + +/** + * Initialization support for running Xtext languages without Equinox extension registry. + */ +class StitchStandaloneSetup extends StitchStandaloneSetupGenerated { + + def static void doSetup() { + new StitchStandaloneSetup().createInjectorAndDoEMFRegistration() + } +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/generator/StitchGenerator.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/generator/StitchGenerator.xtend new file mode 100644 index 000000000..2a6333b2a --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/generator/StitchGenerator.xtend @@ -0,0 +1,25 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch.generator + +import org.eclipse.emf.ecore.resource.Resource +import org.eclipse.xtext.generator.AbstractGenerator +import org.eclipse.xtext.generator.IFileSystemAccess2 +import org.eclipse.xtext.generator.IGeneratorContext + +/** + * Generates code from your model files on save. + * + * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#code-generation + */ +class StitchGenerator extends AbstractGenerator { + + override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) { +// fsa.generateFile('greetings.txt', 'People to greet: ' + +// resource.allContents +// .filter(Greeting) +// .map[name] +// .join(', ')) + } +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/scoping/StitchScopeProvider.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/scoping/StitchScopeProvider.xtend new file mode 100644 index 000000000..c5122870b --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/scoping/StitchScopeProvider.xtend @@ -0,0 +1,15 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch.scoping + + +/** + * This class contains custom scoping description. + * + * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#scoping + * on how and when to use it. + */ +class StitchScopeProvider extends AbstractStitchScopeProvider { + +} diff --git a/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/validation/StitchValidator.xtend b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/validation/StitchValidator.xtend new file mode 100644 index 000000000..32557a157 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/org.sa.rainbow.stitch/src/org/sa/rainbow/stitch/validation/StitchValidator.xtend @@ -0,0 +1,25 @@ +/* + * generated by Xtext 2.19.0 + */ +package org.sa.rainbow.stitch.validation + + +/** + * This class contains custom validation rules. + * + * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#validation + */ +class StitchValidator extends AbstractStitchValidator { + +// public static val INVALID_NAME = 'invalidName' +// +// @Check +// def checkGreetingStartsWithCapital(Greeting greeting) { +// if (!Character.isUpperCase(greeting.name.charAt(0))) { +// warning('Name should start with a capital', +// StitchPackage.Literals.GREETING__NAME, +// INVALID_NAME) +// } +// } + +} diff --git a/ide/org.sa.rainbow.stitch.parent/pom.xml b/ide/org.sa.rainbow.stitch.parent/pom.xml new file mode 100644 index 000000000..e101ffe71 --- /dev/null +++ b/ide/org.sa.rainbow.stitch.parent/pom.xml @@ -0,0 +1,345 @@ + + 4.0.0 + org.sa.rainbow.stitch + 1.0.0-SNAPSHOT + org.sa.rainbow.stitch.parent + pom + + + 2.19.0 + UTF-8 + 1.8 + 1.8 + + 1.4.0 + + + + + + + + org.sa.rainbow.stitch + org.sa.rainbow.stitch.ide + org.sa.rainbow.stitch.ui + org.sa.rainbow.stitch.web + org.sa.rainbow.stitch.target + org.sa.rainbow.stitch.feature + org.sa.rainbow.stitch.tests + org.sa.rainbow.stitch.ui.tests + + + + + org.eclipse.xtext + xtext-dev-bom + ${xtextVersion} + pom + import + + + + + + + org.eclipse.tycho + tycho-maven-plugin + ${tycho-version} + true + + + org.eclipse.tycho + tycho-source-plugin + ${tycho-version} + + + plugin-source + + plugin-source + + + + + + org.eclipse.tycho.extras + tycho-source-feature-plugin + ${tycho-version} + + + source-feature + package + + source-feature + + + + + + org.eclipse.tycho + tycho-p2-plugin + ${tycho-version} + + + attach-p2-metadata + package + + p2-metadata + + + + + + org.eclipse.tycho + target-platform-configuration + ${tycho-version} + + + + org.sa.rainbow.stitch + org.sa.rainbow.stitch.target + ${project.version} + + + + + macosx + cocoa + x86_64 + + + win32 + win32 + x86_64 + + + linux + gtk + x86_64 + + + + + + + + + org.eclipse.xtend + xtend-maven-plugin + ${xtextVersion} + + + + compile + xtend-install-debug-info + testCompile + xtend-test-install-debug-info + + + + + ${basedir}/xtend-gen + ${basedir}/xtend-gen + + + + org.apache.maven.plugins + maven-clean-plugin + 3.1.0 + + + + ${basedir}/xtend-gen + + **/* + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-resources-plugin + + + [2.4.3,) + + + resources + testResources + + + + + + + + + + org.codehaus.mojo + + + build-helper-maven-plugin + + + [1.9.1,) + + + add-resource + add-source + add-test-resource + add-test-source + + + + + + + + + + org.eclipse.tycho + + + tycho-compiler-plugin + + + [0.23.1,) + + + compile + + + + + + + + + + org.eclipse.tycho + + + tycho-packaging-plugin + + + [0.23.1,) + + + build-qualifier + build-qualifier-aggregator + validate-id + validate-version + + + + + + + + + + + + + org.eclipse.tycho + tycho-compiler-plugin + ${tycho-version} + + -err:-forbidden + false + + + + + org.eclipse.tycho + tycho-surefire-plugin + ${tycho-version} + + + ${platformSystemProperties} ${systemProperties} ${moduleProperties} ${additionalTestArguments} + false + false + + + + + + + + codehaus-snapshots + disable dead 'Codehaus Snapshots' repository, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=481478 + http://nexus.codehaus.org/snapshots/ + + false + + + false + + + + + able.maven.repository + + dav:http://acme.able.cs.cmu.edu/maven-repository + + + + + + codehaus-snapshots + disable dead 'Codehaus Snapshots' repository, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=481478 + http://nexus.codehaus.org/snapshots/ + + false + + + false + + + + + + macos + + + mac + + + + + -XstartOnFirstThread + + + + jdk9-or-newer + + [9,) + + + --add-modules=ALL-SYSTEM + + + + + + + diff --git a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/BooleanLED.java b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/BooleanLED.java index feb1bb6ae..d87204d4f 100644 --- a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/BooleanLED.java +++ b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/BooleanLED.java @@ -1,103 +1,103 @@ -package edu.cmu.rainbow_ui.display.widgets; - -import java.util.Map; - -import com.google.gwt.dev.util.collect.HashMap; -import com.vaadin.server.Page; -import com.vaadin.server.Page.Styles; -import com.vaadin.ui.Label; -import com.vaadin.ui.VerticalLayout; - -import edu.cmu.rainbow_ui.common.DataValueSupport; - -public class BooleanLED extends Widget { - - private static final WidgetDescription widgetDescription; - - static { - String name = "2 color LED"; - String description = "An LED that displays a value (boolean or integer) as a color"; - String type = "boolean"; - WidgetFactory factory = new WidgetFactory () { - - @Override - public IWidget getInstance (String mapping) { - return new BooleanLED (mapping); - } - }; - - Map propDescr = new HashMap<> (); - propDescr.put ("name", new WidgetPropertyDescription (String.class, "Visual name of the property", "")); - propDescr.put ("greenValue", new WidgetPropertyDescription (Boolean.class, - "Boolean value that should show green", true)); - propDescr.put ("redValue", new WidgetPropertyDescription (Boolean.class, "Boolean value that should be red", - false)); - widgetDescription = new WidgetDescription (name, description, type, factory, propDescr); - } - - public static WidgetDescription register () { - return widgetDescription; - } - - protected Label label; - protected Label led; - protected String visualName; - - - public BooleanLED (String mapping) { - super (mapping); - label = new Label (visualName); - led = new Label (); - led.setWidth (20, Unit.PIXELS); - led.setHeight (20, Unit.PIXELS); - led.addStyleName ("led"); - getRoot ().addComponent (new VerticalLayout (label, led)); - Styles styles = Page.getCurrent ().getStyles (); - styles.add (".rainbow-theme .led { border : 1px black solid;}"); - styles.add (".rainbow-theme .led-green {background : palegreen;}"); - styles.add (".rainbow-theme .led-red {background : red;}"); - } - - @Override - public WidgetDescription getWidgetDescription () { - return widgetDescription; - } - - @Override - public void update () { - boolean val; - try { - val = DataValueSupport.converter.to_java (value, Boolean.class); - } - catch (Throwable e) { - val = false; - } - boolean redValue = (Boolean )getProperty ("redValue"); - boolean greenValue = (Boolean )getProperty ("greenValue"); - if (redValue == val) { - led.removeStyleName ("led-green"); - led.addStyleName ("led-red"); - } - if (greenValue == val) { - led.removeStyleName ("led-red"); - led.addStyleName ("led-green"); - } - - } - - @Override - public IWidget getClone () { - BooleanLED clone = new BooleanLED (mapping); - clone.setProperties (this.getProperties ()); - return clone; - } - - @Override - protected void onPropertyUpdate () { - String vName = (String )properties.get ("name"); - visualName = vName; - label.setValue (visualName); - update (); - } - -} +package edu.cmu.rainbow_ui.display.widgets; + +import java.util.Map; + +import com.google.gwt.dev.util.collect.HashMap; +import com.vaadin.server.Page; +import com.vaadin.server.Page.Styles; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalLayout; + +import edu.cmu.rainbow_ui.common.DataValueSupport; + +public class BooleanLED extends Widget { + + private static final WidgetDescription widgetDescription; + + static { + String name = "2 color LED"; + String description = "An LED that displays a value (boolean or integer) as a color"; + String type = "boolean"; + WidgetFactory factory = new WidgetFactory () { + + @Override + public IWidget getInstance (String mapping) { + return new BooleanLED (mapping); + } + }; + + Map propDescr = new HashMap<> (); + propDescr.put ("name", new WidgetPropertyDescription (String.class, "Visual name of the property", "")); + propDescr.put ("greenValue", new WidgetPropertyDescription (Boolean.class, + "Boolean value that should show green", true)); + propDescr.put ("redValue", new WidgetPropertyDescription (Boolean.class, "Boolean value that should be red", + false)); + widgetDescription = new WidgetDescription (name, description, type, factory, propDescr); + } + + public static WidgetDescription register () { + return widgetDescription; + } + + protected Label label; + protected Label led; + protected String visualName; + + + public BooleanLED (String mapping) { + super (mapping); + label = new Label (visualName); + led = new Label (); + led.setWidth (20, Unit.PIXELS); + led.setHeight (20, Unit.PIXELS); + led.addStyleName ("led"); + getRoot ().addComponent (new VerticalLayout (label, led)); + Styles styles = Page.getCurrent ().getStyles (); + styles.add (".rainbow-theme .led { border : 1px black solid;}"); + styles.add (".rainbow-theme .led-green {background : palegreen;}"); + styles.add (".rainbow-theme .led-red {background : red;}"); + } + + @Override + public WidgetDescription getWidgetDescription () { + return widgetDescription; + } + + @Override + public void update () { + boolean val; + try { + val = DataValueSupport.converter.to_java (value, Boolean.class); + } + catch (Throwable e) { + val = false; + } + boolean redValue = (Boolean )getProperty ("redValue"); + boolean greenValue = (Boolean )getProperty ("greenValue"); + if (redValue == val) { + led.removeStyleName ("led-green"); + led.addStyleName ("led-red"); + } + if (greenValue == val) { + led.removeStyleName ("led-red"); + led.addStyleName ("led-green"); + } + + } + + @Override + public IWidget getClone () { + BooleanLED clone = new BooleanLED (mapping); + clone.setProperties (this.getProperties ()); + return clone; + } + + @Override + protected void onPropertyUpdate () { + String vName = (String )properties.get ("name"); + visualName = vName; + label.setValue (visualName); + update (); + } + +} diff --git a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/BooleanState.java b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/BooleanState.java index 344a23bcc..143b42109 100644 --- a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/BooleanState.java +++ b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/BooleanState.java @@ -1,104 +1,104 @@ -package edu.cmu.rainbow_ui.display.widgets; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.vaadin.server.FileResource; -import com.vaadin.server.VaadinService; -import com.vaadin.ui.Alignment; -import com.vaadin.ui.Button; -import com.vaadin.ui.HorizontalLayout; -import com.vaadin.ui.Label; - -import edu.cmu.cs.able.typelib.jconv.ValueConversionException; -import edu.cmu.rainbow_ui.common.DataValueSupport; - -public class BooleanState extends Widget { - - private static final WidgetDescription widgetDescription; - - static { - String name = "BooleanState"; - String description = "A widget that displays a boolean as a green (true) or red (false) circle"; - String type = "boolean"; - WidgetFactory factory = new WidgetFactory () { - - @Override - public IWidget getInstance (String mapping) { - return new BooleanState (mapping); - } - }; - Map propDescr = new HashMap<> (); - propDescr.put ("name", new WidgetPropertyDescription (String.class, "Visual name of the property", "")); - widgetDescription = new WidgetDescription (name, description, type, factory, propDescr); - } - - public static WidgetDescription register () { - return widgetDescription; - } - - private Label label; - private FileResource noValResource; - private FileResource trueValResource; - private FileResource falseValResource; - private Button valLabel; - - public BooleanState (String mapping) { - super (mapping); - getImages (); - label = new Label (); - valLabel = new Button (); - HorizontalLayout layout = new HorizontalLayout (); - layout.setWidth ("100%"); - layout.addComponent (label); - layout.addComponent (valLabel); - layout.setExpandRatio (label, 1.0f); - layout.setComponentAlignment (valLabel, Alignment.MIDDLE_RIGHT); - getRoot ().addComponent (layout); - } - - private void getImages () { - String basepath = VaadinService.getCurrent ().getBaseDirectory ().getAbsolutePath (); - noValResource = new FileResource (new File (basepath + "/WEB-INF/images/boolean-state/no-value.png")); - trueValResource = new FileResource (new File (basepath + "/WEB-INF/images/boolean-state/true-value.png")); - falseValResource = new FileResource (new File (basepath + "/WEB-INF/images/boolean-state/false-value.png")); - } - - @Override - public WidgetDescription getWidgetDescription () { - return widgetDescription; - } - - @Override - public void update () { - try { - Boolean val = DataValueSupport.converter.to_java (value, Boolean.class); - if (val) { - valLabel.setIcon (trueValResource); - } - else { - valLabel.setIcon (falseValResource); - } - } - catch (ValueConversionException e) { - Logger.getLogger (this.getClass ().getName ()).log (Level.SEVERE, null, e); - } - } - - @Override - public IWidget getClone () { - BooleanState clone = new BooleanState (mapping); - clone.setProperties (this.getProperties ()); - return clone; - } - - @Override - protected void onPropertyUpdate () { - String vName = (String )properties.get ("name"); - label.setValue (vName); - } - -} +package edu.cmu.rainbow_ui.display.widgets; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.vaadin.server.FileResource; +import com.vaadin.server.VaadinService; +import com.vaadin.ui.Alignment; +import com.vaadin.ui.Button; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; + +import edu.cmu.cs.able.typelib.jconv.ValueConversionException; +import edu.cmu.rainbow_ui.common.DataValueSupport; + +public class BooleanState extends Widget { + + private static final WidgetDescription widgetDescription; + + static { + String name = "BooleanState"; + String description = "A widget that displays a boolean as a green (true) or red (false) circle"; + String type = "boolean"; + WidgetFactory factory = new WidgetFactory () { + + @Override + public IWidget getInstance (String mapping) { + return new BooleanState (mapping); + } + }; + Map propDescr = new HashMap<> (); + propDescr.put ("name", new WidgetPropertyDescription (String.class, "Visual name of the property", "")); + widgetDescription = new WidgetDescription (name, description, type, factory, propDescr); + } + + public static WidgetDescription register () { + return widgetDescription; + } + + private Label label; + private FileResource noValResource; + private FileResource trueValResource; + private FileResource falseValResource; + private Button valLabel; + + public BooleanState (String mapping) { + super (mapping); + getImages (); + label = new Label (); + valLabel = new Button (); + HorizontalLayout layout = new HorizontalLayout (); + layout.setWidth ("100%"); + layout.addComponent (label); + layout.addComponent (valLabel); + layout.setExpandRatio (label, 1.0f); + layout.setComponentAlignment (valLabel, Alignment.MIDDLE_RIGHT); + getRoot ().addComponent (layout); + } + + private void getImages () { + String basepath = VaadinService.getCurrent ().getBaseDirectory ().getAbsolutePath (); + noValResource = new FileResource (new File (basepath + "/WEB-INF/images/boolean-state/no-value.png")); + trueValResource = new FileResource (new File (basepath + "/WEB-INF/images/boolean-state/true-value.png")); + falseValResource = new FileResource (new File (basepath + "/WEB-INF/images/boolean-state/false-value.png")); + } + + @Override + public WidgetDescription getWidgetDescription () { + return widgetDescription; + } + + @Override + public void update () { + try { + Boolean val = DataValueSupport.converter.to_java (value, Boolean.class); + if (val) { + valLabel.setIcon (trueValResource); + } + else { + valLabel.setIcon (falseValResource); + } + } + catch (ValueConversionException e) { + Logger.getLogger (this.getClass ().getName ()).log (Level.SEVERE, null, e); + } + } + + @Override + public IWidget getClone () { + BooleanState clone = new BooleanState (mapping); + clone.setProperties (this.getProperties ()); + return clone; + } + + @Override + protected void onPropertyUpdate () { + String vName = (String )properties.get ("name"); + label.setValue (vName); + } + +} diff --git a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/IWidget.java b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/IWidget.java index 5729b1611..02ad93a26 100644 --- a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/IWidget.java +++ b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/IWidget.java @@ -1,48 +1,48 @@ -package edu.cmu.rainbow_ui.display.widgets; - -import java.util.Map; - -import com.vaadin.ui.Component; - -import edu.cmu.cs.able.typelib.type.DataValue; - -public interface IWidget { - - - public static interface IHandler { - public void handle (); - } - - public abstract Map getProperties (); - - public abstract Object getProperty (String propName); - - public abstract void setProperty (String propName, Object propValue) throws IllegalArgumentException; - - public abstract IWidget getClone (); - - public abstract void deactivate (); - - public abstract void activate (); - - public abstract boolean isActive (); - - public abstract void update (); - - public abstract void setValue (DataValue value); - - public abstract DataValue getValue (); - - public abstract WidgetDescription getWidgetDescription (); - - public abstract String getMapping (); - - public abstract Component getAsComponent (); - - public abstract String getPropertyMonitoring (); - - public abstract void setPropertyMonitoring (String propertyName); - - public abstract void setCloseHandler (IHandler closeHandler); - -} +package edu.cmu.rainbow_ui.display.widgets; + +import java.util.Map; + +import com.vaadin.ui.Component; + +import edu.cmu.cs.able.typelib.type.DataValue; + +public interface IWidget { + + + public static interface IHandler { + public void handle (); + } + + public abstract Map getProperties (); + + public abstract Object getProperty (String propName); + + public abstract void setProperty (String propName, Object propValue) throws IllegalArgumentException; + + public abstract IWidget getClone (); + + public abstract void deactivate (); + + public abstract void activate (); + + public abstract boolean isActive (); + + public abstract void update (); + + public abstract void setValue (DataValue value); + + public abstract DataValue getValue (); + + public abstract WidgetDescription getWidgetDescription (); + + public abstract String getMapping (); + + public abstract Component getAsComponent (); + + public abstract String getPropertyMonitoring (); + + public abstract void setPropertyMonitoring (String propertyName); + + public abstract void setCloseHandler (IHandler closeHandler); + +} diff --git a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/JSWidget.java b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/JSWidget.java index 361858d94..2983b932d 100644 --- a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/JSWidget.java +++ b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/JSWidget.java @@ -1,143 +1,143 @@ -package edu.cmu.rainbow_ui.display.widgets; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import com.vaadin.ui.AbstractJavaScriptComponent; -import com.vaadin.ui.Component; - -import edu.cmu.cs.able.typelib.type.DataValue; - -public abstract class JSWidget extends AbstractJavaScriptComponent implements IWidget, IUpdatableWidget { - - protected String mapping; - - protected DataValue value; - - protected boolean active; - - protected boolean configured; - - protected Map properties = new HashMap<> (); - - private String propertyMonitoring; - - private IHandler closeHandler; - - public JSWidget (String mapping) { - this.mapping = mapping; - active = false; - configured = false; - /* Fill default properties */ - for (String prop : getWidgetDescription ().getProperties ().keySet ()) { - properties.put (prop, getWidgetDescription ().getProperties ().get (prop).getDefaultValue ()); - } - } - - @Override - public Map getProperties () { - return Collections.unmodifiableMap (properties); - } - - @Override - public Object getProperty (String propName) { - return properties.get (propName); - } - - /** - * Set all properties. - * - * @param props - * properties map - */ - protected void setProperties (Map props) { - properties = props; - onPropertyUpdate (); - } - - - @Override - public void setProperty (String propName, Object propValue) throws IllegalArgumentException { - WidgetPropertyDescription propDescr = getWidgetDescription ().getProperties ().get (propName); - if (propDescr == null) throw new IllegalArgumentException ("Widget doesn't have a property: " + propName); - if (!propDescr.getValueClass ().isAssignableFrom (propValue.getClass ())) - throw new IllegalArgumentException ("Widget property value class missmatch." + "\n expected: " - + propDescr.getValueClass ().toString () + "\n actual: " + propValue.getClass ().toString ()); - properties.put (propName, propValue); - onPropertyUpdate (); - } - - @Override - public abstract IWidget getClone (); - - @Override - public void deactivate () { - active = false; - configured = false; - } - - @Override - public void activate () { - active = true; - if (!configured) { - configure (); - } - } - - protected void configure () { - configured = true; - } - - @Override - public boolean isActive () { - return active; - } - - @Override - public abstract void update (); - - @Override - public void setValue (DataValue value) { - this.value = value; - } - - @Override - public DataValue getValue () { - return value; - } - - @Override - public abstract WidgetDescription getWidgetDescription (); - - @Override - public String getMapping () { - return mapping; - } - - /** - * Signals the widget implementation that properties were updated. - */ - protected abstract void onPropertyUpdate (); - - @Override - public Component getAsComponent () { - return this; - } - - @Override - public void setPropertyMonitoring (String propertyName) { - propertyMonitoring = propertyName; - } - - @Override - public String getPropertyMonitoring () { - return propertyMonitoring; - } - - @Override - public void setCloseHandler (IHandler closeHandler) { - this.closeHandler = closeHandler; - } - -} +package edu.cmu.rainbow_ui.display.widgets; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import com.vaadin.ui.AbstractJavaScriptComponent; +import com.vaadin.ui.Component; + +import edu.cmu.cs.able.typelib.type.DataValue; + +public abstract class JSWidget extends AbstractJavaScriptComponent implements IWidget, IUpdatableWidget { + + protected String mapping; + + protected DataValue value; + + protected boolean active; + + protected boolean configured; + + protected Map properties = new HashMap<> (); + + private String propertyMonitoring; + + private IHandler closeHandler; + + public JSWidget (String mapping) { + this.mapping = mapping; + active = false; + configured = false; + /* Fill default properties */ + for (String prop : getWidgetDescription ().getProperties ().keySet ()) { + properties.put (prop, getWidgetDescription ().getProperties ().get (prop).getDefaultValue ()); + } + } + + @Override + public Map getProperties () { + return Collections.unmodifiableMap (properties); + } + + @Override + public Object getProperty (String propName) { + return properties.get (propName); + } + + /** + * Set all properties. + * + * @param props + * properties map + */ + protected void setProperties (Map props) { + properties = props; + onPropertyUpdate (); + } + + + @Override + public void setProperty (String propName, Object propValue) throws IllegalArgumentException { + WidgetPropertyDescription propDescr = getWidgetDescription ().getProperties ().get (propName); + if (propDescr == null) throw new IllegalArgumentException ("Widget doesn't have a property: " + propName); + if (!propDescr.getValueClass ().isAssignableFrom (propValue.getClass ())) + throw new IllegalArgumentException ("Widget property value class missmatch." + "\n expected: " + + propDescr.getValueClass ().toString () + "\n actual: " + propValue.getClass ().toString ()); + properties.put (propName, propValue); + onPropertyUpdate (); + } + + @Override + public abstract IWidget getClone (); + + @Override + public void deactivate () { + active = false; + configured = false; + } + + @Override + public void activate () { + active = true; + if (!configured) { + configure (); + } + } + + protected void configure () { + configured = true; + } + + @Override + public boolean isActive () { + return active; + } + + @Override + public abstract void update (); + + @Override + public void setValue (DataValue value) { + this.value = value; + } + + @Override + public DataValue getValue () { + return value; + } + + @Override + public abstract WidgetDescription getWidgetDescription (); + + @Override + public String getMapping () { + return mapping; + } + + /** + * Signals the widget implementation that properties were updated. + */ + protected abstract void onPropertyUpdate (); + + @Override + public Component getAsComponent () { + return this; + } + + @Override + public void setPropertyMonitoring (String propertyName) { + propertyMonitoring = propertyName; + } + + @Override + public String getPropertyMonitoring () { + return propertyMonitoring; + } + + @Override + public void setCloseHandler (IHandler closeHandler) { + this.closeHandler = closeHandler; + } + +} diff --git a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/LineGauge.java b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/LineGauge.java index 9019674ac..da3f8d9ee 100644 --- a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/LineGauge.java +++ b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/LineGauge.java @@ -1,117 +1,117 @@ -package edu.cmu.rainbow_ui.display.widgets; - -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.vaadin.ui.Alignment; -import com.vaadin.ui.Label; -import com.vaadin.ui.VerticalLayout; - -import edu.cmu.cs.able.typelib.jconv.ValueConversionException; -import edu.cmu.rainbow_ui.common.DataValueSupport; - -public class LineGauge extends Widget { - - private static final WidgetDescription widgetDescription; - static { - String name = "LineGauge"; - String description = "Shows a moving line display of the value and its history"; - String type = "float"; - WidgetFactory factory = new WidgetFactory () { - - @Override - public IWidget getInstance (String mapping) { - return new LineGauge (mapping); - } - - }; - Map propDescr = new HashMap<> (); - propDescr.put ("name", new WidgetPropertyDescription (String.class, "Visual name of the property", "")); - propDescr.put ("max", new WidgetPropertyDescription (Double.class, "The maximum value that will be displayed", - Double.valueOf (1.0))); - propDescr.put ("min", new WidgetPropertyDescription (Double.class, - "The minimum value that will be displayed by the widget", Double.valueOf (0))); - propDescr.put ("window", new WidgetPropertyDescription (Integer.class, "The number of samples to display", - Double.valueOf (10))); - propDescr.put ("yLabel", new WidgetPropertyDescription (String.class, "The label to use for the Y axis", "")); - propDescr.put ("threshold", new WidgetPropertyDescription (Double.class, - "The value to display as the threshold", Double.valueOf (-1.0))); - widgetDescription = new WidgetDescription (name, description, type, factory, propDescr); - } - - static WidgetDescription register () { - return widgetDescription; - } - - private Label m_label; - private LineGaugeComponent m_gauge; - - public LineGauge (String mapping) { - super (mapping); - - m_label = new Label (); - m_gauge = new LineGaugeComponent (); - - VerticalLayout layout = new VerticalLayout (); - layout.setWidth ("100%"); - layout.addComponent (m_gauge); - layout.addComponent (m_label); - layout.setExpandRatio (m_gauge, 1.0f); - layout.setComponentAlignment (m_gauge, Alignment.MIDDLE_CENTER); - - getRoot ().addComponent (layout); - } - - @Override - public IWidget getClone () { - LineGauge clone = new LineGauge (mapping); - clone.setProperties (this.getProperties ()); - return clone; - } - - @Override - public void update () { - Double val = 0.0; - try { - val = DataValueSupport.converter.to_java (value, Double.class); - } - catch (ValueConversionException ex) { - try { - val = (double )DataValueSupport.converter.to_java (value, Float.class); - } - catch (ValueConversionException e) { - Logger.getLogger (LineGauge.class.getName ()).log (Level.SEVERE, null, ex); - - } - - } - m_gauge.updateValue (val); - } - - @Override - public WidgetDescription getWidgetDescription () { - return widgetDescription; - } - - @Override - protected void onPropertyUpdate () { - String vName = (String )properties.get ("name"); - m_label.setValue (vName); - } - - @Override - public void activate () { - super.activate (); - m_gauge.configure (this.getProperties ()); - m_gauge.start (); - } - - @Override - public void deactivate () { - super.deactivate (); - m_gauge.stop (); - } - -} +package edu.cmu.rainbow_ui.display.widgets; + +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.vaadin.ui.Alignment; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalLayout; + +import edu.cmu.cs.able.typelib.jconv.ValueConversionException; +import edu.cmu.rainbow_ui.common.DataValueSupport; + +public class LineGauge extends Widget { + + private static final WidgetDescription widgetDescription; + static { + String name = "LineGauge"; + String description = "Shows a moving line display of the value and its history"; + String type = "float"; + WidgetFactory factory = new WidgetFactory () { + + @Override + public IWidget getInstance (String mapping) { + return new LineGauge (mapping); + } + + }; + Map propDescr = new HashMap<> (); + propDescr.put ("name", new WidgetPropertyDescription (String.class, "Visual name of the property", "")); + propDescr.put ("max", new WidgetPropertyDescription (Double.class, "The maximum value that will be displayed", + Double.valueOf (1.0))); + propDescr.put ("min", new WidgetPropertyDescription (Double.class, + "The minimum value that will be displayed by the widget", Double.valueOf (0))); + propDescr.put ("window", new WidgetPropertyDescription (Integer.class, "The number of samples to display", + Double.valueOf (10))); + propDescr.put ("yLabel", new WidgetPropertyDescription (String.class, "The label to use for the Y axis", "")); + propDescr.put ("threshold", new WidgetPropertyDescription (Double.class, + "The value to display as the threshold", Double.valueOf (-1.0))); + widgetDescription = new WidgetDescription (name, description, type, factory, propDescr); + } + + static WidgetDescription register () { + return widgetDescription; + } + + private Label m_label; + private LineGaugeComponent m_gauge; + + public LineGauge (String mapping) { + super (mapping); + + m_label = new Label (); + m_gauge = new LineGaugeComponent (); + + VerticalLayout layout = new VerticalLayout (); + layout.setWidth ("100%"); + layout.addComponent (m_gauge); + layout.addComponent (m_label); + layout.setExpandRatio (m_gauge, 1.0f); + layout.setComponentAlignment (m_gauge, Alignment.MIDDLE_CENTER); + + getRoot ().addComponent (layout); + } + + @Override + public IWidget getClone () { + LineGauge clone = new LineGauge (mapping); + clone.setProperties (this.getProperties ()); + return clone; + } + + @Override + public void update () { + Double val = 0.0; + try { + val = DataValueSupport.converter.to_java (value, Double.class); + } + catch (ValueConversionException ex) { + try { + val = (double )DataValueSupport.converter.to_java (value, Float.class); + } + catch (ValueConversionException e) { + Logger.getLogger (LineGauge.class.getName ()).log (Level.SEVERE, null, ex); + + } + + } + m_gauge.updateValue (val); + } + + @Override + public WidgetDescription getWidgetDescription () { + return widgetDescription; + } + + @Override + protected void onPropertyUpdate () { + String vName = (String )properties.get ("name"); + m_label.setValue (vName); + } + + @Override + public void activate () { + super.activate (); + m_gauge.configure (this.getProperties ()); + m_gauge.start (); + } + + @Override + public void deactivate () { + super.deactivate (); + m_gauge.stop (); + } + +} diff --git a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/LineGaugeComponent.java b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/LineGaugeComponent.java index da8af7a74..db5031696 100644 --- a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/LineGaugeComponent.java +++ b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/LineGaugeComponent.java @@ -1,40 +1,40 @@ -package edu.cmu.rainbow_ui.display.widgets; - -import java.util.Map; - -import com.vaadin.annotations.JavaScript; -import com.vaadin.ui.AbstractJavaScriptComponent; - -import edu.cmu.rainbow_ui.display.widgets.state.LineGaugeState; - -@JavaScript ({ "http://d3js.org/d3.v2.js", "line-gauge5.js" }) -public class LineGaugeComponent extends AbstractJavaScriptComponent { - - public LineGaugeComponent () { - super (); - } - - public void updateValue (Double val) { - getState ().value = val; - } - - public void configure (Map properties) { - callFunction ("createGauge", "notneeded", properties.get ("name"), properties.get ("min"), - properties.get ("max"), properties.get ("window"), properties.get ("yLabel"), - properties.get ("threshold")); - } - - public void start () { - callFunction ("activate"); - } - - public void stop () { - callFunction ("deactivate"); - } - - @Override - protected LineGaugeState getState () { - return (LineGaugeState )super.getState (); - } - -} +package edu.cmu.rainbow_ui.display.widgets; + +import java.util.Map; + +import com.vaadin.annotations.JavaScript; +import com.vaadin.ui.AbstractJavaScriptComponent; + +import edu.cmu.rainbow_ui.display.widgets.state.LineGaugeState; + +@JavaScript ({ "http://d3js.org/d3.v2.js", "line-gauge5.js" }) +public class LineGaugeComponent extends AbstractJavaScriptComponent { + + public LineGaugeComponent () { + super (); + } + + public void updateValue (Double val) { + getState ().value = val; + } + + public void configure (Map properties) { + callFunction ("createGauge", "notneeded", properties.get ("name"), properties.get ("min"), + properties.get ("max"), properties.get ("window"), properties.get ("yLabel"), + properties.get ("threshold")); + } + + public void start () { + callFunction ("activate"); + } + + public void stop () { + callFunction ("deactivate"); + } + + @Override + protected LineGaugeState getState () { + return (LineGaugeState )super.getState (); + } + +} diff --git a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/Tachometer.java b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/Tachometer.java index 9da085610..66f598139 100644 --- a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/Tachometer.java +++ b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/Tachometer.java @@ -1,102 +1,102 @@ -package edu.cmu.rainbow_ui.display.widgets; - -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.vaadin.annotations.JavaScript; - -import edu.cmu.cs.able.typelib.jconv.ValueConversionException; -import edu.cmu.rainbow_ui.common.DataValueSupport; -import edu.cmu.rainbow_ui.display.widgets.state.TachometerState; - -@JavaScript ({ "http://d3js.org/d3.v2.js", "gauge4.js" }) -public class Tachometer extends JSWidget { - - private static final WidgetDescription widgetDescription; - private String visualName = ""; - - static { - String name = "Tachometer"; - String description = "Shows a tachometer display of a value"; - String type = "float"; - WidgetFactory factory = new WidgetFactory () { - - @Override - public IWidget getInstance (String mapping) { - return new Tachometer (mapping); - } - }; - Map propDescr = new HashMap<> (); - propDescr.put ("name", new WidgetPropertyDescription (String.class, "Visual name of the property", "")); - propDescr.put ("max", new WidgetPropertyDescription (Double.class, "The maximum value that will be displayed", - Double.valueOf (1.0))); - propDescr.put ("min", new WidgetPropertyDescription (Double.class, - "The minimum value that will be displayed by the widget", Double.valueOf (0))); - propDescr.put ("startYellow", new WidgetPropertyDescription (Integer.class, - "The percentage at which the value displayed will be yellow", Integer.valueOf (-1))); // No yellow zone by default - propDescr.put ("startRed", new WidgetPropertyDescription (Integer.class, - "The percentage at which the value will go into red", Integer.valueOf (90))); - widgetDescription = new WidgetDescription (name, description, type, factory, propDescr); - - } - - static WidgetDescription register () { - return widgetDescription; - } - - public Tachometer (String mapping) { - super (mapping); - } - - @Override - public IWidget getClone () { - Tachometer clone = new Tachometer (mapping); - clone.setProperties (this.getProperties ()); - return clone; - } - - @Override - public void update () { - try { - Float val; - try { - val = DataValueSupport.converter.to_java (value, Float.class); - } - catch (ValueConversionException e) { - val = (float )DataValueSupport.converter.to_java (value, Integer.class); - } - - getState ().value = val; - } - catch (ValueConversionException e) { - Logger.getLogger (Tachometer.class.getName ()).log (Level.SEVERE, null, e); - } - - } - - @Override - protected TachometerState getState () { - return (TachometerState )super.getState (); - } - - @Override - public WidgetDescription getWidgetDescription () { - return widgetDescription; - } - - @Override - protected void onPropertyUpdate () { - // Do this later; can the javascript update? - } - - - @Override - protected void configure () { - callFunction ("createGauge", "notneeded", getProperty ("name"), getProperty ("min"), getProperty ("max"), - ((Integer )getProperty ("startRed")) / 100.0, ((Integer )getProperty ("startYellow")) / 100.0); - super.configure (); - } - -} +package edu.cmu.rainbow_ui.display.widgets; + +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.vaadin.annotations.JavaScript; + +import edu.cmu.cs.able.typelib.jconv.ValueConversionException; +import edu.cmu.rainbow_ui.common.DataValueSupport; +import edu.cmu.rainbow_ui.display.widgets.state.TachometerState; + +@JavaScript ({ "http://d3js.org/d3.v2.js", "gauge4.js" }) +public class Tachometer extends JSWidget { + + private static final WidgetDescription widgetDescription; + private String visualName = ""; + + static { + String name = "Tachometer"; + String description = "Shows a tachometer display of a value"; + String type = "float"; + WidgetFactory factory = new WidgetFactory () { + + @Override + public IWidget getInstance (String mapping) { + return new Tachometer (mapping); + } + }; + Map propDescr = new HashMap<> (); + propDescr.put ("name", new WidgetPropertyDescription (String.class, "Visual name of the property", "")); + propDescr.put ("max", new WidgetPropertyDescription (Double.class, "The maximum value that will be displayed", + Double.valueOf (1.0))); + propDescr.put ("min", new WidgetPropertyDescription (Double.class, + "The minimum value that will be displayed by the widget", Double.valueOf (0))); + propDescr.put ("startYellow", new WidgetPropertyDescription (Integer.class, + "The percentage at which the value displayed will be yellow", Integer.valueOf (-1))); // No yellow zone by default + propDescr.put ("startRed", new WidgetPropertyDescription (Integer.class, + "The percentage at which the value will go into red", Integer.valueOf (90))); + widgetDescription = new WidgetDescription (name, description, type, factory, propDescr); + + } + + static WidgetDescription register () { + return widgetDescription; + } + + public Tachometer (String mapping) { + super (mapping); + } + + @Override + public IWidget getClone () { + Tachometer clone = new Tachometer (mapping); + clone.setProperties (this.getProperties ()); + return clone; + } + + @Override + public void update () { + try { + Float val; + try { + val = DataValueSupport.converter.to_java (value, Float.class); + } + catch (ValueConversionException e) { + val = (float )DataValueSupport.converter.to_java (value, Integer.class); + } + + getState ().value = val; + } + catch (ValueConversionException e) { + Logger.getLogger (Tachometer.class.getName ()).log (Level.SEVERE, null, e); + } + + } + + @Override + protected TachometerState getState () { + return (TachometerState )super.getState (); + } + + @Override + public WidgetDescription getWidgetDescription () { + return widgetDescription; + } + + @Override + protected void onPropertyUpdate () { + // Do this later; can the javascript update? + } + + + @Override + protected void configure () { + callFunction ("createGauge", "notneeded", getProperty ("name"), getProperty ("min"), getProperty ("max"), + ((Integer )getProperty ("startRed")) / 100.0, ((Integer )getProperty ("startYellow")) / 100.0); + super.configure (); + } + +} diff --git a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/TrinaryLED.java b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/TrinaryLED.java index f2f14c7b6..bd84a6353 100644 --- a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/TrinaryLED.java +++ b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/TrinaryLED.java @@ -1,80 +1,80 @@ -package edu.cmu.rainbow_ui.display.widgets; - -import java.util.Map; - -import com.google.gwt.dev.util.collect.HashMap; -import com.vaadin.server.Page; -import com.vaadin.server.Page.Styles; - -import edu.cmu.rainbow_ui.common.DataValueSupport; - -public class TrinaryLED extends BooleanLED { - - private static final WidgetDescription widgetDescription; - - static { - String name = "3 color LED"; - String description = "An LED that displays a value (integer) as a color"; - String type = "integer"; - WidgetFactory factory = new WidgetFactory () { - - @Override - public IWidget getInstance (String mapping) { - return new BooleanLED (mapping); - } - }; - - Map propDescr = new HashMap<> (); - propDescr.put ("name", new WidgetPropertyDescription (String.class, "Visual name of the property", "")); - propDescr.put ("greenValue", new WidgetPropertyDescription (Integer.class, - "Boolean value that should show green", 1)); - propDescr.put ("redValue", - new WidgetPropertyDescription (Integer.class, "Boolean value that should be red", -1)); - propDescr.put ("whiteValue", new WidgetPropertyDescription (Integer.class, "Boolean value that should be red", - 0)); - widgetDescription = new WidgetDescription (name, description, type, factory, propDescr); - } - - public static WidgetDescription register () { - return widgetDescription; - } - - public TrinaryLED (String mapping) { - super (mapping); - Styles styles = Page.getCurrent ().getStyles (); - styles.add (".rainbow-theme .led-white {background : white;}"); - - } - - @Override - public WidgetDescription getWidgetDescription () { - return widgetDescription; - } - - @Override - public void update () { - int val; - try { - val = DataValueSupport.converter.to_java (value, Integer.class); - } - catch (Throwable e) { - val = 0; - } - int redValue = (Integer )getProperty ("redValue"); - int greenValue = (Integer )getProperty ("greenValue"); - int whiteValue = (Integer )getProperty ("whiteValue"); - led.removeStyleName ("led-green"); - led.removeStyleName ("led-red"); - led.removeStyleName ("led-white"); - if (redValue == val) { - led.addStyleName ("led-red"); - } - if (greenValue == val) { - led.addStyleName ("led-green"); - } - if (whiteValue == val) { - led.addStyleName ("led-white"); - } - } - -} +package edu.cmu.rainbow_ui.display.widgets; + +import java.util.Map; + +import com.google.gwt.dev.util.collect.HashMap; +import com.vaadin.server.Page; +import com.vaadin.server.Page.Styles; + +import edu.cmu.rainbow_ui.common.DataValueSupport; + +public class TrinaryLED extends BooleanLED { + + private static final WidgetDescription widgetDescription; + + static { + String name = "3 color LED"; + String description = "An LED that displays a value (integer) as a color"; + String type = "integer"; + WidgetFactory factory = new WidgetFactory () { + + @Override + public IWidget getInstance (String mapping) { + return new BooleanLED (mapping); + } + }; + + Map propDescr = new HashMap<> (); + propDescr.put ("name", new WidgetPropertyDescription (String.class, "Visual name of the property", "")); + propDescr.put ("greenValue", new WidgetPropertyDescription (Integer.class, + "Boolean value that should show green", 1)); + propDescr.put ("redValue", + new WidgetPropertyDescription (Integer.class, "Boolean value that should be red", -1)); + propDescr.put ("whiteValue", new WidgetPropertyDescription (Integer.class, "Boolean value that should be red", + 0)); + widgetDescription = new WidgetDescription (name, description, type, factory, propDescr); + } + + public static WidgetDescription register () { + return widgetDescription; + } + + public TrinaryLED (String mapping) { + super (mapping); + Styles styles = Page.getCurrent ().getStyles (); + styles.add (".rainbow-theme .led-white {background : white;}"); + + } + + @Override + public WidgetDescription getWidgetDescription () { + return widgetDescription; + } + + @Override + public void update () { + int val; + try { + val = DataValueSupport.converter.to_java (value, Integer.class); + } + catch (Throwable e) { + val = 0; + } + int redValue = (Integer )getProperty ("redValue"); + int greenValue = (Integer )getProperty ("greenValue"); + int whiteValue = (Integer )getProperty ("whiteValue"); + led.removeStyleName ("led-green"); + led.removeStyleName ("led-red"); + led.removeStyleName ("led-white"); + if (redValue == val) { + led.addStyleName ("led-red"); + } + if (greenValue == val) { + led.addStyleName ("led-green"); + } + if (whiteValue == val) { + led.addStyleName ("led-white"); + } + } + +} diff --git a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/state/LineGaugeState.java b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/state/LineGaugeState.java index c6657757b..a2995ca37 100644 --- a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/state/LineGaugeState.java +++ b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/state/LineGaugeState.java @@ -1,7 +1,7 @@ -package edu.cmu.rainbow_ui.display.widgets.state; - -import com.vaadin.shared.ui.JavaScriptComponentState; - -public class LineGaugeState extends JavaScriptComponentState { - public double value; -} +package edu.cmu.rainbow_ui.display.widgets.state; + +import com.vaadin.shared.ui.JavaScriptComponentState; + +public class LineGaugeState extends JavaScriptComponentState { + public double value; +} diff --git a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/state/TachometerState.java b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/state/TachometerState.java index 3a6864c7e..ad309fdbc 100644 --- a/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/state/TachometerState.java +++ b/ide/rainbow-ui-framework/src/main/java/edu/cmu/rainbow_ui/display/widgets/state/TachometerState.java @@ -1,9 +1,9 @@ -package edu.cmu.rainbow_ui.display.widgets.state; - -import com.vaadin.shared.ui.JavaScriptComponentState; - -public class TachometerState extends JavaScriptComponentState { - - public float value; - -} +package edu.cmu.rainbow_ui.display.widgets.state; + +import com.vaadin.shared.ui.JavaScriptComponentState; + +public class TachometerState extends JavaScriptComponentState { + + public float value; + +} diff --git a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/gauge4.js b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/gauge4.js index 57c42e576..4ba262e32 100644 --- a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/gauge4.js +++ b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/gauge4.js @@ -1,292 +1,292 @@ -function Gauge(placeholderName, configuration) { - this.placeholderName = placeholderName; - - var self = this; // for internal d3 functions - - this.configure = function(configuration) { - this.config = configuration; - - this.config.size = this.config.size * 0.9; - - this.config.raduis = this.config.size * 0.97 / 2; - this.config.cx = this.config.size / 2; - this.config.cy = this.config.size / 2; - - this.config.min = undefined != configuration.min ? configuration.min - : 0; - this.config.max = undefined != configuration.max ? configuration.max - : 100; - this.config.range = this.config.max - this.config.min; - - this.config.majorTicks = configuration.majorTicks || 5; - this.config.minorTicks = configuration.minorTicks || 2; - - this.config.greenColor = configuration.greenColor || "#109618"; - this.config.yellowColor = configuration.yellowColor || "#FF9900"; - this.config.redColor = configuration.redColor || "#DC3912"; - - this.config.transitionDuration = configuration.transitionDuration || 500; - } - - this.render = function() { - - if (typeof this.placeholderName == "string") { - this.body = d3.select("#" + this.placeholderName).append("svg:svg") - .attr("class", "gauge").attr("width", this.config.size).attr( - "height", this.config.size); - } - else { - this.body = d3.select (this.placeholderName).append ("svg:svg").attr("class", "gauge"). - attr ("width", this.config.size).attr ("height", this.config.size); - } - - - this.body.append("svg:circle").attr("cx", this.config.cx).attr("cy", - this.config.cy).attr("r", this.config.raduis).style("fill", - "#ccc").style("stroke", "#000").style("stroke-width", "0.5px"); - - this.body.append("svg:circle").attr("cx", this.config.cx).attr("cy", - this.config.cy).attr("r", 0.9 * this.config.raduis).style( - "fill", "#fff").style("stroke", "#e0e0e0").style( - "stroke-width", "2px"); - - for ( var index in this.config.greenZones) { - this.drawBand(this.config.greenZones[index].from, - this.config.greenZones[index].to, self.config.greenColor); - } - - for ( var index in this.config.yellowZones) { - this.drawBand(this.config.yellowZones[index].from, - this.config.yellowZones[index].to, self.config.yellowColor); - } - - for ( var index in this.config.redZones) { - this.drawBand(this.config.redZones[index].from, - this.config.redZones[index].to, self.config.redColor); - } - - if (undefined != this.config.label) { - var fontSize = Math.round(this.config.size / 9); - this.body.append("svg:text").attr("x", this.config.cx).attr("y", - this.config.cy / 2 + fontSize / 2).attr("dy", fontSize / 2) - .attr("text-anchor", "middle").text(this.config.label) - .style("font-size", fontSize + "px").style("fill", "#333") - .style("stroke-width", "0px"); - } - - var fontSize = Math.round(this.config.size / 16); - var majorDelta = this.config.range / (this.config.majorTicks - 1); - for (var major = this.config.min; major <= this.config.max; major += majorDelta) { - var minorDelta = majorDelta / this.config.minorTicks; - for (var minor = major + minorDelta; minor < Math.min(major - + majorDelta, this.config.max); minor += minorDelta) { - var point1 = this.valueToPoint(minor, 0.75); - var point2 = this.valueToPoint(minor, 0.85); - - this.body.append("svg:line").attr("x1", point1.x).attr("y1", - point1.y).attr("x2", point2.x).attr("y2", point2.y) - .style("stroke", "#666").style("stroke-width", "1px"); - } - - var point1 = this.valueToPoint(major, 0.7); - var point2 = this.valueToPoint(major, 0.85); - - this.body.append("svg:line").attr("x1", point1.x).attr("y1", - point1.y).attr("x2", point2.x).attr("y2", point2.y).style( - "stroke", "#333").style("stroke-width", "2px"); - - if (major == this.config.min || major == this.config.max) { - var point = this.valueToPoint(major, 0.63); - - this.body.append("svg:text").attr("x", point.x).attr("y", - point.y).attr("dy", fontSize / 3).attr("text-anchor", - major == this.config.min ? "start" : "end").text(major) - .style("font-size", fontSize + "px").style("fill", - "#333").style("stroke-width", "0px"); - } - } - - var pointerContainer = this.body.append("svg:g").attr("class", - "pointerContainer"); - - var midValue = (this.config.min + this.config.max) / 2; - - var pointerPath = this.buildPointerPath(midValue); - - var pointerLine = d3.svg.line().x(function(d) { - return d.x - }).y(function(d) { - return d.y - }).interpolate("basis"); - - pointerContainer.selectAll("path").data([ pointerPath ]).enter() - .append("svg:path").attr("d", pointerLine).style("fill", - "#dc3912").style("stroke", "#c63310").style( - "fill-opacity", 0.7) - - pointerContainer.append("svg:circle").attr("cx", this.config.cx).attr( - "cy", this.config.cy).attr("r", 0.12 * this.config.raduis) - .style("fill", "#4684EE").style("stroke", "#666").style( - "opacity", 1); - - var fontSize = Math.round(this.config.size / 10); - pointerContainer.selectAll("text").data([ midValue ]).enter().append( - "svg:text").attr("x", this.config.cx).attr("y", - this.config.size - this.config.cy / 4 - fontSize).attr("dy", - fontSize / 2).attr("text-anchor", "middle").style("font-size", - fontSize + "px").style("fill", "#000").style("stroke-width", - "0px"); - - this.redraw(this.config.min, 0); - } - - this.buildPointerPath = function(value) { - var delta = this.config.range / 13; - - var head = valueToPoint(value, 0.85); - var head1 = valueToPoint(value - delta, 0.12); - var head2 = valueToPoint(value + delta, 0.12); - - var tailValue = value - (this.config.range * (1 / (270 / 360)) / 2); - var tail = valueToPoint(tailValue, 0.28); - var tail1 = valueToPoint(tailValue - delta, 0.12); - var tail2 = valueToPoint(tailValue + delta, 0.12); - - return [ head, head1, tail2, tail, tail1, head2, head ]; - - function valueToPoint(value, factor) { - var point = self.valueToPoint(value, factor); - point.x -= self.config.cx; - point.y -= self.config.cy; - return point; - } - } - - this.drawBand = function(start, end, color) { - if (0 >= end - start) - return; - - this.body.append("svg:path").style("fill", color).attr( - "d", - d3.svg.arc().startAngle(this.valueToRadians(start)).endAngle( - this.valueToRadians(end)).innerRadius( - 0.65 * this.config.raduis).outerRadius( - 0.85 * this.config.raduis)).attr( - "transform", - function() { - return "translate(" + self.config.cx + ", " - + self.config.cy + ") rotate(270)" - }); - } - - this.redraw = function(value, transitionDuration) { - var pointerContainer = this.body.select(".pointerContainer"); - - pointerContainer.selectAll("text").text(Math.round(value)); - - var pointer = pointerContainer.selectAll("path"); - pointer.transition().duration( - undefined != transitionDuration ? transitionDuration - : this.config.transitionDuration) - // .delay(0) - // .ease("linear") - // .attr("transform", function(d) - .attrTween( - "transform", - function() { - var pointerValue = value; - if (value > self.config.max) - pointerValue = self.config.max + 0.02 - * self.config.range; - else if (value < self.config.min) - pointerValue = self.config.min - 0.02 - * self.config.range; - var targetRotation = (self - .valueToDegrees(pointerValue) - 90); - var currentRotation = self._currentRotation - || targetRotation; - self._currentRotation = targetRotation; - - return function(step) { - var rotation = currentRotation - + (targetRotation - currentRotation) - * step; - return "translate(" + self.config.cx + ", " - + self.config.cy + ") rotate(" - + rotation + ")"; - } - }); - } - - this.valueToDegrees = function(value) { - // thanks @closealert - // return value / this.config.range * 270 - 45; - return value / this.config.range * 270 - - (this.config.min / this.config.range * 270 + 45); - } - - this.valueToRadians = function(value) { - return this.valueToDegrees(value) * Math.PI / 180; - } - - this.valueToPoint = function(value, factor) { - return { - x : this.config.cx - this.config.raduis * factor - * Math.cos(this.valueToRadians(value)), - y : this.config.cy - this.config.raduis * factor - * Math.sin(this.valueToRadians(value)) - }; - } - - // initialization - this.configure(configuration); -} - -window.edu_cmu_rainbow_ui_display_widgets_Tachometer = function() { - var element = this.getElement(); - - var gauge; - - this.onStateChange = function() { - if (gauge) - gauge.redraw(this.getState().value); - } - - this.createGauge = function(name, label, min, max, red, yellow, editable) { - - var config = { - size : 60, - label : label, - min : undefined != min ? min : 0, - max : undefined != max ? max : 100, - minorTicks : 5 - } - if (editable) { - config.editFun = updateValueGen(name); - config.reference = label; - } - - var range = config.max - config.min; - var tRed = 0.9; - var tYellow = 0.75; - if (red) { - if (red > 0 && red <= 1) - tRed = red; - } - if (yellow) { - if (yellow > 0 && yellow <= 1) - tYellow = yellow; - } - config.redZones = [ { - from : config.min + range * tRed, - to : config.max - } ]; - config.yellowZones = [ { - from : config.min + range * tYellow, - to : config.redZones[0].from - } ]; - - gauge = new Gauge(element, config); - gauge.render(); - } +function Gauge(placeholderName, configuration) { + this.placeholderName = placeholderName; + + var self = this; // for internal d3 functions + + this.configure = function(configuration) { + this.config = configuration; + + this.config.size = this.config.size * 0.9; + + this.config.raduis = this.config.size * 0.97 / 2; + this.config.cx = this.config.size / 2; + this.config.cy = this.config.size / 2; + + this.config.min = undefined != configuration.min ? configuration.min + : 0; + this.config.max = undefined != configuration.max ? configuration.max + : 100; + this.config.range = this.config.max - this.config.min; + + this.config.majorTicks = configuration.majorTicks || 5; + this.config.minorTicks = configuration.minorTicks || 2; + + this.config.greenColor = configuration.greenColor || "#109618"; + this.config.yellowColor = configuration.yellowColor || "#FF9900"; + this.config.redColor = configuration.redColor || "#DC3912"; + + this.config.transitionDuration = configuration.transitionDuration || 500; + } + + this.render = function() { + + if (typeof this.placeholderName == "string") { + this.body = d3.select("#" + this.placeholderName).append("svg:svg") + .attr("class", "gauge").attr("width", this.config.size).attr( + "height", this.config.size); + } + else { + this.body = d3.select (this.placeholderName).append ("svg:svg").attr("class", "gauge"). + attr ("width", this.config.size).attr ("height", this.config.size); + } + + + this.body.append("svg:circle").attr("cx", this.config.cx).attr("cy", + this.config.cy).attr("r", this.config.raduis).style("fill", + "#ccc").style("stroke", "#000").style("stroke-width", "0.5px"); + + this.body.append("svg:circle").attr("cx", this.config.cx).attr("cy", + this.config.cy).attr("r", 0.9 * this.config.raduis).style( + "fill", "#fff").style("stroke", "#e0e0e0").style( + "stroke-width", "2px"); + + for ( var index in this.config.greenZones) { + this.drawBand(this.config.greenZones[index].from, + this.config.greenZones[index].to, self.config.greenColor); + } + + for ( var index in this.config.yellowZones) { + this.drawBand(this.config.yellowZones[index].from, + this.config.yellowZones[index].to, self.config.yellowColor); + } + + for ( var index in this.config.redZones) { + this.drawBand(this.config.redZones[index].from, + this.config.redZones[index].to, self.config.redColor); + } + + if (undefined != this.config.label) { + var fontSize = Math.round(this.config.size / 9); + this.body.append("svg:text").attr("x", this.config.cx).attr("y", + this.config.cy / 2 + fontSize / 2).attr("dy", fontSize / 2) + .attr("text-anchor", "middle").text(this.config.label) + .style("font-size", fontSize + "px").style("fill", "#333") + .style("stroke-width", "0px"); + } + + var fontSize = Math.round(this.config.size / 16); + var majorDelta = this.config.range / (this.config.majorTicks - 1); + for (var major = this.config.min; major <= this.config.max; major += majorDelta) { + var minorDelta = majorDelta / this.config.minorTicks; + for (var minor = major + minorDelta; minor < Math.min(major + + majorDelta, this.config.max); minor += minorDelta) { + var point1 = this.valueToPoint(minor, 0.75); + var point2 = this.valueToPoint(minor, 0.85); + + this.body.append("svg:line").attr("x1", point1.x).attr("y1", + point1.y).attr("x2", point2.x).attr("y2", point2.y) + .style("stroke", "#666").style("stroke-width", "1px"); + } + + var point1 = this.valueToPoint(major, 0.7); + var point2 = this.valueToPoint(major, 0.85); + + this.body.append("svg:line").attr("x1", point1.x).attr("y1", + point1.y).attr("x2", point2.x).attr("y2", point2.y).style( + "stroke", "#333").style("stroke-width", "2px"); + + if (major == this.config.min || major == this.config.max) { + var point = this.valueToPoint(major, 0.63); + + this.body.append("svg:text").attr("x", point.x).attr("y", + point.y).attr("dy", fontSize / 3).attr("text-anchor", + major == this.config.min ? "start" : "end").text(major) + .style("font-size", fontSize + "px").style("fill", + "#333").style("stroke-width", "0px"); + } + } + + var pointerContainer = this.body.append("svg:g").attr("class", + "pointerContainer"); + + var midValue = (this.config.min + this.config.max) / 2; + + var pointerPath = this.buildPointerPath(midValue); + + var pointerLine = d3.svg.line().x(function(d) { + return d.x + }).y(function(d) { + return d.y + }).interpolate("basis"); + + pointerContainer.selectAll("path").data([ pointerPath ]).enter() + .append("svg:path").attr("d", pointerLine).style("fill", + "#dc3912").style("stroke", "#c63310").style( + "fill-opacity", 0.7) + + pointerContainer.append("svg:circle").attr("cx", this.config.cx).attr( + "cy", this.config.cy).attr("r", 0.12 * this.config.raduis) + .style("fill", "#4684EE").style("stroke", "#666").style( + "opacity", 1); + + var fontSize = Math.round(this.config.size / 10); + pointerContainer.selectAll("text").data([ midValue ]).enter().append( + "svg:text").attr("x", this.config.cx).attr("y", + this.config.size - this.config.cy / 4 - fontSize).attr("dy", + fontSize / 2).attr("text-anchor", "middle").style("font-size", + fontSize + "px").style("fill", "#000").style("stroke-width", + "0px"); + + this.redraw(this.config.min, 0); + } + + this.buildPointerPath = function(value) { + var delta = this.config.range / 13; + + var head = valueToPoint(value, 0.85); + var head1 = valueToPoint(value - delta, 0.12); + var head2 = valueToPoint(value + delta, 0.12); + + var tailValue = value - (this.config.range * (1 / (270 / 360)) / 2); + var tail = valueToPoint(tailValue, 0.28); + var tail1 = valueToPoint(tailValue - delta, 0.12); + var tail2 = valueToPoint(tailValue + delta, 0.12); + + return [ head, head1, tail2, tail, tail1, head2, head ]; + + function valueToPoint(value, factor) { + var point = self.valueToPoint(value, factor); + point.x -= self.config.cx; + point.y -= self.config.cy; + return point; + } + } + + this.drawBand = function(start, end, color) { + if (0 >= end - start) + return; + + this.body.append("svg:path").style("fill", color).attr( + "d", + d3.svg.arc().startAngle(this.valueToRadians(start)).endAngle( + this.valueToRadians(end)).innerRadius( + 0.65 * this.config.raduis).outerRadius( + 0.85 * this.config.raduis)).attr( + "transform", + function() { + return "translate(" + self.config.cx + ", " + + self.config.cy + ") rotate(270)" + }); + } + + this.redraw = function(value, transitionDuration) { + var pointerContainer = this.body.select(".pointerContainer"); + + pointerContainer.selectAll("text").text(Math.round(value)); + + var pointer = pointerContainer.selectAll("path"); + pointer.transition().duration( + undefined != transitionDuration ? transitionDuration + : this.config.transitionDuration) + // .delay(0) + // .ease("linear") + // .attr("transform", function(d) + .attrTween( + "transform", + function() { + var pointerValue = value; + if (value > self.config.max) + pointerValue = self.config.max + 0.02 + * self.config.range; + else if (value < self.config.min) + pointerValue = self.config.min - 0.02 + * self.config.range; + var targetRotation = (self + .valueToDegrees(pointerValue) - 90); + var currentRotation = self._currentRotation + || targetRotation; + self._currentRotation = targetRotation; + + return function(step) { + var rotation = currentRotation + + (targetRotation - currentRotation) + * step; + return "translate(" + self.config.cx + ", " + + self.config.cy + ") rotate(" + + rotation + ")"; + } + }); + } + + this.valueToDegrees = function(value) { + // thanks @closealert + // return value / this.config.range * 270 - 45; + return value / this.config.range * 270 + - (this.config.min / this.config.range * 270 + 45); + } + + this.valueToRadians = function(value) { + return this.valueToDegrees(value) * Math.PI / 180; + } + + this.valueToPoint = function(value, factor) { + return { + x : this.config.cx - this.config.raduis * factor + * Math.cos(this.valueToRadians(value)), + y : this.config.cy - this.config.raduis * factor + * Math.sin(this.valueToRadians(value)) + }; + } + + // initialization + this.configure(configuration); +} + +window.edu_cmu_rainbow_ui_display_widgets_Tachometer = function() { + var element = this.getElement(); + + var gauge; + + this.onStateChange = function() { + if (gauge) + gauge.redraw(this.getState().value); + } + + this.createGauge = function(name, label, min, max, red, yellow, editable) { + + var config = { + size : 60, + label : label, + min : undefined != min ? min : 0, + max : undefined != max ? max : 100, + minorTicks : 5 + } + if (editable) { + config.editFun = updateValueGen(name); + config.reference = label; + } + + var range = config.max - config.min; + var tRed = 0.9; + var tYellow = 0.75; + if (red) { + if (red > 0 && red <= 1) + tRed = red; + } + if (yellow) { + if (yellow > 0 && yellow <= 1) + tYellow = yellow; + } + config.redZones = [ { + from : config.min + range * tRed, + to : config.max + } ]; + config.yellowZones = [ { + from : config.min + range * tYellow, + to : config.redZones[0].from + } ]; + + gauge = new Gauge(element, config); + gauge.render(); + } } \ No newline at end of file diff --git a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge.js b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge.js index 75f8c7b51..16b08a925 100644 --- a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge.js +++ b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge.js @@ -1,286 +1,286 @@ - function MovingLineGauge (placeholderName, configuration, nextDatum) { - this.placeholderName = placeholderName; - var self = this; - - this.data = []; - - this.configure = function (configuration) { - this.config = configuration; - // The width of the gauge - this.config.width = configuration.width || 100; - // The height of the gauge - this.config.height = configuration.height || 50; - this.config.graphHeight = configuration.height || 50; - // Whether to smooth or not: linear, basis - this.config.interpolation = configuration.smooth?"basis":"linear"; - // Whether to animate the transition each interval - this.config.animate = configuration.animate || false; - // The interval for new values, ms - this.config.interval = configuration.interval || 1000; - // If animating, how long the transition should take - this.config.transition = configuration.transition || this.config.interval; - // The maximum number of values to display - this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); - // The minumum expected value - this.config.min = configuration.min || 0; - // The maximum expected value - this.config.max = configuration.max || 100; - this.config.range = this.config.max - this.config.min; - // Any initial data that should be displayed - if (this.config.initialData != null) { - this.data = this.config.initialData.slice (0); - this.max = Math.max (this.config.max, d3.max(this.data)); - this.min = Math.min (this.config.min, d3.min(this.data)); - } - else { - this.min = this.config.min; - this.max = this.config.max; - } - - if (this.config.label) { - this.config.graphHeight = this.config.graphHeight - 9; - } - - // Set up the x and y scales - // The X scale will fit windowSize values within the width of the - // widget - this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting - // point - // is - // -5 - // so - // the - // first - // value - // doesn't - // show - // and - // slides - // off - // the - // edge - // as - // part - // of - // the - // transition - // The Y scale will fit values min,max within the height - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - } - this.resetYScale = function (max, min) { - this.max = max; - this.min = min; - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - this.drawThreshold (); - } - - this.render = function () { - var div; - if (typeof this.placeholderName == "string") { - div = d3.select("#" + this.placeholderName); - } - else { - div = d3.select (this.placeholderName); - } - this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); - this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); - - - // Create axes and thresholds (todo) - - // Create the line - this.line = d3.svg.line () - // assign the X functino to plot the line - .x (function (d,i) { - return self.xScale(i); - }) - .y (function (d) { - return self.yScale(d); - }) - .interpolate (this.config.interpolation); - // display the line by appending an svg:path element with the data - // line above - this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); - this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); - var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) - .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); - if (this.config.yLabel) { - axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); - } - if (this.config.label) { - this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); - } - this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); - - this.drawThreshold (); - } - - this.drawThreshold = function () { - if (this.config.threshold) { - var threshold = this.graph.selectAll (".threshold"); - if (threshold.empty ()) - this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( - "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - else - threshold - .attr("x1", this.xScale (0)).attr( - "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - - } - } - - - - // Starts the gauge animation (ignored if already started) - this.start = function () { - if (this.timer == null) { - this.timer = setInterval (function() { - var nxt = self.config.nextDatum (); - if (nxt == null && self.data.length > 0) { - self.data.shift (); - } - else if (nxt == null) { - return; - } - else { - if (self.data.length < self.config.windowSize) { - self.data.push(nxt); - } - else { - self.data.shift (); - self.data.push(nxt); - } - } - if (self.config.animate) { - self.redrawWithAnimation (); - } - else { - self.redrawWithoutAnimation (); - } - var currentValue = self.group.select (".MLCurrentValue"); - currentValue.text (self.data.slice(-1)); - - - }, this.config.interval); - } - } - - // Stops the gauge animation (ignored if already started) - this.stop = function () { - if (this.timer != null) { - clearInterval (this.timer); - this.timer == null; - } - } - - this.redrawWithAnimation = function () { - // todo: reset the yscale if the max and mins differ with the new - // data - var max = Math.max (this.config.max, d3.max(this.data)); - var min = Math.min (this.config.min, d3.min (this.data)); - if (max > this.max || min < this.min) { - this.resetYScale (max, min); - } - else if (max <= this.config.max || min >= this.config.min) { - this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); - } - if (this.data.length < this.config.windowSize) { - this.redrawWithoutAnimation (); - } - else { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .attr("transform", "translate(" + this.xScale(1) + ")") // set - // the - // transform - // to - // the - // right - // by - // xScale - // (1) - .attr("d", this.line) // apply the new data values ... but - // the new value is hidden at this - // point off the right of the canvas - .transition () // start the transition to bring in the new - // value - .ease("linear") - .duration (this.config.transition) - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr("transform", "translate(" + this.xScale(0) + ")"); // animate - // a - // slide - // to - // the - // left - // back - // to - // x(0) - // pixels - // to - // reveal - // the - // new - // value - } - - - } - - this.redrawWithoutAnimation = function () { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr ("d", this.line); // apply the new data values - } - - // Initialization - this.configure (configuration); - } - -window.edu_cmu_rainbow_ui_display_widgets_LineGaugeComponent = function () { - var element = this.getElement (); - - var gauge; - - this.onStateChange = function () { - // updates are done with periodic readings of the value using the next data function - } - - this.nextDatum = function () { - return this.getState ().value; - } - - this.createGauge = function (name, label, min, max, window, yLabel, threshold) { - var config = { - width: 100, - height: 50, - interval: 1000, - windowSize: window, - animate:true, - min:min, - max:max, - } - - if (yLabel) config.yLabel = yLabel; - if (threshold && threshold > 0) config.threshold = threshold; - config.nextDatum = this.nextDatum; - - gauge = new MovingLineGauge(element, config); - gauge.render (); - } - - this.deactivate = function () { - if (gauge) - gauge.stop (); - } - - this.activate = function () { - if (gauge) - gauge.start (); - } -} + function MovingLineGauge (placeholderName, configuration, nextDatum) { + this.placeholderName = placeholderName; + var self = this; + + this.data = []; + + this.configure = function (configuration) { + this.config = configuration; + // The width of the gauge + this.config.width = configuration.width || 100; + // The height of the gauge + this.config.height = configuration.height || 50; + this.config.graphHeight = configuration.height || 50; + // Whether to smooth or not: linear, basis + this.config.interpolation = configuration.smooth?"basis":"linear"; + // Whether to animate the transition each interval + this.config.animate = configuration.animate || false; + // The interval for new values, ms + this.config.interval = configuration.interval || 1000; + // If animating, how long the transition should take + this.config.transition = configuration.transition || this.config.interval; + // The maximum number of values to display + this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); + // The minumum expected value + this.config.min = configuration.min || 0; + // The maximum expected value + this.config.max = configuration.max || 100; + this.config.range = this.config.max - this.config.min; + // Any initial data that should be displayed + if (this.config.initialData != null) { + this.data = this.config.initialData.slice (0); + this.max = Math.max (this.config.max, d3.max(this.data)); + this.min = Math.min (this.config.min, d3.min(this.data)); + } + else { + this.min = this.config.min; + this.max = this.config.max; + } + + if (this.config.label) { + this.config.graphHeight = this.config.graphHeight - 9; + } + + // Set up the x and y scales + // The X scale will fit windowSize values within the width of the + // widget + this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting + // point + // is + // -5 + // so + // the + // first + // value + // doesn't + // show + // and + // slides + // off + // the + // edge + // as + // part + // of + // the + // transition + // The Y scale will fit values min,max within the height + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + } + this.resetYScale = function (max, min) { + this.max = max; + this.min = min; + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + this.drawThreshold (); + } + + this.render = function () { + var div; + if (typeof this.placeholderName == "string") { + div = d3.select("#" + this.placeholderName); + } + else { + div = d3.select (this.placeholderName); + } + this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); + this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); + + + // Create axes and thresholds (todo) + + // Create the line + this.line = d3.svg.line () + // assign the X functino to plot the line + .x (function (d,i) { + return self.xScale(i); + }) + .y (function (d) { + return self.yScale(d); + }) + .interpolate (this.config.interpolation); + // display the line by appending an svg:path element with the data + // line above + this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); + this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); + var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) + .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); + if (this.config.yLabel) { + axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); + } + if (this.config.label) { + this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); + } + this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); + + this.drawThreshold (); + } + + this.drawThreshold = function () { + if (this.config.threshold) { + var threshold = this.graph.selectAll (".threshold"); + if (threshold.empty ()) + this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( + "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + else + threshold + .attr("x1", this.xScale (0)).attr( + "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + + } + } + + + + // Starts the gauge animation (ignored if already started) + this.start = function () { + if (this.timer == null) { + this.timer = setInterval (function() { + var nxt = self.config.nextDatum (); + if (nxt == null && self.data.length > 0) { + self.data.shift (); + } + else if (nxt == null) { + return; + } + else { + if (self.data.length < self.config.windowSize) { + self.data.push(nxt); + } + else { + self.data.shift (); + self.data.push(nxt); + } + } + if (self.config.animate) { + self.redrawWithAnimation (); + } + else { + self.redrawWithoutAnimation (); + } + var currentValue = self.group.select (".MLCurrentValue"); + currentValue.text (self.data.slice(-1)); + + + }, this.config.interval); + } + } + + // Stops the gauge animation (ignored if already started) + this.stop = function () { + if (this.timer != null) { + clearInterval (this.timer); + this.timer == null; + } + } + + this.redrawWithAnimation = function () { + // todo: reset the yscale if the max and mins differ with the new + // data + var max = Math.max (this.config.max, d3.max(this.data)); + var min = Math.min (this.config.min, d3.min (this.data)); + if (max > this.max || min < this.min) { + this.resetYScale (max, min); + } + else if (max <= this.config.max || min >= this.config.min) { + this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); + } + if (this.data.length < this.config.windowSize) { + this.redrawWithoutAnimation (); + } + else { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .attr("transform", "translate(" + this.xScale(1) + ")") // set + // the + // transform + // to + // the + // right + // by + // xScale + // (1) + .attr("d", this.line) // apply the new data values ... but + // the new value is hidden at this + // point off the right of the canvas + .transition () // start the transition to bring in the new + // value + .ease("linear") + .duration (this.config.transition) + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr("transform", "translate(" + this.xScale(0) + ")"); // animate + // a + // slide + // to + // the + // left + // back + // to + // x(0) + // pixels + // to + // reveal + // the + // new + // value + } + + + } + + this.redrawWithoutAnimation = function () { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr ("d", this.line); // apply the new data values + } + + // Initialization + this.configure (configuration); + } + +window.edu_cmu_rainbow_ui_display_widgets_LineGaugeComponent = function () { + var element = this.getElement (); + + var gauge; + + this.onStateChange = function () { + // updates are done with periodic readings of the value using the next data function + } + + this.nextDatum = function () { + return this.getState ().value; + } + + this.createGauge = function (name, label, min, max, window, yLabel, threshold) { + var config = { + width: 100, + height: 50, + interval: 1000, + windowSize: window, + animate:true, + min:min, + max:max, + } + + if (yLabel) config.yLabel = yLabel; + if (threshold && threshold > 0) config.threshold = threshold; + config.nextDatum = this.nextDatum; + + gauge = new MovingLineGauge(element, config); + gauge.render (); + } + + this.deactivate = function () { + if (gauge) + gauge.stop (); + } + + this.activate = function () { + if (gauge) + gauge.start (); + } +} diff --git a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge1.js b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge1.js index 3541ed977..2ba482476 100644 --- a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge1.js +++ b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge1.js @@ -1,284 +1,284 @@ - function MovingLineGauge (placeholderName, configuration, nextDatum) { - this.placeholderName = placeholderName; - var self = this; - - this.data = []; - - this.configure = function (configuration) { - this.config = configuration; - // The width of the gauge - this.config.width = configuration.width || 100; - // The height of the gauge - this.config.height = configuration.height || 50; - this.config.graphHeight = configuration.height || 50; - // Whether to smooth or not: linear, basis - this.config.interpolation = configuration.smooth?"basis":"linear"; - // Whether to animate the transition each interval - this.config.animate = configuration.animate || false; - // The interval for new values, ms - this.config.interval = configuration.interval || 1000; - // If animating, how long the transition should take - this.config.transition = configuration.transition || this.config.interval; - // The maximum number of values to display - this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); - // The minumum expected value - this.config.min = configuration.min || 0; - // The maximum expected value - this.config.max = configuration.max || 100; - this.config.range = this.config.max - this.config.min; - // Any initial data that should be displayed - if (this.config.initialData != null) { - this.data = this.config.initialData.slice (0); - this.max = Math.max (this.config.max, d3.max(this.data)); - this.min = Math.min (this.config.min, d3.min(this.data)); - } - else { - this.min = this.config.min; - this.max = this.config.max; - } - - if (this.config.label) { - this.config.graphHeight = this.config.graphHeight - 9; - } - - // Set up the x and y scales - // The X scale will fit windowSize values within the width of the - // widget - this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting - // point - // is - // -5 - // so - // the - // first - // value - // doesn't - // show - // and - // slides - // off - // the - // edge - // as - // part - // of - // the - // transition - // The Y scale will fit values min,max within the height - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - } - this.resetYScale = function (max, min) { - this.max = max; - this.min = min; - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - this.drawThreshold (); - } - - this.render = function () { - var div; - if (typeof this.placeholderName == "string") { - div = d3.select("#" + this.placeholderName); - } - else { - div = d3.select (this.placeholderName); - } - this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); - this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); - - - // Create axes and thresholds (todo) - - // Create the line - this.line = d3.svg.line () - // assign the X functino to plot the line - .x (function (d,i) { - return self.xScale(i); - }) - .y (function (d) { - return self.yScale(d); - }) - .interpolate (this.config.interpolation); - // display the line by appending an svg:path element with the data - // line above - this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); - this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); - var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) - .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); - if (this.config.yLabel) { - axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); - } - if (this.config.label) { - this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); - } - this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); - - this.drawThreshold (); - } - - this.drawThreshold = function () { - if (this.config.threshold) { - var threshold = this.graph.selectAll (".threshold"); - if (threshold.empty ()) - this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( - "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - else - threshold - .attr("x1", this.xScale (0)).attr( - "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - - } - } - - - - // Starts the gauge animation (ignored if already started) - this.start = function () { - if (this.timer == null) { - this.timer = setInterval (function() { - var nxt = nextDatum (); - if (nxt == null && self.data.length > 0) { - self.data.shift (); - } - else if (nxt == null) { - return; - } - else { - if (self.data.length < self.config.windowSize) { - self.data.push(nxt); - } - else { - self.data.shift (); - self.data.push(nxt); - } - } - if (self.config.animate) { - self.redrawWithAnimation (); - } - else { - self.redrawWithoutAnimation (); - } - var currentValue = self.group.select (".MLCurrentValue"); - currentValue.text (self.data.slice(-1)); - - - }, this.config.interval); - } - } - - // Stops the gauge animation (ignored if already started) - this.stop = function () { - if (this.timer != null) { - clearInterval (this.timer); - this.timer == null; - } - } - - this.redrawWithAnimation = function () { - // todo: reset the yscale if the max and mins differ with the new - // data - var max = Math.max (this.config.max, d3.max(this.data)); - var min = Math.min (this.config.min, d3.min (this.data)); - if (max > this.max || min < this.min) { - this.resetYScale (max, min); - } - else if (max <= this.config.max || min >= this.config.min) { - this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); - } - if (this.data.length < this.config.windowSize) { - this.redrawWithoutAnimation (); - } - else { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .attr("transform", "translate(" + this.xScale(1) + ")") // set - // the - // transform - // to - // the - // right - // by - // xScale - // (1) - .attr("d", this.line) // apply the new data values ... but - // the new value is hidden at this - // point off the right of the canvas - .transition () // start the transition to bring in the new - // value - .ease("linear") - .duration (this.config.transition) - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr("transform", "translate(" + this.xScale(0) + ")"); // animate - // a - // slide - // to - // the - // left - // back - // to - // x(0) - // pixels - // to - // reveal - // the - // new - // value - } - - - } - - this.redrawWithoutAnimation = function () { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr ("d", this.line); // apply the new data values - } - - // Initialization - this.configure (configuration); - } - -window.edu_cmu_rainbow_ui_display_widgets_MovingLine = function () { - var element = this.getElement (); - - var gauge; - - this.onStateChange = function () { - if (gauge) - gauge.redraw (this.getState ().value); - } - - this.createGauge = function (name, label, min, max, window, yLabel, threshold) { - var config = { - width: 100, - height: 50, - label: label, - interval: 1000, - windowSize: window, - animate:true, - min:min, - max:max, - } - - if (ylabel) config.yLabel = yLabel; - if (threshold && threshold > 0) config.threshold = threshold; - - - gauge = new MovingLineGauge(element, config); - gauge.render (); - } - - this.deactivate = function () { - if (gauge) - gauge.stop (); - } - - this.activate = function () { - if (gauge) - gauge.start (); - } -} + function MovingLineGauge (placeholderName, configuration, nextDatum) { + this.placeholderName = placeholderName; + var self = this; + + this.data = []; + + this.configure = function (configuration) { + this.config = configuration; + // The width of the gauge + this.config.width = configuration.width || 100; + // The height of the gauge + this.config.height = configuration.height || 50; + this.config.graphHeight = configuration.height || 50; + // Whether to smooth or not: linear, basis + this.config.interpolation = configuration.smooth?"basis":"linear"; + // Whether to animate the transition each interval + this.config.animate = configuration.animate || false; + // The interval for new values, ms + this.config.interval = configuration.interval || 1000; + // If animating, how long the transition should take + this.config.transition = configuration.transition || this.config.interval; + // The maximum number of values to display + this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); + // The minumum expected value + this.config.min = configuration.min || 0; + // The maximum expected value + this.config.max = configuration.max || 100; + this.config.range = this.config.max - this.config.min; + // Any initial data that should be displayed + if (this.config.initialData != null) { + this.data = this.config.initialData.slice (0); + this.max = Math.max (this.config.max, d3.max(this.data)); + this.min = Math.min (this.config.min, d3.min(this.data)); + } + else { + this.min = this.config.min; + this.max = this.config.max; + } + + if (this.config.label) { + this.config.graphHeight = this.config.graphHeight - 9; + } + + // Set up the x and y scales + // The X scale will fit windowSize values within the width of the + // widget + this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting + // point + // is + // -5 + // so + // the + // first + // value + // doesn't + // show + // and + // slides + // off + // the + // edge + // as + // part + // of + // the + // transition + // The Y scale will fit values min,max within the height + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + } + this.resetYScale = function (max, min) { + this.max = max; + this.min = min; + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + this.drawThreshold (); + } + + this.render = function () { + var div; + if (typeof this.placeholderName == "string") { + div = d3.select("#" + this.placeholderName); + } + else { + div = d3.select (this.placeholderName); + } + this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); + this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); + + + // Create axes and thresholds (todo) + + // Create the line + this.line = d3.svg.line () + // assign the X functino to plot the line + .x (function (d,i) { + return self.xScale(i); + }) + .y (function (d) { + return self.yScale(d); + }) + .interpolate (this.config.interpolation); + // display the line by appending an svg:path element with the data + // line above + this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); + this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); + var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) + .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); + if (this.config.yLabel) { + axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); + } + if (this.config.label) { + this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); + } + this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); + + this.drawThreshold (); + } + + this.drawThreshold = function () { + if (this.config.threshold) { + var threshold = this.graph.selectAll (".threshold"); + if (threshold.empty ()) + this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( + "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + else + threshold + .attr("x1", this.xScale (0)).attr( + "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + + } + } + + + + // Starts the gauge animation (ignored if already started) + this.start = function () { + if (this.timer == null) { + this.timer = setInterval (function() { + var nxt = nextDatum (); + if (nxt == null && self.data.length > 0) { + self.data.shift (); + } + else if (nxt == null) { + return; + } + else { + if (self.data.length < self.config.windowSize) { + self.data.push(nxt); + } + else { + self.data.shift (); + self.data.push(nxt); + } + } + if (self.config.animate) { + self.redrawWithAnimation (); + } + else { + self.redrawWithoutAnimation (); + } + var currentValue = self.group.select (".MLCurrentValue"); + currentValue.text (self.data.slice(-1)); + + + }, this.config.interval); + } + } + + // Stops the gauge animation (ignored if already started) + this.stop = function () { + if (this.timer != null) { + clearInterval (this.timer); + this.timer == null; + } + } + + this.redrawWithAnimation = function () { + // todo: reset the yscale if the max and mins differ with the new + // data + var max = Math.max (this.config.max, d3.max(this.data)); + var min = Math.min (this.config.min, d3.min (this.data)); + if (max > this.max || min < this.min) { + this.resetYScale (max, min); + } + else if (max <= this.config.max || min >= this.config.min) { + this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); + } + if (this.data.length < this.config.windowSize) { + this.redrawWithoutAnimation (); + } + else { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .attr("transform", "translate(" + this.xScale(1) + ")") // set + // the + // transform + // to + // the + // right + // by + // xScale + // (1) + .attr("d", this.line) // apply the new data values ... but + // the new value is hidden at this + // point off the right of the canvas + .transition () // start the transition to bring in the new + // value + .ease("linear") + .duration (this.config.transition) + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr("transform", "translate(" + this.xScale(0) + ")"); // animate + // a + // slide + // to + // the + // left + // back + // to + // x(0) + // pixels + // to + // reveal + // the + // new + // value + } + + + } + + this.redrawWithoutAnimation = function () { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr ("d", this.line); // apply the new data values + } + + // Initialization + this.configure (configuration); + } + +window.edu_cmu_rainbow_ui_display_widgets_MovingLine = function () { + var element = this.getElement (); + + var gauge; + + this.onStateChange = function () { + if (gauge) + gauge.redraw (this.getState ().value); + } + + this.createGauge = function (name, label, min, max, window, yLabel, threshold) { + var config = { + width: 100, + height: 50, + label: label, + interval: 1000, + windowSize: window, + animate:true, + min:min, + max:max, + } + + if (ylabel) config.yLabel = yLabel; + if (threshold && threshold > 0) config.threshold = threshold; + + + gauge = new MovingLineGauge(element, config); + gauge.render (); + } + + this.deactivate = function () { + if (gauge) + gauge.stop (); + } + + this.activate = function () { + if (gauge) + gauge.start (); + } +} diff --git a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge2.js b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge2.js index a87e22995..3153e1a0a 100644 --- a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge2.js +++ b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge2.js @@ -1,284 +1,284 @@ - function MovingLineGauge (placeholderName, configuration, nextDatum) { - this.placeholderName = placeholderName; - var self = this; - - this.data = []; - - this.configure = function (configuration) { - this.config = configuration; - // The width of the gauge - this.config.width = configuration.width || 100; - // The height of the gauge - this.config.height = configuration.height || 50; - this.config.graphHeight = configuration.height || 50; - // Whether to smooth or not: linear, basis - this.config.interpolation = configuration.smooth?"basis":"linear"; - // Whether to animate the transition each interval - this.config.animate = configuration.animate || false; - // The interval for new values, ms - this.config.interval = configuration.interval || 1000; - // If animating, how long the transition should take - this.config.transition = configuration.transition || this.config.interval; - // The maximum number of values to display - this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); - // The minumum expected value - this.config.min = configuration.min || 0; - // The maximum expected value - this.config.max = configuration.max || 100; - this.config.range = this.config.max - this.config.min; - // Any initial data that should be displayed - if (this.config.initialData != null) { - this.data = this.config.initialData.slice (0); - this.max = Math.max (this.config.max, d3.max(this.data)); - this.min = Math.min (this.config.min, d3.min(this.data)); - } - else { - this.min = this.config.min; - this.max = this.config.max; - } - - if (this.config.label) { - this.config.graphHeight = this.config.graphHeight - 9; - } - - // Set up the x and y scales - // The X scale will fit windowSize values within the width of the - // widget - this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting - // point - // is - // -5 - // so - // the - // first - // value - // doesn't - // show - // and - // slides - // off - // the - // edge - // as - // part - // of - // the - // transition - // The Y scale will fit values min,max within the height - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - } - this.resetYScale = function (max, min) { - this.max = max; - this.min = min; - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - this.drawThreshold (); - } - - this.render = function () { - var div; - if (typeof this.placeholderName == "string") { - div = d3.select("#" + this.placeholderName); - } - else { - div = d3.select (this.placeholderName); - } - this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); - this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); - - - // Create axes and thresholds (todo) - - // Create the line - this.line = d3.svg.line () - // assign the X functino to plot the line - .x (function (d,i) { - return self.xScale(i); - }) - .y (function (d) { - return self.yScale(d); - }) - .interpolate (this.config.interpolation); - // display the line by appending an svg:path element with the data - // line above - this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); - this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); - var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) - .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); - if (this.config.yLabel) { - axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); - } - if (this.config.label) { - this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); - } - this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); - - this.drawThreshold (); - } - - this.drawThreshold = function () { - if (this.config.threshold) { - var threshold = this.graph.selectAll (".threshold"); - if (threshold.empty ()) - this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( - "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - else - threshold - .attr("x1", this.xScale (0)).attr( - "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - - } - } - - - - // Starts the gauge animation (ignored if already started) - this.start = function () { - if (this.timer == null) { - this.timer = setInterval (function() { - var nxt = nextDatum (); - if (nxt == null && self.data.length > 0) { - self.data.shift (); - } - else if (nxt == null) { - return; - } - else { - if (self.data.length < self.config.windowSize) { - self.data.push(nxt); - } - else { - self.data.shift (); - self.data.push(nxt); - } - } - if (self.config.animate) { - self.redrawWithAnimation (); - } - else { - self.redrawWithoutAnimation (); - } - var currentValue = self.group.select (".MLCurrentValue"); - currentValue.text (self.data.slice(-1)); - - - }, this.config.interval); - } - } - - // Stops the gauge animation (ignored if already started) - this.stop = function () { - if (this.timer != null) { - clearInterval (this.timer); - this.timer == null; - } - } - - this.redrawWithAnimation = function () { - // todo: reset the yscale if the max and mins differ with the new - // data - var max = Math.max (this.config.max, d3.max(this.data)); - var min = Math.min (this.config.min, d3.min (this.data)); - if (max > this.max || min < this.min) { - this.resetYScale (max, min); - } - else if (max <= this.config.max || min >= this.config.min) { - this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); - } - if (this.data.length < this.config.windowSize) { - this.redrawWithoutAnimation (); - } - else { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .attr("transform", "translate(" + this.xScale(1) + ")") // set - // the - // transform - // to - // the - // right - // by - // xScale - // (1) - .attr("d", this.line) // apply the new data values ... but - // the new value is hidden at this - // point off the right of the canvas - .transition () // start the transition to bring in the new - // value - .ease("linear") - .duration (this.config.transition) - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr("transform", "translate(" + this.xScale(0) + ")"); // animate - // a - // slide - // to - // the - // left - // back - // to - // x(0) - // pixels - // to - // reveal - // the - // new - // value - } - - - } - - this.redrawWithoutAnimation = function () { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr ("d", this.line); // apply the new data values - } - - // Initialization - this.configure (configuration); - } - -window.edu_cmu_rainbow_ui_display_widgets_LineGaugeComponent = function () { - var element = this.getElement (); - - var gauge; - - this.onStateChange = function () { - if (gauge) - gauge.redraw (this.getState ().value); - } - - this.createGauge = function (name, label, min, max, window, yLabel, threshold) { - var config = { - width: 100, - height: 50, - label: label, - interval: 1000, - windowSize: window, - animate:true, - min:min, - max:max, - } - - if (ylabel) config.yLabel = yLabel; - if (threshold && threshold > 0) config.threshold = threshold; - - - gauge = new MovingLineGauge(element, config); - gauge.render (); - } - - this.deactivate = function () { - if (gauge) - gauge.stop (); - } - - this.activate = function () { - if (gauge) - gauge.start (); - } -} + function MovingLineGauge (placeholderName, configuration, nextDatum) { + this.placeholderName = placeholderName; + var self = this; + + this.data = []; + + this.configure = function (configuration) { + this.config = configuration; + // The width of the gauge + this.config.width = configuration.width || 100; + // The height of the gauge + this.config.height = configuration.height || 50; + this.config.graphHeight = configuration.height || 50; + // Whether to smooth or not: linear, basis + this.config.interpolation = configuration.smooth?"basis":"linear"; + // Whether to animate the transition each interval + this.config.animate = configuration.animate || false; + // The interval for new values, ms + this.config.interval = configuration.interval || 1000; + // If animating, how long the transition should take + this.config.transition = configuration.transition || this.config.interval; + // The maximum number of values to display + this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); + // The minumum expected value + this.config.min = configuration.min || 0; + // The maximum expected value + this.config.max = configuration.max || 100; + this.config.range = this.config.max - this.config.min; + // Any initial data that should be displayed + if (this.config.initialData != null) { + this.data = this.config.initialData.slice (0); + this.max = Math.max (this.config.max, d3.max(this.data)); + this.min = Math.min (this.config.min, d3.min(this.data)); + } + else { + this.min = this.config.min; + this.max = this.config.max; + } + + if (this.config.label) { + this.config.graphHeight = this.config.graphHeight - 9; + } + + // Set up the x and y scales + // The X scale will fit windowSize values within the width of the + // widget + this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting + // point + // is + // -5 + // so + // the + // first + // value + // doesn't + // show + // and + // slides + // off + // the + // edge + // as + // part + // of + // the + // transition + // The Y scale will fit values min,max within the height + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + } + this.resetYScale = function (max, min) { + this.max = max; + this.min = min; + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + this.drawThreshold (); + } + + this.render = function () { + var div; + if (typeof this.placeholderName == "string") { + div = d3.select("#" + this.placeholderName); + } + else { + div = d3.select (this.placeholderName); + } + this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); + this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); + + + // Create axes and thresholds (todo) + + // Create the line + this.line = d3.svg.line () + // assign the X functino to plot the line + .x (function (d,i) { + return self.xScale(i); + }) + .y (function (d) { + return self.yScale(d); + }) + .interpolate (this.config.interpolation); + // display the line by appending an svg:path element with the data + // line above + this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); + this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); + var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) + .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); + if (this.config.yLabel) { + axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); + } + if (this.config.label) { + this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); + } + this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); + + this.drawThreshold (); + } + + this.drawThreshold = function () { + if (this.config.threshold) { + var threshold = this.graph.selectAll (".threshold"); + if (threshold.empty ()) + this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( + "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + else + threshold + .attr("x1", this.xScale (0)).attr( + "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + + } + } + + + + // Starts the gauge animation (ignored if already started) + this.start = function () { + if (this.timer == null) { + this.timer = setInterval (function() { + var nxt = nextDatum (); + if (nxt == null && self.data.length > 0) { + self.data.shift (); + } + else if (nxt == null) { + return; + } + else { + if (self.data.length < self.config.windowSize) { + self.data.push(nxt); + } + else { + self.data.shift (); + self.data.push(nxt); + } + } + if (self.config.animate) { + self.redrawWithAnimation (); + } + else { + self.redrawWithoutAnimation (); + } + var currentValue = self.group.select (".MLCurrentValue"); + currentValue.text (self.data.slice(-1)); + + + }, this.config.interval); + } + } + + // Stops the gauge animation (ignored if already started) + this.stop = function () { + if (this.timer != null) { + clearInterval (this.timer); + this.timer == null; + } + } + + this.redrawWithAnimation = function () { + // todo: reset the yscale if the max and mins differ with the new + // data + var max = Math.max (this.config.max, d3.max(this.data)); + var min = Math.min (this.config.min, d3.min (this.data)); + if (max > this.max || min < this.min) { + this.resetYScale (max, min); + } + else if (max <= this.config.max || min >= this.config.min) { + this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); + } + if (this.data.length < this.config.windowSize) { + this.redrawWithoutAnimation (); + } + else { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .attr("transform", "translate(" + this.xScale(1) + ")") // set + // the + // transform + // to + // the + // right + // by + // xScale + // (1) + .attr("d", this.line) // apply the new data values ... but + // the new value is hidden at this + // point off the right of the canvas + .transition () // start the transition to bring in the new + // value + .ease("linear") + .duration (this.config.transition) + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr("transform", "translate(" + this.xScale(0) + ")"); // animate + // a + // slide + // to + // the + // left + // back + // to + // x(0) + // pixels + // to + // reveal + // the + // new + // value + } + + + } + + this.redrawWithoutAnimation = function () { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr ("d", this.line); // apply the new data values + } + + // Initialization + this.configure (configuration); + } + +window.edu_cmu_rainbow_ui_display_widgets_LineGaugeComponent = function () { + var element = this.getElement (); + + var gauge; + + this.onStateChange = function () { + if (gauge) + gauge.redraw (this.getState ().value); + } + + this.createGauge = function (name, label, min, max, window, yLabel, threshold) { + var config = { + width: 100, + height: 50, + label: label, + interval: 1000, + windowSize: window, + animate:true, + min:min, + max:max, + } + + if (ylabel) config.yLabel = yLabel; + if (threshold && threshold > 0) config.threshold = threshold; + + + gauge = new MovingLineGauge(element, config); + gauge.render (); + } + + this.deactivate = function () { + if (gauge) + gauge.stop (); + } + + this.activate = function () { + if (gauge) + gauge.start (); + } +} diff --git a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge3.js b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge3.js index 4a72666bf..dc95fcdd1 100644 --- a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge3.js +++ b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge3.js @@ -1,284 +1,284 @@ - function MovingLineGauge (placeholderName, configuration, nextDatum) { - this.placeholderName = placeholderName; - var self = this; - - this.data = []; - - this.configure = function (configuration) { - this.config = configuration; - // The width of the gauge - this.config.width = configuration.width || 100; - // The height of the gauge - this.config.height = configuration.height || 50; - this.config.graphHeight = configuration.height || 50; - // Whether to smooth or not: linear, basis - this.config.interpolation = configuration.smooth?"basis":"linear"; - // Whether to animate the transition each interval - this.config.animate = configuration.animate || false; - // The interval for new values, ms - this.config.interval = configuration.interval || 1000; - // If animating, how long the transition should take - this.config.transition = configuration.transition || this.config.interval; - // The maximum number of values to display - this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); - // The minumum expected value - this.config.min = configuration.min || 0; - // The maximum expected value - this.config.max = configuration.max || 100; - this.config.range = this.config.max - this.config.min; - // Any initial data that should be displayed - if (this.config.initialData != null) { - this.data = this.config.initialData.slice (0); - this.max = Math.max (this.config.max, d3.max(this.data)); - this.min = Math.min (this.config.min, d3.min(this.data)); - } - else { - this.min = this.config.min; - this.max = this.config.max; - } - - if (this.config.label) { - this.config.graphHeight = this.config.graphHeight - 9; - } - - // Set up the x and y scales - // The X scale will fit windowSize values within the width of the - // widget - this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting - // point - // is - // -5 - // so - // the - // first - // value - // doesn't - // show - // and - // slides - // off - // the - // edge - // as - // part - // of - // the - // transition - // The Y scale will fit values min,max within the height - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - } - this.resetYScale = function (max, min) { - this.max = max; - this.min = min; - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - this.drawThreshold (); - } - - this.render = function () { - var div; - if (typeof this.placeholderName == "string") { - div = d3.select("#" + this.placeholderName); - } - else { - div = d3.select (this.placeholderName); - } - this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); - this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); - - - // Create axes and thresholds (todo) - - // Create the line - this.line = d3.svg.line () - // assign the X functino to plot the line - .x (function (d,i) { - return self.xScale(i); - }) - .y (function (d) { - return self.yScale(d); - }) - .interpolate (this.config.interpolation); - // display the line by appending an svg:path element with the data - // line above - this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); - this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); - var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) - .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); - if (this.config.yLabel) { - axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); - } - if (this.config.label) { - this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); - } - this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); - - this.drawThreshold (); - } - - this.drawThreshold = function () { - if (this.config.threshold) { - var threshold = this.graph.selectAll (".threshold"); - if (threshold.empty ()) - this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( - "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - else - threshold - .attr("x1", this.xScale (0)).attr( - "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - - } - } - - - - // Starts the gauge animation (ignored if already started) - this.start = function () { - if (this.timer == null) { - this.timer = setInterval (function() { - var nxt = nextDatum (); - if (nxt == null && self.data.length > 0) { - self.data.shift (); - } - else if (nxt == null) { - return; - } - else { - if (self.data.length < self.config.windowSize) { - self.data.push(nxt); - } - else { - self.data.shift (); - self.data.push(nxt); - } - } - if (self.config.animate) { - self.redrawWithAnimation (); - } - else { - self.redrawWithoutAnimation (); - } - var currentValue = self.group.select (".MLCurrentValue"); - currentValue.text (self.data.slice(-1)); - - - }, this.config.interval); - } - } - - // Stops the gauge animation (ignored if already started) - this.stop = function () { - if (this.timer != null) { - clearInterval (this.timer); - this.timer == null; - } - } - - this.redrawWithAnimation = function () { - // todo: reset the yscale if the max and mins differ with the new - // data - var max = Math.max (this.config.max, d3.max(this.data)); - var min = Math.min (this.config.min, d3.min (this.data)); - if (max > this.max || min < this.min) { - this.resetYScale (max, min); - } - else if (max <= this.config.max || min >= this.config.min) { - this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); - } - if (this.data.length < this.config.windowSize) { - this.redrawWithoutAnimation (); - } - else { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .attr("transform", "translate(" + this.xScale(1) + ")") // set - // the - // transform - // to - // the - // right - // by - // xScale - // (1) - .attr("d", this.line) // apply the new data values ... but - // the new value is hidden at this - // point off the right of the canvas - .transition () // start the transition to bring in the new - // value - .ease("linear") - .duration (this.config.transition) - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr("transform", "translate(" + this.xScale(0) + ")"); // animate - // a - // slide - // to - // the - // left - // back - // to - // x(0) - // pixels - // to - // reveal - // the - // new - // value - } - - - } - - this.redrawWithoutAnimation = function () { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr ("d", this.line); // apply the new data values - } - - // Initialization - this.configure (configuration); - } - -window.edu_cmu_rainbow_ui_display_widgets_LineGaugeComponent = function () { - var element = this.getElement (); - - var gauge; - - this.onStateChange = function () { - if (gauge) - gauge.redraw (this.getState ().value); - } - - this.createGauge = function (name, label, min, max, window, yLabel, threshold) { - var config = { - width: 100, - height: 50, - label: label, - interval: 1000, - windowSize: window, - animate:true, - min:min, - max:max, - } - - if (yLabel) config.yLabel = yLabel; - if (threshold && threshold > 0) config.threshold = threshold; - - - gauge = new MovingLineGauge(element, config); - gauge.render (); - } - - this.deactivate = function () { - if (gauge) - gauge.stop (); - } - - this.activate = function () { - if (gauge) - gauge.start (); - } -} + function MovingLineGauge (placeholderName, configuration, nextDatum) { + this.placeholderName = placeholderName; + var self = this; + + this.data = []; + + this.configure = function (configuration) { + this.config = configuration; + // The width of the gauge + this.config.width = configuration.width || 100; + // The height of the gauge + this.config.height = configuration.height || 50; + this.config.graphHeight = configuration.height || 50; + // Whether to smooth or not: linear, basis + this.config.interpolation = configuration.smooth?"basis":"linear"; + // Whether to animate the transition each interval + this.config.animate = configuration.animate || false; + // The interval for new values, ms + this.config.interval = configuration.interval || 1000; + // If animating, how long the transition should take + this.config.transition = configuration.transition || this.config.interval; + // The maximum number of values to display + this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); + // The minumum expected value + this.config.min = configuration.min || 0; + // The maximum expected value + this.config.max = configuration.max || 100; + this.config.range = this.config.max - this.config.min; + // Any initial data that should be displayed + if (this.config.initialData != null) { + this.data = this.config.initialData.slice (0); + this.max = Math.max (this.config.max, d3.max(this.data)); + this.min = Math.min (this.config.min, d3.min(this.data)); + } + else { + this.min = this.config.min; + this.max = this.config.max; + } + + if (this.config.label) { + this.config.graphHeight = this.config.graphHeight - 9; + } + + // Set up the x and y scales + // The X scale will fit windowSize values within the width of the + // widget + this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting + // point + // is + // -5 + // so + // the + // first + // value + // doesn't + // show + // and + // slides + // off + // the + // edge + // as + // part + // of + // the + // transition + // The Y scale will fit values min,max within the height + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + } + this.resetYScale = function (max, min) { + this.max = max; + this.min = min; + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + this.drawThreshold (); + } + + this.render = function () { + var div; + if (typeof this.placeholderName == "string") { + div = d3.select("#" + this.placeholderName); + } + else { + div = d3.select (this.placeholderName); + } + this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); + this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); + + + // Create axes and thresholds (todo) + + // Create the line + this.line = d3.svg.line () + // assign the X functino to plot the line + .x (function (d,i) { + return self.xScale(i); + }) + .y (function (d) { + return self.yScale(d); + }) + .interpolate (this.config.interpolation); + // display the line by appending an svg:path element with the data + // line above + this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); + this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); + var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) + .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); + if (this.config.yLabel) { + axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); + } + if (this.config.label) { + this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); + } + this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); + + this.drawThreshold (); + } + + this.drawThreshold = function () { + if (this.config.threshold) { + var threshold = this.graph.selectAll (".threshold"); + if (threshold.empty ()) + this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( + "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + else + threshold + .attr("x1", this.xScale (0)).attr( + "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + + } + } + + + + // Starts the gauge animation (ignored if already started) + this.start = function () { + if (this.timer == null) { + this.timer = setInterval (function() { + var nxt = nextDatum (); + if (nxt == null && self.data.length > 0) { + self.data.shift (); + } + else if (nxt == null) { + return; + } + else { + if (self.data.length < self.config.windowSize) { + self.data.push(nxt); + } + else { + self.data.shift (); + self.data.push(nxt); + } + } + if (self.config.animate) { + self.redrawWithAnimation (); + } + else { + self.redrawWithoutAnimation (); + } + var currentValue = self.group.select (".MLCurrentValue"); + currentValue.text (self.data.slice(-1)); + + + }, this.config.interval); + } + } + + // Stops the gauge animation (ignored if already started) + this.stop = function () { + if (this.timer != null) { + clearInterval (this.timer); + this.timer == null; + } + } + + this.redrawWithAnimation = function () { + // todo: reset the yscale if the max and mins differ with the new + // data + var max = Math.max (this.config.max, d3.max(this.data)); + var min = Math.min (this.config.min, d3.min (this.data)); + if (max > this.max || min < this.min) { + this.resetYScale (max, min); + } + else if (max <= this.config.max || min >= this.config.min) { + this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); + } + if (this.data.length < this.config.windowSize) { + this.redrawWithoutAnimation (); + } + else { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .attr("transform", "translate(" + this.xScale(1) + ")") // set + // the + // transform + // to + // the + // right + // by + // xScale + // (1) + .attr("d", this.line) // apply the new data values ... but + // the new value is hidden at this + // point off the right of the canvas + .transition () // start the transition to bring in the new + // value + .ease("linear") + .duration (this.config.transition) + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr("transform", "translate(" + this.xScale(0) + ")"); // animate + // a + // slide + // to + // the + // left + // back + // to + // x(0) + // pixels + // to + // reveal + // the + // new + // value + } + + + } + + this.redrawWithoutAnimation = function () { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr ("d", this.line); // apply the new data values + } + + // Initialization + this.configure (configuration); + } + +window.edu_cmu_rainbow_ui_display_widgets_LineGaugeComponent = function () { + var element = this.getElement (); + + var gauge; + + this.onStateChange = function () { + if (gauge) + gauge.redraw (this.getState ().value); + } + + this.createGauge = function (name, label, min, max, window, yLabel, threshold) { + var config = { + width: 100, + height: 50, + label: label, + interval: 1000, + windowSize: window, + animate:true, + min:min, + max:max, + } + + if (yLabel) config.yLabel = yLabel; + if (threshold && threshold > 0) config.threshold = threshold; + + + gauge = new MovingLineGauge(element, config); + gauge.render (); + } + + this.deactivate = function () { + if (gauge) + gauge.stop (); + } + + this.activate = function () { + if (gauge) + gauge.start (); + } +} diff --git a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge4.js b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge4.js index d5d881108..92e55fc2f 100644 --- a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge4.js +++ b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge4.js @@ -1,288 +1,288 @@ - function MovingLineGauge (placeholderName, configuration, nextDatum) { - this.placeholderName = placeholderName; - var self = this; - - this.data = []; - - this.configure = function (configuration) { - this.config = configuration; - // The width of the gauge - this.config.width = configuration.width || 100; - // The height of the gauge - this.config.height = configuration.height || 50; - this.config.graphHeight = configuration.height || 50; - // Whether to smooth or not: linear, basis - this.config.interpolation = configuration.smooth?"basis":"linear"; - // Whether to animate the transition each interval - this.config.animate = configuration.animate || false; - // The interval for new values, ms - this.config.interval = configuration.interval || 1000; - // If animating, how long the transition should take - this.config.transition = configuration.transition || this.config.interval; - // The maximum number of values to display - this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); - // The minumum expected value - this.config.min = configuration.min || 0; - // The maximum expected value - this.config.max = configuration.max || 100; - this.config.range = this.config.max - this.config.min; - // Any initial data that should be displayed - if (this.config.initialData != null) { - this.data = this.config.initialData.slice (0); - this.max = Math.max (this.config.max, d3.max(this.data)); - this.min = Math.min (this.config.min, d3.min(this.data)); - } - else { - this.min = this.config.min; - this.max = this.config.max; - } - - if (this.config.label) { - this.config.graphHeight = this.config.graphHeight - 9; - } - - // Set up the x and y scales - // The X scale will fit windowSize values within the width of the - // widget - this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting - // point - // is - // -5 - // so - // the - // first - // value - // doesn't - // show - // and - // slides - // off - // the - // edge - // as - // part - // of - // the - // transition - // The Y scale will fit values min,max within the height - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - } - this.resetYScale = function (max, min) { - this.max = max; - this.min = min; - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - this.drawThreshold (); - } - - this.render = function () { - var div; - if (typeof this.placeholderName == "string") { - div = d3.select("#" + this.placeholderName); - } - else { - div = d3.select (this.placeholderName); - } - this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); - this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); - - - // Create axes and thresholds (todo) - - // Create the line - this.line = d3.svg.line () - // assign the X functino to plot the line - .x (function (d,i) { - return self.xScale(i); - }) - .y (function (d) { - return self.yScale(d); - }) - .interpolate (this.config.interpolation); - // display the line by appending an svg:path element with the data - // line above - this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); - this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); - var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) - .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); - if (this.config.yLabel) { - axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); - } - if (this.config.label) { - this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); - } - this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); - - this.drawThreshold (); - } - - this.drawThreshold = function () { - if (this.config.threshold) { - var threshold = this.graph.selectAll (".threshold"); - if (threshold.empty ()) - this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( - "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - else - threshold - .attr("x1", this.xScale (0)).attr( - "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - - } - } - - - - // Starts the gauge animation (ignored if already started) - this.start = function () { - if (this.timer == null) { - this.timer = setInterval (function() { - var nxt = self.config.nextDatum (); - if (nxt == null && self.data.length > 0) { - self.data.shift (); - } - else if (nxt == null) { - return; - } - else { - if (self.data.length < self.config.windowSize) { - self.data.push(nxt); - } - else { - self.data.shift (); - self.data.push(nxt); - } - } - if (self.config.animate) { - self.redrawWithAnimation (); - } - else { - self.redrawWithoutAnimation (); - } - var currentValue = self.group.select (".MLCurrentValue"); - currentValue.text (self.data.slice(-1)); - - - }, this.config.interval); - } - } - - // Stops the gauge animation (ignored if already started) - this.stop = function () { - if (this.timer != null) { - clearInterval (this.timer); - this.timer == null; - } - } - - this.redrawWithAnimation = function () { - // todo: reset the yscale if the max and mins differ with the new - // data - var max = Math.max (this.config.max, d3.max(this.data)); - var min = Math.min (this.config.min, d3.min (this.data)); - if (max > this.max || min < this.min) { - this.resetYScale (max, min); - } - else if (max <= this.config.max || min >= this.config.min) { - this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); - } - if (this.data.length < this.config.windowSize) { - this.redrawWithoutAnimation (); - } - else { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .attr("transform", "translate(" + this.xScale(1) + ")") // set - // the - // transform - // to - // the - // right - // by - // xScale - // (1) - .attr("d", this.line) // apply the new data values ... but - // the new value is hidden at this - // point off the right of the canvas - .transition () // start the transition to bring in the new - // value - .ease("linear") - .duration (this.config.transition) - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr("transform", "translate(" + this.xScale(0) + ")"); // animate - // a - // slide - // to - // the - // left - // back - // to - // x(0) - // pixels - // to - // reveal - // the - // new - // value - } - - - } - - this.redrawWithoutAnimation = function () { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr ("d", this.line); // apply the new data values - } - - // Initialization - this.configure (configuration); - } - -window.edu_cmu_rainbow_ui_display_widgets_LineGaugeComponent = function () { - var element = this.getElement (); - - var gauge; - - var self = this; - - this.onStateChange = function () { - // updates are done with periodic readings of the value using the next data function - } - - this.nextDatum = function () { - return self.getState ().value; - } - - this.createGauge = function (name, label, min, max, window, yLabel, threshold) { - var config = { - width: 100, - height: 50, - interval: 1000, - windowSize: window, - animate:true, - min:min, - max:max, - } - - if (yLabel) config.yLabel = yLabel; - if (threshold && threshold > 0) config.threshold = threshold; - config.nextDatum = this.nextDatum; - - gauge = new MovingLineGauge(element, config); - gauge.render (); - } - - this.deactivate = function () { - if (gauge) - gauge.stop (); - } - - this.activate = function () { - if (gauge) - gauge.start (); - } -} + function MovingLineGauge (placeholderName, configuration, nextDatum) { + this.placeholderName = placeholderName; + var self = this; + + this.data = []; + + this.configure = function (configuration) { + this.config = configuration; + // The width of the gauge + this.config.width = configuration.width || 100; + // The height of the gauge + this.config.height = configuration.height || 50; + this.config.graphHeight = configuration.height || 50; + // Whether to smooth or not: linear, basis + this.config.interpolation = configuration.smooth?"basis":"linear"; + // Whether to animate the transition each interval + this.config.animate = configuration.animate || false; + // The interval for new values, ms + this.config.interval = configuration.interval || 1000; + // If animating, how long the transition should take + this.config.transition = configuration.transition || this.config.interval; + // The maximum number of values to display + this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); + // The minumum expected value + this.config.min = configuration.min || 0; + // The maximum expected value + this.config.max = configuration.max || 100; + this.config.range = this.config.max - this.config.min; + // Any initial data that should be displayed + if (this.config.initialData != null) { + this.data = this.config.initialData.slice (0); + this.max = Math.max (this.config.max, d3.max(this.data)); + this.min = Math.min (this.config.min, d3.min(this.data)); + } + else { + this.min = this.config.min; + this.max = this.config.max; + } + + if (this.config.label) { + this.config.graphHeight = this.config.graphHeight - 9; + } + + // Set up the x and y scales + // The X scale will fit windowSize values within the width of the + // widget + this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting + // point + // is + // -5 + // so + // the + // first + // value + // doesn't + // show + // and + // slides + // off + // the + // edge + // as + // part + // of + // the + // transition + // The Y scale will fit values min,max within the height + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + } + this.resetYScale = function (max, min) { + this.max = max; + this.min = min; + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + this.drawThreshold (); + } + + this.render = function () { + var div; + if (typeof this.placeholderName == "string") { + div = d3.select("#" + this.placeholderName); + } + else { + div = d3.select (this.placeholderName); + } + this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); + this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); + + + // Create axes and thresholds (todo) + + // Create the line + this.line = d3.svg.line () + // assign the X functino to plot the line + .x (function (d,i) { + return self.xScale(i); + }) + .y (function (d) { + return self.yScale(d); + }) + .interpolate (this.config.interpolation); + // display the line by appending an svg:path element with the data + // line above + this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); + this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); + var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) + .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); + if (this.config.yLabel) { + axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); + } + if (this.config.label) { + this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); + } + this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); + + this.drawThreshold (); + } + + this.drawThreshold = function () { + if (this.config.threshold) { + var threshold = this.graph.selectAll (".threshold"); + if (threshold.empty ()) + this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( + "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + else + threshold + .attr("x1", this.xScale (0)).attr( + "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + + } + } + + + + // Starts the gauge animation (ignored if already started) + this.start = function () { + if (this.timer == null) { + this.timer = setInterval (function() { + var nxt = self.config.nextDatum (); + if (nxt == null && self.data.length > 0) { + self.data.shift (); + } + else if (nxt == null) { + return; + } + else { + if (self.data.length < self.config.windowSize) { + self.data.push(nxt); + } + else { + self.data.shift (); + self.data.push(nxt); + } + } + if (self.config.animate) { + self.redrawWithAnimation (); + } + else { + self.redrawWithoutAnimation (); + } + var currentValue = self.group.select (".MLCurrentValue"); + currentValue.text (self.data.slice(-1)); + + + }, this.config.interval); + } + } + + // Stops the gauge animation (ignored if already started) + this.stop = function () { + if (this.timer != null) { + clearInterval (this.timer); + this.timer == null; + } + } + + this.redrawWithAnimation = function () { + // todo: reset the yscale if the max and mins differ with the new + // data + var max = Math.max (this.config.max, d3.max(this.data)); + var min = Math.min (this.config.min, d3.min (this.data)); + if (max > this.max || min < this.min) { + this.resetYScale (max, min); + } + else if (max <= this.config.max || min >= this.config.min) { + this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); + } + if (this.data.length < this.config.windowSize) { + this.redrawWithoutAnimation (); + } + else { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .attr("transform", "translate(" + this.xScale(1) + ")") // set + // the + // transform + // to + // the + // right + // by + // xScale + // (1) + .attr("d", this.line) // apply the new data values ... but + // the new value is hidden at this + // point off the right of the canvas + .transition () // start the transition to bring in the new + // value + .ease("linear") + .duration (this.config.transition) + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr("transform", "translate(" + this.xScale(0) + ")"); // animate + // a + // slide + // to + // the + // left + // back + // to + // x(0) + // pixels + // to + // reveal + // the + // new + // value + } + + + } + + this.redrawWithoutAnimation = function () { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr ("d", this.line); // apply the new data values + } + + // Initialization + this.configure (configuration); + } + +window.edu_cmu_rainbow_ui_display_widgets_LineGaugeComponent = function () { + var element = this.getElement (); + + var gauge; + + var self = this; + + this.onStateChange = function () { + // updates are done with periodic readings of the value using the next data function + } + + this.nextDatum = function () { + return self.getState ().value; + } + + this.createGauge = function (name, label, min, max, window, yLabel, threshold) { + var config = { + width: 100, + height: 50, + interval: 1000, + windowSize: window, + animate:true, + min:min, + max:max, + } + + if (yLabel) config.yLabel = yLabel; + if (threshold && threshold > 0) config.threshold = threshold; + config.nextDatum = this.nextDatum; + + gauge = new MovingLineGauge(element, config); + gauge.render (); + } + + this.deactivate = function () { + if (gauge) + gauge.stop (); + } + + this.activate = function () { + if (gauge) + gauge.start (); + } +} diff --git a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge5.js b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge5.js index d5d881108..92e55fc2f 100644 --- a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge5.js +++ b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/line-gauge5.js @@ -1,288 +1,288 @@ - function MovingLineGauge (placeholderName, configuration, nextDatum) { - this.placeholderName = placeholderName; - var self = this; - - this.data = []; - - this.configure = function (configuration) { - this.config = configuration; - // The width of the gauge - this.config.width = configuration.width || 100; - // The height of the gauge - this.config.height = configuration.height || 50; - this.config.graphHeight = configuration.height || 50; - // Whether to smooth or not: linear, basis - this.config.interpolation = configuration.smooth?"basis":"linear"; - // Whether to animate the transition each interval - this.config.animate = configuration.animate || false; - // The interval for new values, ms - this.config.interval = configuration.interval || 1000; - // If animating, how long the transition should take - this.config.transition = configuration.transition || this.config.interval; - // The maximum number of values to display - this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); - // The minumum expected value - this.config.min = configuration.min || 0; - // The maximum expected value - this.config.max = configuration.max || 100; - this.config.range = this.config.max - this.config.min; - // Any initial data that should be displayed - if (this.config.initialData != null) { - this.data = this.config.initialData.slice (0); - this.max = Math.max (this.config.max, d3.max(this.data)); - this.min = Math.min (this.config.min, d3.min(this.data)); - } - else { - this.min = this.config.min; - this.max = this.config.max; - } - - if (this.config.label) { - this.config.graphHeight = this.config.graphHeight - 9; - } - - // Set up the x and y scales - // The X scale will fit windowSize values within the width of the - // widget - this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting - // point - // is - // -5 - // so - // the - // first - // value - // doesn't - // show - // and - // slides - // off - // the - // edge - // as - // part - // of - // the - // transition - // The Y scale will fit values min,max within the height - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - } - this.resetYScale = function (max, min) { - this.max = max; - this.min = min; - this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); - this.drawThreshold (); - } - - this.render = function () { - var div; - if (typeof this.placeholderName == "string") { - div = d3.select("#" + this.placeholderName); - } - else { - div = d3.select (this.placeholderName); - } - this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); - this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); - - - // Create axes and thresholds (todo) - - // Create the line - this.line = d3.svg.line () - // assign the X functino to plot the line - .x (function (d,i) { - return self.xScale(i); - }) - .y (function (d) { - return self.yScale(d); - }) - .interpolate (this.config.interpolation); - // display the line by appending an svg:path element with the data - // line above - this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); - this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); - var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) - .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); - if (this.config.yLabel) { - axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); - } - if (this.config.label) { - this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); - } - this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); - - this.drawThreshold (); - } - - this.drawThreshold = function () { - if (this.config.threshold) { - var threshold = this.graph.selectAll (".threshold"); - if (threshold.empty ()) - this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( - "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - else - threshold - .attr("x1", this.xScale (0)).attr( - "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", - this.yScale(this.config.threshold)).style("stroke", "#600").style( - "stroke-width", "1px").style("stroke-dasharray", ("3","3")); - - } - } - - - - // Starts the gauge animation (ignored if already started) - this.start = function () { - if (this.timer == null) { - this.timer = setInterval (function() { - var nxt = self.config.nextDatum (); - if (nxt == null && self.data.length > 0) { - self.data.shift (); - } - else if (nxt == null) { - return; - } - else { - if (self.data.length < self.config.windowSize) { - self.data.push(nxt); - } - else { - self.data.shift (); - self.data.push(nxt); - } - } - if (self.config.animate) { - self.redrawWithAnimation (); - } - else { - self.redrawWithoutAnimation (); - } - var currentValue = self.group.select (".MLCurrentValue"); - currentValue.text (self.data.slice(-1)); - - - }, this.config.interval); - } - } - - // Stops the gauge animation (ignored if already started) - this.stop = function () { - if (this.timer != null) { - clearInterval (this.timer); - this.timer == null; - } - } - - this.redrawWithAnimation = function () { - // todo: reset the yscale if the max and mins differ with the new - // data - var max = Math.max (this.config.max, d3.max(this.data)); - var min = Math.min (this.config.min, d3.min (this.data)); - if (max > this.max || min < this.min) { - this.resetYScale (max, min); - } - else if (max <= this.config.max || min >= this.config.min) { - this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); - } - if (this.data.length < this.config.windowSize) { - this.redrawWithoutAnimation (); - } - else { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .attr("transform", "translate(" + this.xScale(1) + ")") // set - // the - // transform - // to - // the - // right - // by - // xScale - // (1) - .attr("d", this.line) // apply the new data values ... but - // the new value is hidden at this - // point off the right of the canvas - .transition () // start the transition to bring in the new - // value - .ease("linear") - .duration (this.config.transition) - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr("transform", "translate(" + this.xScale(0) + ")"); // animate - // a - // slide - // to - // the - // left - // back - // to - // x(0) - // pixels - // to - // reveal - // the - // new - // value - } - - - } - - this.redrawWithoutAnimation = function () { - this.graph.selectAll(".data") - .data([this.data]) // set the new data - .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") - .attr ("d", this.line); // apply the new data values - } - - // Initialization - this.configure (configuration); - } - -window.edu_cmu_rainbow_ui_display_widgets_LineGaugeComponent = function () { - var element = this.getElement (); - - var gauge; - - var self = this; - - this.onStateChange = function () { - // updates are done with periodic readings of the value using the next data function - } - - this.nextDatum = function () { - return self.getState ().value; - } - - this.createGauge = function (name, label, min, max, window, yLabel, threshold) { - var config = { - width: 100, - height: 50, - interval: 1000, - windowSize: window, - animate:true, - min:min, - max:max, - } - - if (yLabel) config.yLabel = yLabel; - if (threshold && threshold > 0) config.threshold = threshold; - config.nextDatum = this.nextDatum; - - gauge = new MovingLineGauge(element, config); - gauge.render (); - } - - this.deactivate = function () { - if (gauge) - gauge.stop (); - } - - this.activate = function () { - if (gauge) - gauge.start (); - } -} + function MovingLineGauge (placeholderName, configuration, nextDatum) { + this.placeholderName = placeholderName; + var self = this; + + this.data = []; + + this.configure = function (configuration) { + this.config = configuration; + // The width of the gauge + this.config.width = configuration.width || 100; + // The height of the gauge + this.config.height = configuration.height || 50; + this.config.graphHeight = configuration.height || 50; + // Whether to smooth or not: linear, basis + this.config.interpolation = configuration.smooth?"basis":"linear"; + // Whether to animate the transition each interval + this.config.animate = configuration.animate || false; + // The interval for new values, ms + this.config.interval = configuration.interval || 1000; + // If animating, how long the transition should take + this.config.transition = configuration.transition || this.config.interval; + // The maximum number of values to display + this.config.windowSize = configuration.windowSize || Math.floor (this.config.width / 10); + // The minumum expected value + this.config.min = configuration.min || 0; + // The maximum expected value + this.config.max = configuration.max || 100; + this.config.range = this.config.max - this.config.min; + // Any initial data that should be displayed + if (this.config.initialData != null) { + this.data = this.config.initialData.slice (0); + this.max = Math.max (this.config.max, d3.max(this.data)); + this.min = Math.min (this.config.min, d3.min(this.data)); + } + else { + this.min = this.config.min; + this.max = this.config.max; + } + + if (this.config.label) { + this.config.graphHeight = this.config.graphHeight - 9; + } + + // Set up the x and y scales + // The X scale will fit windowSize values within the width of the + // widget + this.xScale = d3.scale.linear ().domain ([0,this.config.windowSize]).range ([-5,this.config.width]); // starting + // point + // is + // -5 + // so + // the + // first + // value + // doesn't + // show + // and + // slides + // off + // the + // edge + // as + // part + // of + // the + // transition + // The Y scale will fit values min,max within the height + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + } + this.resetYScale = function (max, min) { + this.max = max; + this.min = min; + this.yScale = d3.scale.linear ().domain([this.max, this.min]).range([0,this.config.graphHeight]); + this.drawThreshold (); + } + + this.render = function () { + var div; + if (typeof this.placeholderName == "string") { + div = d3.select("#" + this.placeholderName); + } + else { + div = d3.select (this.placeholderName); + } + this.group = div.append ("svg:svg").attr ("class", "movingGraphContainer").attr("width", this.config.width).attr("height",this.config.height); + this.graph = this.group.append ("svg:svg").attr ("width", this.config.width).attr("height", this.config.graphHeight); + + + // Create axes and thresholds (todo) + + // Create the line + this.line = d3.svg.line () + // assign the X functino to plot the line + .x (function (d,i) { + return self.xScale(i); + }) + .y (function (d) { + return self.yScale(d); + }) + .interpolate (this.config.interpolation); + // display the line by appending an svg:path element with the data + // line above + this.graph.append("svg:path").attr("class", "data").attr("d", this.line (this.data)).style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none"); + this.yAxis = d3.svg.axis ().scale (this.yScale).orient("left"); + var axis = this.graph.append ("g").attr("class", "y axis").call(this.yAxis) + .style("fill","none").style("stroke","#000").style("shape-rendering","crispEdges"); + if (this.config.yLabel) { + axis.append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy",".5em").style("font-size", "8px").style("text-anchor","end").text(this.config.yLabel); + } + if (this.config.label) { + this.group.append ("svg:text").attr("x", this.config.width / 2).attr ("y", this.config.height).attr("dy", "-4").attr("text-anchor", "middle").style("font-size", "9px").style("stroke-width", "1").style("fill", "#000").text (this.config.label); + } + this.group.append ("svg:text").attr ("class", "MLCurrentValue").attr("x", this.config.width - 25).attr ("y", 9).attr("text-anchor", "right").style("font-size", "8px").style("stroke-width", 1).style ("fill", "#000"); + + this.drawThreshold (); + } + + this.drawThreshold = function () { + if (this.config.threshold) { + var threshold = this.graph.selectAll (".threshold"); + if (threshold.empty ()) + this.graph.append("svg:line").attr("class","threshold").attr("x1", this.xScale (0)).attr( + "y1", this.yScale (this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + else + threshold + .attr("x1", this.xScale (0)).attr( + "y1", this.yScale(this.config.threshold)).attr("x2", this.xScale (this.config.width)).attr("y2", + this.yScale(this.config.threshold)).style("stroke", "#600").style( + "stroke-width", "1px").style("stroke-dasharray", ("3","3")); + + } + } + + + + // Starts the gauge animation (ignored if already started) + this.start = function () { + if (this.timer == null) { + this.timer = setInterval (function() { + var nxt = self.config.nextDatum (); + if (nxt == null && self.data.length > 0) { + self.data.shift (); + } + else if (nxt == null) { + return; + } + else { + if (self.data.length < self.config.windowSize) { + self.data.push(nxt); + } + else { + self.data.shift (); + self.data.push(nxt); + } + } + if (self.config.animate) { + self.redrawWithAnimation (); + } + else { + self.redrawWithoutAnimation (); + } + var currentValue = self.group.select (".MLCurrentValue"); + currentValue.text (self.data.slice(-1)); + + + }, this.config.interval); + } + } + + // Stops the gauge animation (ignored if already started) + this.stop = function () { + if (this.timer != null) { + clearInterval (this.timer); + this.timer == null; + } + } + + this.redrawWithAnimation = function () { + // todo: reset the yscale if the max and mins differ with the new + // data + var max = Math.max (this.config.max, d3.max(this.data)); + var min = Math.min (this.config.min, d3.min (this.data)); + if (max > this.max || min < this.min) { + this.resetYScale (max, min); + } + else if (max <= this.config.max || min >= this.config.min) { + this.resetYScale (Math.max (this.config.max,max), Math.min (this.config.min,min)); + } + if (this.data.length < this.config.windowSize) { + this.redrawWithoutAnimation (); + } + else { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .attr("transform", "translate(" + this.xScale(1) + ")") // set + // the + // transform + // to + // the + // right + // by + // xScale + // (1) + .attr("d", this.line) // apply the new data values ... but + // the new value is hidden at this + // point off the right of the canvas + .transition () // start the transition to bring in the new + // value + .ease("linear") + .duration (this.config.transition) + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr("transform", "translate(" + this.xScale(0) + ")"); // animate + // a + // slide + // to + // the + // left + // back + // to + // x(0) + // pixels + // to + // reveal + // the + // new + // value + } + + + } + + this.redrawWithoutAnimation = function () { + this.graph.selectAll(".data") + .data([this.data]) // set the new data + .style("stroke", "steelblue").style ("stroke-width", "1").style ("fill","none") + .attr ("d", this.line); // apply the new data values + } + + // Initialization + this.configure (configuration); + } + +window.edu_cmu_rainbow_ui_display_widgets_LineGaugeComponent = function () { + var element = this.getElement (); + + var gauge; + + var self = this; + + this.onStateChange = function () { + // updates are done with periodic readings of the value using the next data function + } + + this.nextDatum = function () { + return self.getState ().value; + } + + this.createGauge = function (name, label, min, max, window, yLabel, threshold) { + var config = { + width: 100, + height: 50, + interval: 1000, + windowSize: window, + animate:true, + min:min, + max:max, + } + + if (yLabel) config.yLabel = yLabel; + if (threshold && threshold > 0) config.threshold = threshold; + config.nextDatum = this.nextDatum; + + gauge = new MovingLineGauge(element, config); + gauge.render (); + } + + this.deactivate = function () { + if (gauge) + gauge.stop (); + } + + this.activate = function () { + if (gauge) + gauge.start (); + } +} diff --git a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/test.html b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/test.html index e08485e51..3dfc65228 100644 --- a/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/test.html +++ b/ide/rainbow-ui-framework/src/main/resources/edu/cmu/rainbow_ui/display/widgets/test.html @@ -1,41 +1,41 @@ - - - - - -%PROPERTY gauges - - - - - - - - -
-
- + + + + + +%PROPERTY gauges + + + + + + + + +
+
+ \ No newline at end of file diff --git a/ide/rainbow-ui-framework/src/main/webapp/VAADIN/themes/rainbow-theme/addons.scss b/ide/rainbow-ui-framework/src/main/webapp/VAADIN/themes/rainbow-theme/addons.scss index 754ba4bb0..a5670b70c 100644 --- a/ide/rainbow-ui-framework/src/main/webapp/VAADIN/themes/rainbow-theme/addons.scss +++ b/ide/rainbow-ui-framework/src/main/webapp/VAADIN/themes/rainbow-theme/addons.scss @@ -1,7 +1,7 @@ -/* This file is automatically managed and will be overwritten from time to time. */ -/* Do not manually edit this file. */ - -/* Import and include this mixin into your project theme to include the addon themes */ -@mixin addons { -} - +/* This file is automatically managed and will be overwritten from time to time. */ +/* Do not manually edit this file. */ + +/* Import and include this mixin into your project theme to include the addon themes */ +@mixin addons { +} + diff --git a/ide/rainbow-ui-framework/src/test/java/edu/cmu/rainbow_ui/display/event/EventTest.java b/ide/rainbow-ui-framework/src/test/java/edu/cmu/rainbow_ui/display/event/EventTest.java index e5ba7f014..43dc88b18 100644 --- a/ide/rainbow-ui-framework/src/test/java/edu/cmu/rainbow_ui/display/event/EventTest.java +++ b/ide/rainbow-ui-framework/src/test/java/edu/cmu/rainbow_ui/display/event/EventTest.java @@ -1,232 +1,232 @@ -/* - * The MIT License - * - * Copyright 2014 CMU MSIT-SE Rainbow Team. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package edu.cmu.rainbow_ui.display.event; - -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.ui.Component; -import com.vaadin.ui.HasComponents; -import com.vaadin.ui.HorizontalLayout; -import com.vaadin.ui.Label; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import org.acmestudio.acme.model.event.AcmeModelEventType; -import org.junit.After; -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.Test; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; -import org.sa.rainbow.core.ports.eseb.ESEBConstants; -import org.sa.rainbow.core.ports.eseb.RainbowESEBMessage; -import org.sa.rainbow.model.acme.AcmeModelOperation; -import org.tepi.filtertable.paged.PagedFilterTable; - -import com.google.gwt.editor.client.Editor.Ignore; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.ui.Component; -import com.vaadin.ui.HasComponents; -import com.vaadin.ui.HorizontalLayout; -import com.vaadin.ui.Label; - -public class EventTest { - - private List eventList1; - private List eventList2; - - @Before - public void setUp() throws Exception { - eventList1 = new ArrayList<>(); - - long curTime = 0; - - for (int i = 0; i < 5; i++) { - try { - IRainbowMessage event = new RainbowESEBMessage(); - event.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, - AcmeModelEventType.SET_PROPERTY_VALUE.toString()); - event.setProperty(AcmeModelOperation.PROPERTY_PROP, - "ZNewsSys.Server0.load"); - event.setProperty(AcmeModelOperation.VALUE_PROP, i); - event.setProperty(ESEBConstants.MSG_SENT, curTime + ""); - curTime += 10; - eventList1.add(event); - } catch (Exception e) { - - } - } - - eventList2 = new ArrayList<>(); - for (int i = 6; i < 12; i++) { - try { - IRainbowMessage event = new RainbowESEBMessage(); - event.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, - AcmeModelEventType.SET_PROPERTY_VALUE.toString()); - event.setProperty(AcmeModelOperation.PROPERTY_PROP, - "ZNewsSys.Server0.load"); - event.setProperty(AcmeModelOperation.VALUE_PROP, i); - event.setProperty(ESEBConstants.MSG_SENT, curTime + ""); - curTime += 10; - eventList2.add(event); - } catch (Exception e) { - - } - } - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void CreateTable() { - MockEventTable table = new MockEventTable(); - assertEquals(false, table.isActive()); - assertNotNull(table.getTable()); - assertNotNull(table.getContainer()); - assertNotNull(table.getEventDetails()); - } - - @Test - public void CreateTableWithEvents() { - MockEventTable table = new MockEventTable(eventList1); - assertEquals(false, table.isActive()); - assertNotNull(table.getTable()); - assertNotNull(table.getContainer()); - assertNotNull(table.getEventDetails()); - assertNotNull(table.getEvents()); - assertEquals(eventList1.size(), table.getEvents().size()); - } - - @Test - public void SetEvents() { - MockEventTable table = new MockEventTable(); - - table.setEvents(eventList1); - assertNotNull(table.getEvents()); - assertEquals(eventList1.size(), table.getEvents().size()); - - IndexedContainer container = table.getContainer(); - assertNotNull(container); - assertEquals(eventList1.get(0).getPropertyNames().size() + 1, container - .getContainerPropertyIds().size()); - } - - @Test - public void AddEvent() { - MockEventTable table = new MockEventTable(); - - table.addEvent(eventList1.get(0)); - assertNotNull(table.getEvents()); - assertEquals(1, table.getEvents().size()); - - IndexedContainer container = table.getContainer(); - assertNotNull(container); - assertEquals(eventList1.get(0).getPropertyNames().size() + 1, container - .getContainerPropertyIds().size()); - } - - @Ignore - @Test - public void AddEventToList() { - MockEventTable table = new MockEventTable(eventList1); - table.setEvents(eventList1); - table.addEvent(eventList2.get(0)); - assertNotNull(table.getEvents()); - assertEquals(eventList1.size() + 1, table.getEvents().size()); - - IndexedContainer container = table.getContainer(); - assertNotNull(container); - assertEquals(eventList1.get(0).getPropertyNames().size() + 1, container - .getContainerPropertyIds().size()); - - assertEquals(eventList2.get(0), - table.getContainer() - .getItem(table.getContainer().getIdByIndex(0)) - .getItemProperty("Raw Message").getValue()); - } - - @Test - public void SelectEvent() { - MockEventTable eventTable = new MockEventTable(eventList1); - - PagedFilterTable table = eventTable.getTable(); - assertNotNull(table); - - IndexedContainer container = eventTable.getContainer(); - assertNotNull(container); - assertEquals(container.size(), eventList1.size()); - - table.setValue(container.getIdByIndex(0)); - Object selectedItem = eventTable.getSelectedItem(); - assertNotNull(selectedItem); - - IRainbowMessage message = (IRainbowMessage) table.getContainerProperty( - selectedItem, "Raw Message").getValue(); - assertNotNull(message); - assertEquals(message.getPropertyNames().size(), eventList1.get(0) - .getPropertyNames().size()); - assertEquals(message.getProperty(AcmeModelOperation.VALUE_PROP), - eventList1.get(eventList1.size() - 1).getProperty(AcmeModelOperation.VALUE_PROP)); - - table.select(null); - selectedItem = eventTable.getSelectedItem(); - assertNull(selectedItem); - } - - @Test - public void SelectEventDetails() { - EventDetails details = new EventDetails(); - details.setMessage(eventList1.get(0)); - - Iterator iterate = details.iterator(); - while (iterate.hasNext()) { - Component c = iterate.next(); - if (c instanceof HasComponents) { - Iterator rowIterate = ((HorizontalLayout) c) - .iterator(); - String key = ""; - String value = ""; - boolean isKeyValueRow = true; - while (rowIterate.hasNext()) { - Component cc = rowIterate.next(); - if (cc instanceof Label) { - if (key.equals("")) { - key = ((Label) cc).getValue(); - } else { - value = ((Label) cc).getValue(); - } - } else { - isKeyValueRow = false; - } - } - - if (isKeyValueRow) { - assertEquals(eventList1.get(0).getProperty(key).toString(), - value); - } - } - } - } -} +/* + * The MIT License + * + * Copyright 2014 CMU MSIT-SE Rainbow Team. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package edu.cmu.rainbow_ui.display.event; + +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.ui.Component; +import com.vaadin.ui.HasComponents; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import org.acmestudio.acme.model.event.AcmeModelEventType; +import org.junit.After; +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; +import org.sa.rainbow.core.ports.eseb.ESEBConstants; +import org.sa.rainbow.core.ports.eseb.RainbowESEBMessage; +import org.sa.rainbow.model.acme.AcmeModelOperation; +import org.tepi.filtertable.paged.PagedFilterTable; + +import com.google.gwt.editor.client.Editor.Ignore; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.ui.Component; +import com.vaadin.ui.HasComponents; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; + +public class EventTest { + + private List eventList1; + private List eventList2; + + @Before + public void setUp() throws Exception { + eventList1 = new ArrayList<>(); + + long curTime = 0; + + for (int i = 0; i < 5; i++) { + try { + IRainbowMessage event = new RainbowESEBMessage(); + event.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, + AcmeModelEventType.SET_PROPERTY_VALUE.toString()); + event.setProperty(AcmeModelOperation.PROPERTY_PROP, + "ZNewsSys.Server0.load"); + event.setProperty(AcmeModelOperation.VALUE_PROP, i); + event.setProperty(ESEBConstants.MSG_SENT, curTime + ""); + curTime += 10; + eventList1.add(event); + } catch (Exception e) { + + } + } + + eventList2 = new ArrayList<>(); + for (int i = 6; i < 12; i++) { + try { + IRainbowMessage event = new RainbowESEBMessage(); + event.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, + AcmeModelEventType.SET_PROPERTY_VALUE.toString()); + event.setProperty(AcmeModelOperation.PROPERTY_PROP, + "ZNewsSys.Server0.load"); + event.setProperty(AcmeModelOperation.VALUE_PROP, i); + event.setProperty(ESEBConstants.MSG_SENT, curTime + ""); + curTime += 10; + eventList2.add(event); + } catch (Exception e) { + + } + } + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void CreateTable() { + MockEventTable table = new MockEventTable(); + assertEquals(false, table.isActive()); + assertNotNull(table.getTable()); + assertNotNull(table.getContainer()); + assertNotNull(table.getEventDetails()); + } + + @Test + public void CreateTableWithEvents() { + MockEventTable table = new MockEventTable(eventList1); + assertEquals(false, table.isActive()); + assertNotNull(table.getTable()); + assertNotNull(table.getContainer()); + assertNotNull(table.getEventDetails()); + assertNotNull(table.getEvents()); + assertEquals(eventList1.size(), table.getEvents().size()); + } + + @Test + public void SetEvents() { + MockEventTable table = new MockEventTable(); + + table.setEvents(eventList1); + assertNotNull(table.getEvents()); + assertEquals(eventList1.size(), table.getEvents().size()); + + IndexedContainer container = table.getContainer(); + assertNotNull(container); + assertEquals(eventList1.get(0).getPropertyNames().size() + 1, container + .getContainerPropertyIds().size()); + } + + @Test + public void AddEvent() { + MockEventTable table = new MockEventTable(); + + table.addEvent(eventList1.get(0)); + assertNotNull(table.getEvents()); + assertEquals(1, table.getEvents().size()); + + IndexedContainer container = table.getContainer(); + assertNotNull(container); + assertEquals(eventList1.get(0).getPropertyNames().size() + 1, container + .getContainerPropertyIds().size()); + } + + @Ignore + @Test + public void AddEventToList() { + MockEventTable table = new MockEventTable(eventList1); + table.setEvents(eventList1); + table.addEvent(eventList2.get(0)); + assertNotNull(table.getEvents()); + assertEquals(eventList1.size() + 1, table.getEvents().size()); + + IndexedContainer container = table.getContainer(); + assertNotNull(container); + assertEquals(eventList1.get(0).getPropertyNames().size() + 1, container + .getContainerPropertyIds().size()); + + assertEquals(eventList2.get(0), + table.getContainer() + .getItem(table.getContainer().getIdByIndex(0)) + .getItemProperty("Raw Message").getValue()); + } + + @Test + public void SelectEvent() { + MockEventTable eventTable = new MockEventTable(eventList1); + + PagedFilterTable table = eventTable.getTable(); + assertNotNull(table); + + IndexedContainer container = eventTable.getContainer(); + assertNotNull(container); + assertEquals(container.size(), eventList1.size()); + + table.setValue(container.getIdByIndex(0)); + Object selectedItem = eventTable.getSelectedItem(); + assertNotNull(selectedItem); + + IRainbowMessage message = (IRainbowMessage) table.getContainerProperty( + selectedItem, "Raw Message").getValue(); + assertNotNull(message); + assertEquals(message.getPropertyNames().size(), eventList1.get(0) + .getPropertyNames().size()); + assertEquals(message.getProperty(AcmeModelOperation.VALUE_PROP), + eventList1.get(eventList1.size() - 1).getProperty(AcmeModelOperation.VALUE_PROP)); + + table.select(null); + selectedItem = eventTable.getSelectedItem(); + assertNull(selectedItem); + } + + @Test + public void SelectEventDetails() { + EventDetails details = new EventDetails(); + details.setMessage(eventList1.get(0)); + + Iterator iterate = details.iterator(); + while (iterate.hasNext()) { + Component c = iterate.next(); + if (c instanceof HasComponents) { + Iterator rowIterate = ((HorizontalLayout) c) + .iterator(); + String key = ""; + String value = ""; + boolean isKeyValueRow = true; + while (rowIterate.hasNext()) { + Component cc = rowIterate.next(); + if (cc instanceof Label) { + if (key.equals("")) { + key = ((Label) cc).getValue(); + } else { + value = ((Label) cc).getValue(); + } + } else { + isKeyValueRow = false; + } + } + + if (isKeyValueRow) { + assertEquals(eventList1.get(0).getProperty(key).toString(), + value); + } + } + } + } +} diff --git a/ide/rainbow-ui-framework/src/test/java/edu/cmu/rainbow_ui/storage/MockDatabaseConnector.java b/ide/rainbow-ui-framework/src/test/java/edu/cmu/rainbow_ui/storage/MockDatabaseConnector.java index 84075264b..14001d086 100644 --- a/ide/rainbow-ui-framework/src/test/java/edu/cmu/rainbow_ui/storage/MockDatabaseConnector.java +++ b/ide/rainbow-ui-framework/src/test/java/edu/cmu/rainbow_ui/storage/MockDatabaseConnector.java @@ -1,264 +1,264 @@ -/* - * The MIT License - * - * Copyright 2014 CMU MSIT-SE Rainbow Team. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package edu.cmu.rainbow_ui.storage; - -import edu.cmu.rainbow_ui.ingestion.AcmeInternalModelInstance; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.acmestudio.acme.core.resource.ParsingFailureException; -import org.acmestudio.acme.element.IAcmeSystem; -import org.acmestudio.acme.model.event.AcmeModelEventType; -import org.acmestudio.basicmodel.element.AcmeSystem; -import org.acmestudio.standalone.resource.StandaloneResource; -import org.acmestudio.standalone.resource.StandaloneResourceProvider; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.sa.rainbow.core.error.RainbowException; -import org.sa.rainbow.core.event.IRainbowMessage; -import org.sa.rainbow.core.models.IModelInstance; -import org.sa.rainbow.core.ports.IRainbowMessageFactory; -import org.sa.rainbow.core.ports.eseb.ESEBConstants; -import org.sa.rainbow.core.ports.eseb.RainbowESEBMessage; -import org.sa.rainbow.model.acme.AcmeModelOperation; - -/** - * Mock database connector. - * - *

- * Provides plausible data to the users of Database Connector. For testing purposes. - *

- * - * @author Denis Anisimov - */ -public class MockDatabaseConnector implements IDatabaseConnector { - - @Override - public void writeEvent(String channel, IRainbowMessage event, Date timestamp) { - // Do nothing - } - - @Override - public void writeSnapshot(IModelInstance snapshot, Date timestamp) { - // Do nothing - } - - @Override - public ImmutablePair> getLatestSnapshot(Date time) { - StandaloneResource resource = null; - ImmutablePair> snapshot = null; - try { - resource = StandaloneResourceProvider.instance() - .acmeResourceForString("ZNewsSys.acme"); - AcmeSystem sys = resource.getModel().getSystems().iterator().next(); - IModelInstance model = new AcmeInternalModelInstance( - sys, "Acme"); - Calendar cal = Calendar.getInstance(); - Date date = cal.getTime(); - IModelInstance newmodel = (IModelInstance) model; - snapshot = new ImmutablePair>(date, - newmodel); - } catch (IOException | ParsingFailureException ex) { - Logger.getLogger(MockDatabaseConnector.class.getName()).log( - Level.SEVERE, null, ex); - } - return snapshot; - } - - @Override - public void writeModelUpdateEvent(IRainbowMessage event, Date timestamp) { - // Do nothing - } - - @Override - public List getEventRange(Date startTime, Date endTime) { - Float expRes = (float) 99.9; - IRainbowMessage event1 = new RainbowESEBMessage(); - try { - event1.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, - AcmeModelEventType.SET_PROPERTY_VALUE.toString()); - event1.setProperty(AcmeModelOperation.PROPERTY_PROP, - "ZNewsSys.Server0.load"); - event1.setProperty(AcmeModelOperation.VALUE_PROP, "1"); - event1.setProperty(ESEBConstants.MSG_SENT, - System.currentTimeMillis() + ""); - } catch (RainbowException e) { - Logger.getLogger(MockDatabaseConnector.class.getName()).log( - Level.SEVERE, null, e); - } - Date end = new Date(); - IRainbowMessage event2 = new RainbowESEBMessage(); - List events = new ArrayList<>(); - events.add(event1); - events.add(event2); - return events; - } - - @Override - public List getEventRangeByType(String channel, - Date startTime, Date endTime) { - IRainbowMessage event1 = new RainbowESEBMessage(); - IRainbowMessage event2 = new RainbowESEBMessage(); - List events = new ArrayList<>(); - events.add(event1); - events.add(event2); - return events; - } - - @Override - public List getModelEventRange(Date startTime, Date endTime) { - Float expRes = (float) 99.9; - IRainbowMessage event1 = new RainbowESEBMessage(); - IRainbowMessage event2 = new RainbowESEBMessage(); - try { - event1.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, - AcmeModelEventType.SET_PROPERTY_VALUE.toString()); - event1.setProperty(AcmeModelOperation.PROPERTY_PROP, - "ZNewsSys.Server0.load"); - event1.setProperty(AcmeModelOperation.VALUE_PROP, expRes.toString()); - event1.setProperty(ESEBConstants.MSG_SENT, - System.currentTimeMillis() + ""); - event2.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, - AcmeModelEventType.SET_PROPERTY_VALUE.toString()); - event2.setProperty(AcmeModelOperation.PROPERTY_PROP, - "ZNewsSys.Server0.load"); - event2.setProperty(AcmeModelOperation.VALUE_PROP, expRes.toString()); - event2.setProperty(ESEBConstants.MSG_SENT, - System.currentTimeMillis() + ""); - - } catch (RainbowException ex) { - Logger.getLogger(MockDatabaseConnector.class.getName()).log( - Level.SEVERE, null, ex); - } - List events = new ArrayList<>(); - events.add(event1); - events.add(event2); - return events; - } - - @Override - public IRainbowMessage getEvent(Date time) { - IRainbowMessage event = new RainbowESEBMessage(); - try { - event.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, - AcmeModelEventType.SET_PROPERTY_VALUE.toString()); - event.setProperty(AcmeModelOperation.PROPERTY_PROP, - "ZNewsSys.Server0.load"); - - } catch (RainbowException ex) { - Logger.getLogger(MockDatabaseConnector.class.getName()).log( - Level.SEVERE, null, ex); - } - return event; - } - - @Override - public void useSession(String name) { - // Do nothing - } - - @Override - public ArrayList getSessionList() { - ArrayList sessions = new ArrayList<>(); - return sessions; - } - - @Override - public void createSession(String name) { - // Do nothing - } - - @Override - public String getWriteSession() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getReadSession() { - return "mockSession"; - } - - @Override - public void closeWriteSession() { - // Do nothing - } - - @Override - public ArrayList getConfigurationList(String type) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getLatestConfigurationName(String type) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getConfiguration(String type, String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void writeConfiguration(String config, String type, String name) { - // TODO Auto-generated method stub - - } - - @Override - public Date getStartDate() { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean currentSessionIsWriteSession() { - // TODO Auto-generated method stub - return false; - } - - @Override - public Date getMaxDate() { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getNumberOfEventsBefore(Date endTime, - int numEvents) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void closeConnection() { - // Do nothing - } - -} +/* + * The MIT License + * + * Copyright 2014 CMU MSIT-SE Rainbow Team. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package edu.cmu.rainbow_ui.storage; + +import edu.cmu.rainbow_ui.ingestion.AcmeInternalModelInstance; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.acmestudio.acme.core.resource.ParsingFailureException; +import org.acmestudio.acme.element.IAcmeSystem; +import org.acmestudio.acme.model.event.AcmeModelEventType; +import org.acmestudio.basicmodel.element.AcmeSystem; +import org.acmestudio.standalone.resource.StandaloneResource; +import org.acmestudio.standalone.resource.StandaloneResourceProvider; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.sa.rainbow.core.error.RainbowException; +import org.sa.rainbow.core.event.IRainbowMessage; +import org.sa.rainbow.core.models.IModelInstance; +import org.sa.rainbow.core.ports.IRainbowMessageFactory; +import org.sa.rainbow.core.ports.eseb.ESEBConstants; +import org.sa.rainbow.core.ports.eseb.RainbowESEBMessage; +import org.sa.rainbow.model.acme.AcmeModelOperation; + +/** + * Mock database connector. + * + *

+ * Provides plausible data to the users of Database Connector. For testing purposes. + *

+ * + * @author Denis Anisimov + */ +public class MockDatabaseConnector implements IDatabaseConnector { + + @Override + public void writeEvent(String channel, IRainbowMessage event, Date timestamp) { + // Do nothing + } + + @Override + public void writeSnapshot(IModelInstance snapshot, Date timestamp) { + // Do nothing + } + + @Override + public ImmutablePair> getLatestSnapshot(Date time) { + StandaloneResource resource = null; + ImmutablePair> snapshot = null; + try { + resource = StandaloneResourceProvider.instance() + .acmeResourceForString("ZNewsSys.acme"); + AcmeSystem sys = resource.getModel().getSystems().iterator().next(); + IModelInstance model = new AcmeInternalModelInstance( + sys, "Acme"); + Calendar cal = Calendar.getInstance(); + Date date = cal.getTime(); + IModelInstance newmodel = (IModelInstance) model; + snapshot = new ImmutablePair>(date, + newmodel); + } catch (IOException | ParsingFailureException ex) { + Logger.getLogger(MockDatabaseConnector.class.getName()).log( + Level.SEVERE, null, ex); + } + return snapshot; + } + + @Override + public void writeModelUpdateEvent(IRainbowMessage event, Date timestamp) { + // Do nothing + } + + @Override + public List getEventRange(Date startTime, Date endTime) { + Float expRes = (float) 99.9; + IRainbowMessage event1 = new RainbowESEBMessage(); + try { + event1.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, + AcmeModelEventType.SET_PROPERTY_VALUE.toString()); + event1.setProperty(AcmeModelOperation.PROPERTY_PROP, + "ZNewsSys.Server0.load"); + event1.setProperty(AcmeModelOperation.VALUE_PROP, "1"); + event1.setProperty(ESEBConstants.MSG_SENT, + System.currentTimeMillis() + ""); + } catch (RainbowException e) { + Logger.getLogger(MockDatabaseConnector.class.getName()).log( + Level.SEVERE, null, e); + } + Date end = new Date(); + IRainbowMessage event2 = new RainbowESEBMessage(); + List events = new ArrayList<>(); + events.add(event1); + events.add(event2); + return events; + } + + @Override + public List getEventRangeByType(String channel, + Date startTime, Date endTime) { + IRainbowMessage event1 = new RainbowESEBMessage(); + IRainbowMessage event2 = new RainbowESEBMessage(); + List events = new ArrayList<>(); + events.add(event1); + events.add(event2); + return events; + } + + @Override + public List getModelEventRange(Date startTime, Date endTime) { + Float expRes = (float) 99.9; + IRainbowMessage event1 = new RainbowESEBMessage(); + IRainbowMessage event2 = new RainbowESEBMessage(); + try { + event1.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, + AcmeModelEventType.SET_PROPERTY_VALUE.toString()); + event1.setProperty(AcmeModelOperation.PROPERTY_PROP, + "ZNewsSys.Server0.load"); + event1.setProperty(AcmeModelOperation.VALUE_PROP, expRes.toString()); + event1.setProperty(ESEBConstants.MSG_SENT, + System.currentTimeMillis() + ""); + event2.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, + AcmeModelEventType.SET_PROPERTY_VALUE.toString()); + event2.setProperty(AcmeModelOperation.PROPERTY_PROP, + "ZNewsSys.Server0.load"); + event2.setProperty(AcmeModelOperation.VALUE_PROP, expRes.toString()); + event2.setProperty(ESEBConstants.MSG_SENT, + System.currentTimeMillis() + ""); + + } catch (RainbowException ex) { + Logger.getLogger(MockDatabaseConnector.class.getName()).log( + Level.SEVERE, null, ex); + } + List events = new ArrayList<>(); + events.add(event1); + events.add(event2); + return events; + } + + @Override + public IRainbowMessage getEvent(Date time) { + IRainbowMessage event = new RainbowESEBMessage(); + try { + event.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, + AcmeModelEventType.SET_PROPERTY_VALUE.toString()); + event.setProperty(AcmeModelOperation.PROPERTY_PROP, + "ZNewsSys.Server0.load"); + + } catch (RainbowException ex) { + Logger.getLogger(MockDatabaseConnector.class.getName()).log( + Level.SEVERE, null, ex); + } + return event; + } + + @Override + public void useSession(String name) { + // Do nothing + } + + @Override + public ArrayList getSessionList() { + ArrayList sessions = new ArrayList<>(); + return sessions; + } + + @Override + public void createSession(String name) { + // Do nothing + } + + @Override + public String getWriteSession() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String getReadSession() { + return "mockSession"; + } + + @Override + public void closeWriteSession() { + // Do nothing + } + + @Override + public ArrayList getConfigurationList(String type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getLatestConfigurationName(String type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getConfiguration(String type, String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void writeConfiguration(String config, String type, String name) { + // TODO Auto-generated method stub + + } + + @Override + public Date getStartDate() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean currentSessionIsWriteSession() { + // TODO Auto-generated method stub + return false; + } + + @Override + public Date getMaxDate() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getNumberOfEventsBefore(Date endTime, + int numEvents) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void closeConnection() { + // Do nothing + } + +} diff --git a/ide/raindroid/raindroid/.gitignore b/ide/raindroid/raindroid/.gitignore index 3543521e9..796b96d1c 100644 --- a/ide/raindroid/raindroid/.gitignore +++ b/ide/raindroid/raindroid/.gitignore @@ -1 +1 @@ -/build +/build diff --git a/ide/raindroid/raindroid/build.gradle b/ide/raindroid/raindroid/build.gradle index 71f5cc56a..e0179f3ec 100644 --- a/ide/raindroid/raindroid/build.gradle +++ b/ide/raindroid/raindroid/build.gradle @@ -1,27 +1,27 @@ -apply plugin: 'com.android.application' - -android { - compileSdkVersion 22 - buildToolsVersion "22.0.1" - - defaultConfig { - applicationId "org.sa.rainbow.raindroid" - minSdkVersion 17 - targetSdkVersion 22 - versionCode 1 - versionName "1.0" - } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - } -} - -dependencies { - compile fileTree(dir: 'libs', include: ['*.jar']) - testCompile 'junit:junit:4.12' - compile 'com.android.support:appcompat-v7:22.2.1' - compile 'com.android.support:support-v4:22.2.1' -} +apply plugin: 'com.android.application' + +android { + compileSdkVersion 22 + buildToolsVersion "22.0.1" + + defaultConfig { + applicationId "org.sa.rainbow.raindroid" + minSdkVersion 17 + targetSdkVersion 22 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + testCompile 'junit:junit:4.12' + compile 'com.android.support:appcompat-v7:22.2.1' + compile 'com.android.support:support-v4:22.2.1' +} diff --git a/ide/raindroid/raindroid/proguard-rules.pro b/ide/raindroid/raindroid/proguard-rules.pro index a6191caae..0152b2092 100644 --- a/ide/raindroid/raindroid/proguard-rules.pro +++ b/ide/raindroid/raindroid/proguard-rules.pro @@ -1,17 +1,17 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in C:\Users\schmerl\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in C:\Users\schmerl\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/ide/raindroid/raindroid/src/androidTest/java/org/sa/rainbow/raindroid/ApplicationTest.java b/ide/raindroid/raindroid/src/androidTest/java/org/sa/rainbow/raindroid/ApplicationTest.java index fc5748195..fd885e304 100644 --- a/ide/raindroid/raindroid/src/androidTest/java/org/sa/rainbow/raindroid/ApplicationTest.java +++ b/ide/raindroid/raindroid/src/androidTest/java/org/sa/rainbow/raindroid/ApplicationTest.java @@ -1,13 +1,13 @@ -package org.sa.rainbow.raindroid; - -import android.app.Application; -import android.test.ApplicationTestCase; - -/** - * Testing Fundamentals - */ -public class ApplicationTest extends ApplicationTestCase { - public ApplicationTest() { - super(Application.class); - } +package org.sa.rainbow.raindroid; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } } \ No newline at end of file diff --git a/ide/raindroid/raindroid/src/main/AndroidManifest.xml b/ide/raindroid/raindroid/src/main/AndroidManifest.xml index fea14751a..adab1cccd 100644 --- a/ide/raindroid/raindroid/src/main/AndroidManifest.xml +++ b/ide/raindroid/raindroid/src/main/AndroidManifest.xml @@ -1,35 +1,35 @@ - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/HuILActivity.java b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/HuILActivity.java index fa094ed3e..44eb7bfb9 100644 --- a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/HuILActivity.java +++ b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/HuILActivity.java @@ -1,73 +1,73 @@ -package org.sa.rainbow.raindroid; - -import android.app.AlertDialog; -import android.content.ComponentName; -import android.content.DialogInterface; -import android.content.Intent; -import android.support.v7.app.AppCompatActivity; -import android.os.Bundle; -import android.view.View; - -import org.sa.rainbow.raindroid.org.sa.rainbow.randroid.util.RaindroidMessages; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * This class implements an invisible Activity that can be used as the context for - * bringing up a dialog to interact with the user. - * Currently, the activity has hardwired into it responses for what to do with intents, - * rather than policies for how to make a choice. One extension would be to make this - * more general. - */ -public class HuILActivity extends AppCompatActivity { - - /** The choice of what to do with an implicit intent **/ - private String m_intentDisposition = RaindroidMessages.MSG_RAINDROID_INTENT_PREVENT; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_hu_il); - - // What to do when the OK button is pressed - DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - - dialog.dismiss(); - Integer id = (Integer) getIntent().getIntExtra("stateId", -1); - // Send the choice via the Proxy service back to the application-Raindroid bridge - RaindroidProxyService.instance().dispositionIntent(id, m_intentDisposition); - // Go back to the previous activity (this might not be the wisest thing - onBackPressed(); - } - }; - - // Bring up an alert dialog to make a choice - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle("Dangerous activity detected. Proceed?") - .setSingleChoiceItems(new String[]{"Send to good", "Do not send", "Send"}, 1, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - switch (which) { - case 0: // Send to known good - m_intentDisposition = RaindroidMessages.MSG_RAINDROID_INTENT_SEND_TO_GOOD; - break; - case 1: // Do not send - m_intentDisposition = RaindroidMessages.MSG_RAINBOW_INTENT_NO_EFFECT; - break; - case 2: // Send as normal - m_intentDisposition = RaindroidMessages.MSG_RAINBOW_INTENT_NO_EFFECT; - break; - } - } - }) - .setPositiveButton("OK", dialogClickListener) - .show(); - } - - - - -} +package org.sa.rainbow.raindroid; + +import android.app.AlertDialog; +import android.content.ComponentName; +import android.content.DialogInterface; +import android.content.Intent; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.view.View; + +import org.sa.rainbow.raindroid.org.sa.rainbow.randroid.util.RaindroidMessages; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * This class implements an invisible Activity that can be used as the context for + * bringing up a dialog to interact with the user. + * Currently, the activity has hardwired into it responses for what to do with intents, + * rather than policies for how to make a choice. One extension would be to make this + * more general. + */ +public class HuILActivity extends AppCompatActivity { + + /** The choice of what to do with an implicit intent **/ + private String m_intentDisposition = RaindroidMessages.MSG_RAINDROID_INTENT_PREVENT; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_hu_il); + + // What to do when the OK button is pressed + DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + dialog.dismiss(); + Integer id = (Integer) getIntent().getIntExtra("stateId", -1); + // Send the choice via the Proxy service back to the application-Raindroid bridge + RaindroidProxyService.instance().dispositionIntent(id, m_intentDisposition); + // Go back to the previous activity (this might not be the wisest thing + onBackPressed(); + } + }; + + // Bring up an alert dialog to make a choice + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle("Dangerous activity detected. Proceed?") + .setSingleChoiceItems(new String[]{"Send to good", "Do not send", "Send"}, 1, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + switch (which) { + case 0: // Send to known good + m_intentDisposition = RaindroidMessages.MSG_RAINDROID_INTENT_SEND_TO_GOOD; + break; + case 1: // Do not send + m_intentDisposition = RaindroidMessages.MSG_RAINBOW_INTENT_NO_EFFECT; + break; + case 2: // Send as normal + m_intentDisposition = RaindroidMessages.MSG_RAINBOW_INTENT_NO_EFFECT; + break; + } + } + }) + .setPositiveButton("OK", dialogClickListener) + .show(); + } + + + + +} diff --git a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/RainbowConnectionManager.java b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/RainbowConnectionManager.java index 16be137cb..84309a02f 100644 --- a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/RainbowConnectionManager.java +++ b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/RainbowConnectionManager.java @@ -1,87 +1,87 @@ -package org.sa.rainbow.raindroid; - -import android.util.Log; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.net.InetAddress; -import java.net.Socket; - -/** - * Created by schmerl on 12/14/2015. - */ -public class RainbowConnectionManager { - - public static final int SERVERPORT = 5011; - public static final String SERVER_IP = "128.2.219.56"; - public SocketThread m_socketThread; - - private static RainbowConnectionManager s_instance; - - - protected RainbowConnectionManager () {} - - public static RainbowConnectionManager instance () { - if (s_instance == null) - s_instance = new RainbowConnectionManager(); - return s_instance; - } - - - - public void sendPackageInfo(String[] packages) { - - for (String p : packages) { - getRainbowOutputStream("I[" + p + "]"); - } - } - - - public void appInstalled (String p) { - getRainbowOutputStream("I["+p+"]"); - } - - public void appUninstalled (String p) { - getRainbowOutputStream("U[" + p + "]"); - } - - public void appActivated (String p) { - getRainbowOutputStream("A[" + p + "]"); - } - - public void appDeactivated (String p) { - getRainbowOutputStream ("D[" + p + "]"); - } - - - protected void getRainbowOutputStream(String w) { - Log.d("RAINDORID", w); -// return; - if (m_socketThread != null) { - synchronized (m_socketThread) { - m_socketThread.m_pw.println (w); - } - } else { - m_socketThread = new SocketThread(this); - new Thread(m_socketThread).start(); - synchronized (m_socketThread) { - try { - m_socketThread.wait(5000); - if (m_socketThread.m_pw == null) { - Log.d("RAINDROID", "Could not open socket"); - m_socketThread = null; - return; - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - m_socketThread.m_pw.println (w); - } - } - - } - - -} +package org.sa.rainbow.raindroid; + +import android.util.Log; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.InetAddress; +import java.net.Socket; + +/** + * Created by schmerl on 12/14/2015. + */ +public class RainbowConnectionManager { + + public static final int SERVERPORT = 5011; + public static final String SERVER_IP = "128.2.219.56"; + public SocketThread m_socketThread; + + private static RainbowConnectionManager s_instance; + + + protected RainbowConnectionManager () {} + + public static RainbowConnectionManager instance () { + if (s_instance == null) + s_instance = new RainbowConnectionManager(); + return s_instance; + } + + + + public void sendPackageInfo(String[] packages) { + + for (String p : packages) { + getRainbowOutputStream("I[" + p + "]"); + } + } + + + public void appInstalled (String p) { + getRainbowOutputStream("I["+p+"]"); + } + + public void appUninstalled (String p) { + getRainbowOutputStream("U[" + p + "]"); + } + + public void appActivated (String p) { + getRainbowOutputStream("A[" + p + "]"); + } + + public void appDeactivated (String p) { + getRainbowOutputStream ("D[" + p + "]"); + } + + + protected void getRainbowOutputStream(String w) { + Log.d("RAINDORID", w); +// return; + if (m_socketThread != null) { + synchronized (m_socketThread) { + m_socketThread.m_pw.println (w); + } + } else { + m_socketThread = new SocketThread(this); + new Thread(m_socketThread).start(); + synchronized (m_socketThread) { + try { + m_socketThread.wait(5000); + if (m_socketThread.m_pw == null) { + Log.d("RAINDROID", "Could not open socket"); + m_socketThread = null; + return; + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + m_socketThread.m_pw.println (w); + } + } + + } + + +} diff --git a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/RaindroidProxyService.java b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/RaindroidProxyService.java index d9da508cc..c4902916d 100644 --- a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/RaindroidProxyService.java +++ b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/RaindroidProxyService.java @@ -1,187 +1,187 @@ -package org.sa.rainbow.raindroid; - -import android.app.Service; -import android.content.ComponentName; -import android.content.Intent; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.os.Handler; -import android.os.IBinder; -import android.os.Message; -import android.os.Messenger; -import android.os.RemoteException; -import android.util.Log; - -import org.sa.rainbow.raindroid.org.sa.rainbow.randroid.util.RaindroidMessages; - -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * This class implements the RaindroidProxyService which should manage local - * choices about what to do with various events that happen in apps. These - * events are communicated to the sevice via messages from an Xposed module - * that is attached to all apps on the device. The service should make a decision - * about what the appropriate disposition of the event should be, by either doing - * this locally, or communicating with Rainbow to make the decision. - *

- * The application will wait for a response from the service, and so this decision - * needs to be made quickly (and synchronously) to prevent user annoyance. - *

- * Currently this class only supports intent events and makes the choices locally - * (or through human interaction via the HuILActivity) - */ -public class RaindroidProxyService extends Service { - - private int m_nextState = 0; - private boolean m_askUser = true; - - // The packages list contains information about installed apps - private List m_packages = null; - static RaindroidProxyService m_serviceIntance; - - private Map m_appData = new HashMap<> (); - private boolean m_listedPackageInfo = false; - - public static RaindroidProxyService instance() { - return m_serviceIntance; - } - - public boolean isAskUser() { - return m_askUser; - } - - class ServiceState { - public Intent m_intent; - public Messenger m_replyTo; - } - - /** - * Buld a list of package information for Rainbow - */ - private void listPackageInfo() { - if (!m_listedPackageInfo) { - // Load the list of installed packages when the service starts - m_packages = getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA); - - for (ApplicationInfo packageInfo : m_packages) { - RainbowConnectionManager.instance().appInstalled(packageInfo.packageName); - } - m_listedPackageInfo = true; - } - - - // Log app information. In the future this information will be sent to Rainbow for analysis -// for (ApplicationInfo packageInfo : m_packages) { -// Log.d("RD_LIST", "Installed package :" + packageInfo.packageName); -// Log.d("RD_LIST", "Source dir : " + packageInfo.sourceDir); -// Log.d("RD_LIST", "Launch Activity :" + m_pkgMgr.getLaunchIntentForPackage(packageInfo.packageName)); -// Log.d("RD_LIST", "Permission :" + packageInfo.permission); -// // API > 21 Log.d("RD_LIST", "Version : " + packageInfo.versionCode); -// -// if (packageInfo.enabled == false) { -// Log.d("LIST", packageInfo.packageName + " : disabled"); -// } else { -// Log.d("LIST", packageInfo.packageName + " : enabled"); -// } -// } - } - - private Map m_states = new HashMap<>(); - - protected Integer nextStateId() { - return m_nextState++; - } - - public void dispositionIntent(Integer id, String choice) { - ServiceState ss = m_states.get(id); - if (ss == null) - return; - handleIntentSent(ss.m_replyTo, (Intent) ss.m_intent, choice); - } - - class IncomingHandler extends Handler { - @Override - public void handleMessage(Message msg) { - listPackageInfo(); - switch (msg.what) { - case RaindroidMessages.MSG_RAINDROID_APP_STARTED: - String app = msg.getData().getString(RaindroidMessages.MSG_APP_PACKAGE); - boolean alreadySeen = m_appData.put(app, new Date()) != null; - if (!alreadySeen) { - // send app started message to Rainbow - Log.i (RaindroidMessages.getTag(), String.format("Application %s has started running", app)); - RainbowConnectionManager.instance().appActivated(app); - } - break; - case RaindroidMessages.MSG_RAINDROID_APP_STOPPED: - app = msg.getData().getString(RaindroidMessages.MSG_APP_PACKAGE); - boolean wasKnown = m_appData.remove(app) != null; - if (wasKnown) { - // send app stopped message to Rainbow - Log.i (RaindroidMessages.getTag(), String.format("Application %s has stopped running", app)); - RainbowConnectionManager.instance ().appDeactivated(app); - } - - case RaindroidMessages.MSG_RAINDROID_INTENT_SENT: - - if (isAskUser()) { - ServiceState ss = new ServiceState(); - ss.m_intent = (Intent) msg.getData().getParcelable(RaindroidMessages.MSG_RANDROID_INTENT_DATA_KEY); - ss.m_replyTo = msg.replyTo; - Integer id = nextStateId(); - m_states.put(id, ss); - Intent i = new Intent(RaindroidProxyService.this, HuILActivity.class); - i.putExtra("stateId", id); - i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(i); - } else { - RaindroidProxyService.this.handleIntentSent(msg.replyTo, (Intent) msg.getData().getParcelable(RaindroidMessages.MSG_RANDROID_INTENT_DATA_KEY), RaindroidMessages.MSG_RAINDROID_INTENT_PREVENT); - } - break; - case RaindroidMessages.MSG_RAINDROID_INTENT_RECEIVED: - // send intent received event to Rainbow - Log.d(RaindroidMessages.getTag(), String.format("%s received an intent from %s", msg.getData().getString(RaindroidMessages.MSG_RAINDROID_INTENT_RECEIVER_KEY), msg.getData().getString(RaindroidMessages.MSG_RAINDROID_INTENT_SENDER_KEY))); - break; - } - super.handleMessage(msg); - } - } - - - private final Messenger m_messenger = new Messenger(new IncomingHandler()); - - - public RaindroidProxyService() { - m_serviceIntance = this; - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - super.onStartCommand(intent, flags, startId); - // Uncomment the below -- moved to do debugging - // listPackageInfo(); - return Service.START_REDELIVER_INTENT; - } - - @Override - public IBinder onBind(Intent intent) { - return m_messenger.getBinder(); - } - - protected static void handleIntentSent(Messenger replyTo, Intent i, String disposition) { - ComponentName cmp = i.getComponent(); - if (cmp == null) { - try { - Message msg = Message.obtain(null, RaindroidMessages.MSG_RAINDROID_EFFECT); - msg.getData().putString(RaindroidMessages.MSG_RAINDROID_EFFECT_KEY, disposition); - replyTo.send(msg); - } catch (RemoteException e) { - e.printStackTrace(); - } - } - } - -} +package org.sa.rainbow.raindroid; + +import android.app.Service; +import android.content.ComponentName; +import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.os.Handler; +import android.os.IBinder; +import android.os.Message; +import android.os.Messenger; +import android.os.RemoteException; +import android.util.Log; + +import org.sa.rainbow.raindroid.org.sa.rainbow.randroid.util.RaindroidMessages; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * This class implements the RaindroidProxyService which should manage local + * choices about what to do with various events that happen in apps. These + * events are communicated to the sevice via messages from an Xposed module + * that is attached to all apps on the device. The service should make a decision + * about what the appropriate disposition of the event should be, by either doing + * this locally, or communicating with Rainbow to make the decision. + *

+ * The application will wait for a response from the service, and so this decision + * needs to be made quickly (and synchronously) to prevent user annoyance. + *

+ * Currently this class only supports intent events and makes the choices locally + * (or through human interaction via the HuILActivity) + */ +public class RaindroidProxyService extends Service { + + private int m_nextState = 0; + private boolean m_askUser = true; + + // The packages list contains information about installed apps + private List m_packages = null; + static RaindroidProxyService m_serviceIntance; + + private Map m_appData = new HashMap<> (); + private boolean m_listedPackageInfo = false; + + public static RaindroidProxyService instance() { + return m_serviceIntance; + } + + public boolean isAskUser() { + return m_askUser; + } + + class ServiceState { + public Intent m_intent; + public Messenger m_replyTo; + } + + /** + * Buld a list of package information for Rainbow + */ + private void listPackageInfo() { + if (!m_listedPackageInfo) { + // Load the list of installed packages when the service starts + m_packages = getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA); + + for (ApplicationInfo packageInfo : m_packages) { + RainbowConnectionManager.instance().appInstalled(packageInfo.packageName); + } + m_listedPackageInfo = true; + } + + + // Log app information. In the future this information will be sent to Rainbow for analysis +// for (ApplicationInfo packageInfo : m_packages) { +// Log.d("RD_LIST", "Installed package :" + packageInfo.packageName); +// Log.d("RD_LIST", "Source dir : " + packageInfo.sourceDir); +// Log.d("RD_LIST", "Launch Activity :" + m_pkgMgr.getLaunchIntentForPackage(packageInfo.packageName)); +// Log.d("RD_LIST", "Permission :" + packageInfo.permission); +// // API > 21 Log.d("RD_LIST", "Version : " + packageInfo.versionCode); +// +// if (packageInfo.enabled == false) { +// Log.d("LIST", packageInfo.packageName + " : disabled"); +// } else { +// Log.d("LIST", packageInfo.packageName + " : enabled"); +// } +// } + } + + private Map m_states = new HashMap<>(); + + protected Integer nextStateId() { + return m_nextState++; + } + + public void dispositionIntent(Integer id, String choice) { + ServiceState ss = m_states.get(id); + if (ss == null) + return; + handleIntentSent(ss.m_replyTo, (Intent) ss.m_intent, choice); + } + + class IncomingHandler extends Handler { + @Override + public void handleMessage(Message msg) { + listPackageInfo(); + switch (msg.what) { + case RaindroidMessages.MSG_RAINDROID_APP_STARTED: + String app = msg.getData().getString(RaindroidMessages.MSG_APP_PACKAGE); + boolean alreadySeen = m_appData.put(app, new Date()) != null; + if (!alreadySeen) { + // send app started message to Rainbow + Log.i (RaindroidMessages.getTag(), String.format("Application %s has started running", app)); + RainbowConnectionManager.instance().appActivated(app); + } + break; + case RaindroidMessages.MSG_RAINDROID_APP_STOPPED: + app = msg.getData().getString(RaindroidMessages.MSG_APP_PACKAGE); + boolean wasKnown = m_appData.remove(app) != null; + if (wasKnown) { + // send app stopped message to Rainbow + Log.i (RaindroidMessages.getTag(), String.format("Application %s has stopped running", app)); + RainbowConnectionManager.instance ().appDeactivated(app); + } + + case RaindroidMessages.MSG_RAINDROID_INTENT_SENT: + + if (isAskUser()) { + ServiceState ss = new ServiceState(); + ss.m_intent = (Intent) msg.getData().getParcelable(RaindroidMessages.MSG_RANDROID_INTENT_DATA_KEY); + ss.m_replyTo = msg.replyTo; + Integer id = nextStateId(); + m_states.put(id, ss); + Intent i = new Intent(RaindroidProxyService.this, HuILActivity.class); + i.putExtra("stateId", id); + i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(i); + } else { + RaindroidProxyService.this.handleIntentSent(msg.replyTo, (Intent) msg.getData().getParcelable(RaindroidMessages.MSG_RANDROID_INTENT_DATA_KEY), RaindroidMessages.MSG_RAINDROID_INTENT_PREVENT); + } + break; + case RaindroidMessages.MSG_RAINDROID_INTENT_RECEIVED: + // send intent received event to Rainbow + Log.d(RaindroidMessages.getTag(), String.format("%s received an intent from %s", msg.getData().getString(RaindroidMessages.MSG_RAINDROID_INTENT_RECEIVER_KEY), msg.getData().getString(RaindroidMessages.MSG_RAINDROID_INTENT_SENDER_KEY))); + break; + } + super.handleMessage(msg); + } + } + + + private final Messenger m_messenger = new Messenger(new IncomingHandler()); + + + public RaindroidProxyService() { + m_serviceIntance = this; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + super.onStartCommand(intent, flags, startId); + // Uncomment the below -- moved to do debugging + // listPackageInfo(); + return Service.START_REDELIVER_INTENT; + } + + @Override + public IBinder onBind(Intent intent) { + return m_messenger.getBinder(); + } + + protected static void handleIntentSent(Messenger replyTo, Intent i, String disposition) { + ComponentName cmp = i.getComponent(); + if (cmp == null) { + try { + Message msg = Message.obtain(null, RaindroidMessages.MSG_RAINDROID_EFFECT); + msg.getData().putString(RaindroidMessages.MSG_RAINDROID_EFFECT_KEY, disposition); + replyTo.send(msg); + } catch (RemoteException e) { + e.printStackTrace(); + } + } + } + +} diff --git a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/SocketThread.java b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/SocketThread.java index 86986b6e3..f97e56eb3 100644 --- a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/SocketThread.java +++ b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/SocketThread.java @@ -1,43 +1,43 @@ -package org.sa.rainbow.raindroid; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.net.InetAddress; -import java.net.Socket; - -public class SocketThread implements Runnable { - - - private static final long SLEEP_TIME = 10000; - private final RainbowConnectionManager m_manager; - public PrintWriter m_pw; - - public SocketThread(RainbowConnectionManager manager) { - m_manager = manager; - } - - @Override - public void run() { - try { - InetAddress serverAddr = InetAddress.getByName(RainbowConnectionManager.SERVER_IP); - Socket socket = new Socket(serverAddr, RainbowConnectionManager.SERVERPORT); - m_pw = new PrintWriter (socket.getOutputStream(), true); - synchronized (this) { - this.notifyAll(); - } - Thread.sleep(SLEEP_TIME); - synchronized (this) { - m_pw = null; - socket.close(); - } - m_manager.m_socketThread = null; - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - -} +package org.sa.rainbow.raindroid; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.InetAddress; +import java.net.Socket; + +public class SocketThread implements Runnable { + + + private static final long SLEEP_TIME = 10000; + private final RainbowConnectionManager m_manager; + public PrintWriter m_pw; + + public SocketThread(RainbowConnectionManager manager) { + m_manager = manager; + } + + @Override + public void run() { + try { + InetAddress serverAddr = InetAddress.getByName(RainbowConnectionManager.SERVER_IP); + Socket socket = new Socket(serverAddr, RainbowConnectionManager.SERVERPORT); + m_pw = new PrintWriter (socket.getOutputStream(), true); + synchronized (this) { + this.notifyAll(); + } + Thread.sleep(SLEEP_TIME); + synchronized (this) { + m_pw = null; + socket.close(); + } + m_manager.m_socketThread = null; + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/StartRaindroidReceiver.java b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/StartRaindroidReceiver.java index ee98e9c03..eef99c352 100644 --- a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/StartRaindroidReceiver.java +++ b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/StartRaindroidReceiver.java @@ -1,20 +1,20 @@ -package org.sa.rainbow.raindroid; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.util.Log; - -public class StartRaindroidReceiver extends BroadcastReceiver { - public StartRaindroidReceiver() { - } - - @Override - public void onReceive(Context context, Intent intent) { - Log.d("RANDROID", "Starting Raindroid"); - if (Intent.ACTION_BOOT_COMPLETED.equals (intent.getAction())) { - Intent serviceIntent = new Intent(context, RaindroidProxyService.class); - context.startService(serviceIntent); - } - } -} +package org.sa.rainbow.raindroid; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.util.Log; + +public class StartRaindroidReceiver extends BroadcastReceiver { + public StartRaindroidReceiver() { + } + + @Override + public void onReceive(Context context, Intent intent) { + Log.d("RANDROID", "Starting Raindroid"); + if (Intent.ACTION_BOOT_COMPLETED.equals (intent.getAction())) { + Intent serviceIntent = new Intent(context, RaindroidProxyService.class); + context.startService(serviceIntent); + } + } +} diff --git a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/org/sa/rainbow/randroid/util/RaindroidMessages.java b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/org/sa/rainbow/randroid/util/RaindroidMessages.java index cd5e9f51a..763abd853 100644 --- a/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/org/sa/rainbow/randroid/util/RaindroidMessages.java +++ b/ide/raindroid/raindroid/src/main/java/org/sa/rainbow/raindroid/org/sa/rainbow/randroid/util/RaindroidMessages.java @@ -1,41 +1,41 @@ -package org.sa.rainbow.raindroid.org.sa.rainbow.randroid.util; - -/** - * Created by schmerl on 10/27/2015. - */ -public class RaindroidMessages { - - public static final int MSG_RAINDROID_INTENT_SENT = 1; - public static final int MSG_RAINDROID_INTENT_RECEIVED = 2; - public static final int MSG_RAINDROID_APP_STARTED = 3; - public static final int MSG_RAINDROID_APP_STOPPED = 4; - - public static final String MSG_RANDROID_INTENT_DATA_KEY = "SENT_INTENT"; - public static final String MSG_RAINDROID_INTENT_PREVENT = "__prevent__"; - public static final String MSG_RAINDROID_INTENT_SEND_TO_GOOD = "__send_to_good__"; - public static final String MSG_RAINBOW_INTENT_NO_EFFECT = "__no_effect__"; - public static final String MSG_RAINDROID_EFFECT_KEY = "__RAINDROID__EFFECT__"; - - public static final int MSG_RAINDROID_EFFECT = 2; - public static final String RAINDROID_CALLER = "__RAINDROID_CALLER__"; - public static final String MSG_RAINDROID_INTENT_RECEIVER_KEY = "INTENT_SENDER"; - public static final String MSG_RAINDROID_INTENT_SENDER_KEY = "INTENT_RECEIVER"; - public static final String MSG_APP_PACKAGE = "PACKAGE_NAME"; - - - public static String getTag () { - StringBuilder tag = new StringBuilder (); - final StackTraceElement[] ste = Thread.currentThread().getStackTrace(); - for (int i = 0; i < ste.length; i++) { - if (ste[i].getMethodName().equals ("getTag")) { - tag.append ("("); - tag.append (ste[i+1].getFileName() + ":" + ste[i+1].getLineNumber()); - tag.append ("):"); - tag.append (ste [i+1].getClassName()); - tag.append ("."); - tag.append (ste[i+1].getMethodName()); - } - } - return tag.toString(); - } -} +package org.sa.rainbow.raindroid.org.sa.rainbow.randroid.util; + +/** + * Created by schmerl on 10/27/2015. + */ +public class RaindroidMessages { + + public static final int MSG_RAINDROID_INTENT_SENT = 1; + public static final int MSG_RAINDROID_INTENT_RECEIVED = 2; + public static final int MSG_RAINDROID_APP_STARTED = 3; + public static final int MSG_RAINDROID_APP_STOPPED = 4; + + public static final String MSG_RANDROID_INTENT_DATA_KEY = "SENT_INTENT"; + public static final String MSG_RAINDROID_INTENT_PREVENT = "__prevent__"; + public static final String MSG_RAINDROID_INTENT_SEND_TO_GOOD = "__send_to_good__"; + public static final String MSG_RAINBOW_INTENT_NO_EFFECT = "__no_effect__"; + public static final String MSG_RAINDROID_EFFECT_KEY = "__RAINDROID__EFFECT__"; + + public static final int MSG_RAINDROID_EFFECT = 2; + public static final String RAINDROID_CALLER = "__RAINDROID_CALLER__"; + public static final String MSG_RAINDROID_INTENT_RECEIVER_KEY = "INTENT_SENDER"; + public static final String MSG_RAINDROID_INTENT_SENDER_KEY = "INTENT_RECEIVER"; + public static final String MSG_APP_PACKAGE = "PACKAGE_NAME"; + + + public static String getTag () { + StringBuilder tag = new StringBuilder (); + final StackTraceElement[] ste = Thread.currentThread().getStackTrace(); + for (int i = 0; i < ste.length; i++) { + if (ste[i].getMethodName().equals ("getTag")) { + tag.append ("("); + tag.append (ste[i+1].getFileName() + ":" + ste[i+1].getLineNumber()); + tag.append ("):"); + tag.append (ste [i+1].getClassName()); + tag.append ("."); + tag.append (ste[i+1].getMethodName()); + } + } + return tag.toString(); + } +} diff --git a/ide/raindroid/raindroid/src/main/res/layout/activity_hu_il.xml b/ide/raindroid/raindroid/src/main/res/layout/activity_hu_il.xml index e24b390fc..7d0d26a48 100644 --- a/ide/raindroid/raindroid/src/main/res/layout/activity_hu_il.xml +++ b/ide/raindroid/raindroid/src/main/res/layout/activity_hu_il.xml @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/ide/raindroid/raindroid/src/main/res/values-w820dp/dimens.xml b/ide/raindroid/raindroid/src/main/res/values-w820dp/dimens.xml index 62df1875a..63fc81644 100644 --- a/ide/raindroid/raindroid/src/main/res/values-w820dp/dimens.xml +++ b/ide/raindroid/raindroid/src/main/res/values-w820dp/dimens.xml @@ -1,6 +1,6 @@ - - - 64dp - + + + 64dp + diff --git a/ide/raindroid/raindroid/src/main/res/values/attrs.xml b/ide/raindroid/raindroid/src/main/res/values/attrs.xml index 0917430c8..7ce840eb6 100644 --- a/ide/raindroid/raindroid/src/main/res/values/attrs.xml +++ b/ide/raindroid/raindroid/src/main/res/values/attrs.xml @@ -1,12 +1,12 @@ - - - - - - - - - + + + + + + + + + diff --git a/ide/raindroid/raindroid/src/main/res/values/colors.xml b/ide/raindroid/raindroid/src/main/res/values/colors.xml index 28d03291f..227fd3312 100644 --- a/ide/raindroid/raindroid/src/main/res/values/colors.xml +++ b/ide/raindroid/raindroid/src/main/res/values/colors.xml @@ -1,8 +1,8 @@ - - - #3F51B5 - #303F9F - #FF4081 - - #66000000 - + + + #3F51B5 + #303F9F + #FF4081 + + #66000000 + diff --git a/ide/raindroid/raindroid/src/main/res/values/dimens.xml b/ide/raindroid/raindroid/src/main/res/values/dimens.xml index 295b5a9de..47c822467 100644 --- a/ide/raindroid/raindroid/src/main/res/values/dimens.xml +++ b/ide/raindroid/raindroid/src/main/res/values/dimens.xml @@ -1,5 +1,5 @@ - - - 16dp - 16dp - + + + 16dp + 16dp + diff --git a/ide/raindroid/raindroid/src/main/res/values/strings.xml b/ide/raindroid/raindroid/src/main/res/values/strings.xml index 69fb787a7..68075687c 100644 --- a/ide/raindroid/raindroid/src/main/res/values/strings.xml +++ b/ide/raindroid/raindroid/src/main/res/values/strings.xml @@ -1,8 +1,8 @@ - - Raindroid - - IntentDispositionChoiceActivity - Dummy Button - DUMMY\nCONTENT - OK - + + Raindroid + + IntentDispositionChoiceActivity + Dummy Button + DUMMY\nCONTENT + OK + diff --git a/ide/raindroid/raindroid/src/main/res/values/styles.xml b/ide/raindroid/raindroid/src/main/res/values/styles.xml index 83d1b102a..dc8a48c2a 100644 --- a/ide/raindroid/raindroid/src/main/res/values/styles.xml +++ b/ide/raindroid/raindroid/src/main/res/values/styles.xml @@ -1,23 +1,23 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/ide/raindroid/raindroid/src/test/java/org/sa/rainbow/raindroid/ExampleUnitTest.java b/ide/raindroid/raindroid/src/test/java/org/sa/rainbow/raindroid/ExampleUnitTest.java index 2b0cf6010..eebfd5f23 100644 --- a/ide/raindroid/raindroid/src/test/java/org/sa/rainbow/raindroid/ExampleUnitTest.java +++ b/ide/raindroid/raindroid/src/test/java/org/sa/rainbow/raindroid/ExampleUnitTest.java @@ -1,15 +1,15 @@ -package org.sa.rainbow.raindroid; - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * To work on unit tests, switch the Test Artifact in the Build Variants view. - */ -public class ExampleUnitTest { - @Test - public void addition_isCorrect() throws Exception { - assertEquals(4, 2 + 2); - } +package org.sa.rainbow.raindroid; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * To work on unit tests, switch the Test Artifact in the Build Variants view. + */ +public class ExampleUnitTest { + @Test + public void addition_isCorrect() throws Exception { + assertEquals(4, 2 + 2); + } } \ No newline at end of file diff --git a/ide/raindroid/raindroidxposed/.gitignore b/ide/raindroid/raindroidxposed/.gitignore index 3543521e9..796b96d1c 100644 --- a/ide/raindroid/raindroidxposed/.gitignore +++ b/ide/raindroid/raindroidxposed/.gitignore @@ -1 +1 @@ -/build +/build diff --git a/ide/raindroid/raindroidxposed/build.gradle b/ide/raindroid/raindroidxposed/build.gradle index 01cab8462..84e658333 100644 --- a/ide/raindroid/raindroidxposed/build.gradle +++ b/ide/raindroid/raindroidxposed/build.gradle @@ -1,27 +1,27 @@ -apply plugin: 'com.android.application' - -android { - compileSdkVersion 17 - buildToolsVersion "19.1.0" - defaultConfig { - applicationId "com.example.raindroidxposed" - minSdkVersion 17 - targetSdkVersion 17 - versionCode 1 - versionName "1.1" - } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - } - productFlavors { - } -} - -dependencies { - provided fileTree(include: ['*.jar'], dir: 'libs') - - compile 'com.android.support:appcompat-v7:19+' -} +apply plugin: 'com.android.application' + +android { + compileSdkVersion 17 + buildToolsVersion "19.1.0" + defaultConfig { + applicationId "com.example.raindroidxposed" + minSdkVersion 17 + targetSdkVersion 17 + versionCode 1 + versionName "1.1" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + productFlavors { + } +} + +dependencies { + provided fileTree(include: ['*.jar'], dir: 'libs') + + compile 'com.android.support:appcompat-v7:19+' +} diff --git a/ide/raindroid/raindroidxposed/proguard-rules.pro b/ide/raindroid/raindroidxposed/proguard-rules.pro index 123f67367..0997e8907 100644 --- a/ide/raindroid/raindroidxposed/proguard-rules.pro +++ b/ide/raindroid/raindroidxposed/proguard-rules.pro @@ -1,17 +1,17 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in C:/Users/schmerl/AppData/Local/Android/sdk/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in C:/Users/schmerl/AppData/Local/Android/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/ide/raindroid/raindroidxposed/raindroidxposed.iml b/ide/raindroid/raindroidxposed/raindroidxposed.iml index a05cec0ba..621ae0bb1 100644 --- a/ide/raindroid/raindroidxposed/raindroidxposed.iml +++ b/ide/raindroid/raindroidxposed/raindroidxposed.iml @@ -1,97 +1,97 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ide/raindroid/raindroidxposed/src/androidTest/java/com/example/raindroidxposed/ApplicationTest.java b/ide/raindroid/raindroidxposed/src/androidTest/java/com/example/raindroidxposed/ApplicationTest.java index 3ed22ca34..a21a8ec44 100644 --- a/ide/raindroid/raindroidxposed/src/androidTest/java/com/example/raindroidxposed/ApplicationTest.java +++ b/ide/raindroid/raindroidxposed/src/androidTest/java/com/example/raindroidxposed/ApplicationTest.java @@ -1,13 +1,13 @@ -package com.example.raindroidxposed; - -import android.app.Application; -import android.test.ApplicationTestCase; - -/** - * Testing Fundamentals - */ -public class ApplicationTest extends ApplicationTestCase { - public ApplicationTest() { - super(Application.class); - } +package com.example.raindroidxposed; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } } \ No newline at end of file diff --git a/ide/raindroid/raindroidxposed/src/main/AndroidManifest.xml b/ide/raindroid/raindroidxposed/src/main/AndroidManifest.xml index 0cceef1b3..fa1df3f17 100644 --- a/ide/raindroid/raindroidxposed/src/main/AndroidManifest.xml +++ b/ide/raindroid/raindroidxposed/src/main/AndroidManifest.xml @@ -1,23 +1,23 @@ - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/RaindroidBridge.java b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/RaindroidBridge.java index d363b52fc..b8d180cc6 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/RaindroidBridge.java +++ b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/RaindroidBridge.java @@ -1,185 +1,185 @@ -package com.example.raindroidxposed; - -import android.app.Application; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.ServiceConnection; -import android.os.Bundle; -import android.os.IBinder; -import android.os.Message; -import android.os.Messenger; -import android.os.RemoteException; -import android.util.Log; - -import com.example.raindroidxposed.hooks.OnCreateMethodHook; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import de.robv.android.xposed.IXposedHookLoadPackage; -import de.robv.android.xposed.XposedBridge; -import de.robv.android.xposed.XposedHelpers; -import de.robv.android.xposed.callbacks.XC_LoadPackage; - -import com.example.raindroidxposed.hooks.*; - -import org.sa.rainbow.raindroid.util.RaindroidMessages; - -/** - * This class implements a bridge from an Android app to - * Rainbow. It uses Xposed to insert probes into appropriate - * methods on apps that are identified as potential vulnerability - * points. - *

- * Created by Bradley Schmerl on 9/23/2015. - */ -public class RaindroidBridge implements IXposedHookLoadPackage { - - /** - * The list of packages that should be modified by Xposed - * This should be refactored into the Raindroid service - */ - private final Map> m_interestingPackages; - - /** - * Whether to intercept. This is used when Raindroid says to execute - * the methods, so that we don't get into infinite loops. - */ - private boolean m_intercept = true; - - public void setIntercept(boolean intercept) { - this.m_intercept = intercept; - } - - public boolean isIntercept() { - return m_intercept; - } - - - /** - * Indicates whether the bridge has connected with the Raindroid service - */ - private static boolean m_serviceBound = false; - - private void log(Throwable e) { - e.printStackTrace(System.out); - } - - private static Messenger m_raindroidService = null; - - private static ServiceConnection m_raindroidServiceConnection = new ServiceConnection() { - - @Override - public void onServiceConnected(ComponentName name, IBinder service) { - m_raindroidService = new Messenger(service); - XposedBridge.log("Connected to Raindroid Service"); - synchronized (m_unsentMessages) { - if (!m_unsentMessages.isEmpty()) { - for (Iterator i = m_unsentMessages.iterator(); i.hasNext(); ) { - Message msg = i.next(); - try { - m_raindroidService.send(msg); - i.remove(); - } - catch (Throwable e) { - XposedBridge.log("Still could not send message"); - } - } - } - } - } - - @Override - public void onServiceDisconnected(ComponentName name) { - m_raindroidService = null; - XposedBridge.log("Disconnected from Raindroid Service"); - } - }; - - - /** - * This method is used when an application is loaded, for example when the user launches it or - * when an activity is started - */ - @Override - public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable { - // Ensure that we are in an app that we are interested in - try { - if (!loadPackageParam.packageName.equals("org.sa.rainbow.raindroid")) - XposedHelpers.findAndHookMethod("android.app.Application", loadPackageParam.classLoader, "attach", Context.class, new RegisterWithAndroidHook(this)); - } catch (Throwable t) { - Log.e(RaindroidMessages.getTag(), t.getMessage(), t); - } - if (!m_interestingPackages.keySet().contains(loadPackageParam.packageName)) { - Log.i(RaindroidMessages.getTag(), "Raindroid: package loaded " + loadPackageParam.packageName + " not interested."); - return; - } - - // Only hook the classes that we are interested in - Log.i(RaindroidMessages.getTag(), "Raindroid: package loaded " + loadPackageParam.packageName + " attempting to hook."); - Set classes = m_interestingPackages.get(loadPackageParam.packageName); - if (classes != null && !classes.isEmpty()) { - StringBuilder sb = new StringBuilder(); - for (String cls : classes) { - sb.append(cls).append(", "); - } - sb.delete(sb.length() - 2, sb.length()); - String l = sb.toString(); - Log.i(RaindroidMessages.getTag(), "Raindroid: attempting to hook into " + l); - try { - XposedHelpers.findAndHookMethod("android.app.Activity", loadPackageParam.classLoader, "startActivity", Intent.class, new ActivityMethodHook(this, classes)); - XposedHelpers.findAndHookMethod("android.app.Activity", loadPackageParam.classLoader, "onCreate", Bundle.class, new OnCreateMethodHook(classes)); - XposedHelpers.findAndHookMethod("android.app.Instrumentation", loadPackageParam.classLoader, "newActivity", ClassLoader.class, String.class, Intent.class, new NewActivityHook()); - } catch (Throwable e) { - Log.e(RaindroidMessages.getTag(), "Error! could not hook method '" + l + "'.startActivity", e); - } - } - - } - - private static List m_unsentMessages = new LinkedList(); - - - public RaindroidBridge() { - // Initialize packages that we are interested in - // For now, let's hardwire the example. In future, - // we'll need to do this dynamically, perhaps through - // a file - XposedBridge.log("Loaded RaindroidBridge"); - m_interestingPackages = new HashMap(); - m_interestingPackages.put("sosf.cmu.edu.intentintercept", Collections.singleton("sosf.cmu.edu.activity1.Activity1")); - m_interestingPackages.put("sosf.cmu.edu.maliciousapp", Collections.singleton("sosf.cmu.edu.maliciousapp.MaliciousActivity")); - - } - - public static void sendToRaindroidService(Message msg) throws RemoteException { - if (m_raindroidService == null) { - XposedBridge.log("No binding to the Raindroid service. Msg will not be sent later."); - synchronized (m_unsentMessages) { - m_unsentMessages.add(msg); - } - } - else { - m_raindroidService.send(msg); - } - } - - public static void bindToRaindroid(Context m_context) { - // Establish a connection to the Raindroid service. This will be used for communicating - // events to Rainbow and communicating decisions/adaptations back to this bridge - if (m_context == null) return; - if (!m_serviceBound || m_raindroidService == null) { - Intent intent = new Intent(); - intent.setComponent(new ComponentName("org.sa.rainbow.raindroid", "org.sa.rainbow.raindroid.RaindroidProxyService")); - m_context.bindService(intent, m_raindroidServiceConnection, Context.BIND_AUTO_CREATE); - m_serviceBound = true; - } - } - -} +package com.example.raindroidxposed; + +import android.app.Application; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.os.Bundle; +import android.os.IBinder; +import android.os.Message; +import android.os.Messenger; +import android.os.RemoteException; +import android.util.Log; + +import com.example.raindroidxposed.hooks.OnCreateMethodHook; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import de.robv.android.xposed.IXposedHookLoadPackage; +import de.robv.android.xposed.XposedBridge; +import de.robv.android.xposed.XposedHelpers; +import de.robv.android.xposed.callbacks.XC_LoadPackage; + +import com.example.raindroidxposed.hooks.*; + +import org.sa.rainbow.raindroid.util.RaindroidMessages; + +/** + * This class implements a bridge from an Android app to + * Rainbow. It uses Xposed to insert probes into appropriate + * methods on apps that are identified as potential vulnerability + * points. + *

+ * Created by Bradley Schmerl on 9/23/2015. + */ +public class RaindroidBridge implements IXposedHookLoadPackage { + + /** + * The list of packages that should be modified by Xposed + * This should be refactored into the Raindroid service + */ + private final Map> m_interestingPackages; + + /** + * Whether to intercept. This is used when Raindroid says to execute + * the methods, so that we don't get into infinite loops. + */ + private boolean m_intercept = true; + + public void setIntercept(boolean intercept) { + this.m_intercept = intercept; + } + + public boolean isIntercept() { + return m_intercept; + } + + + /** + * Indicates whether the bridge has connected with the Raindroid service + */ + private static boolean m_serviceBound = false; + + private void log(Throwable e) { + e.printStackTrace(System.out); + } + + private static Messenger m_raindroidService = null; + + private static ServiceConnection m_raindroidServiceConnection = new ServiceConnection() { + + @Override + public void onServiceConnected(ComponentName name, IBinder service) { + m_raindroidService = new Messenger(service); + XposedBridge.log("Connected to Raindroid Service"); + synchronized (m_unsentMessages) { + if (!m_unsentMessages.isEmpty()) { + for (Iterator i = m_unsentMessages.iterator(); i.hasNext(); ) { + Message msg = i.next(); + try { + m_raindroidService.send(msg); + i.remove(); + } + catch (Throwable e) { + XposedBridge.log("Still could not send message"); + } + } + } + } + } + + @Override + public void onServiceDisconnected(ComponentName name) { + m_raindroidService = null; + XposedBridge.log("Disconnected from Raindroid Service"); + } + }; + + + /** + * This method is used when an application is loaded, for example when the user launches it or + * when an activity is started + */ + @Override + public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable { + // Ensure that we are in an app that we are interested in + try { + if (!loadPackageParam.packageName.equals("org.sa.rainbow.raindroid")) + XposedHelpers.findAndHookMethod("android.app.Application", loadPackageParam.classLoader, "attach", Context.class, new RegisterWithAndroidHook(this)); + } catch (Throwable t) { + Log.e(RaindroidMessages.getTag(), t.getMessage(), t); + } + if (!m_interestingPackages.keySet().contains(loadPackageParam.packageName)) { + Log.i(RaindroidMessages.getTag(), "Raindroid: package loaded " + loadPackageParam.packageName + " not interested."); + return; + } + + // Only hook the classes that we are interested in + Log.i(RaindroidMessages.getTag(), "Raindroid: package loaded " + loadPackageParam.packageName + " attempting to hook."); + Set classes = m_interestingPackages.get(loadPackageParam.packageName); + if (classes != null && !classes.isEmpty()) { + StringBuilder sb = new StringBuilder(); + for (String cls : classes) { + sb.append(cls).append(", "); + } + sb.delete(sb.length() - 2, sb.length()); + String l = sb.toString(); + Log.i(RaindroidMessages.getTag(), "Raindroid: attempting to hook into " + l); + try { + XposedHelpers.findAndHookMethod("android.app.Activity", loadPackageParam.classLoader, "startActivity", Intent.class, new ActivityMethodHook(this, classes)); + XposedHelpers.findAndHookMethod("android.app.Activity", loadPackageParam.classLoader, "onCreate", Bundle.class, new OnCreateMethodHook(classes)); + XposedHelpers.findAndHookMethod("android.app.Instrumentation", loadPackageParam.classLoader, "newActivity", ClassLoader.class, String.class, Intent.class, new NewActivityHook()); + } catch (Throwable e) { + Log.e(RaindroidMessages.getTag(), "Error! could not hook method '" + l + "'.startActivity", e); + } + } + + } + + private static List m_unsentMessages = new LinkedList(); + + + public RaindroidBridge() { + // Initialize packages that we are interested in + // For now, let's hardwire the example. In future, + // we'll need to do this dynamically, perhaps through + // a file + XposedBridge.log("Loaded RaindroidBridge"); + m_interestingPackages = new HashMap(); + m_interestingPackages.put("sosf.cmu.edu.intentintercept", Collections.singleton("sosf.cmu.edu.activity1.Activity1")); + m_interestingPackages.put("sosf.cmu.edu.maliciousapp", Collections.singleton("sosf.cmu.edu.maliciousapp.MaliciousActivity")); + + } + + public static void sendToRaindroidService(Message msg) throws RemoteException { + if (m_raindroidService == null) { + XposedBridge.log("No binding to the Raindroid service. Msg will not be sent later."); + synchronized (m_unsentMessages) { + m_unsentMessages.add(msg); + } + } + else { + m_raindroidService.send(msg); + } + } + + public static void bindToRaindroid(Context m_context) { + // Establish a connection to the Raindroid service. This will be used for communicating + // events to Rainbow and communicating decisions/adaptations back to this bridge + if (m_context == null) return; + if (!m_serviceBound || m_raindroidService == null) { + Intent intent = new Intent(); + intent.setComponent(new ComponentName("org.sa.rainbow.raindroid", "org.sa.rainbow.raindroid.RaindroidProxyService")); + m_context.bindService(intent, m_raindroidServiceConnection, Context.BIND_AUTO_CREATE); + m_serviceBound = true; + } + } + +} diff --git a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/RaindroidBridgeOLD.java b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/RaindroidBridgeOLD.java index e6b8b2e5c..8795a5afc 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/RaindroidBridgeOLD.java +++ b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/RaindroidBridgeOLD.java @@ -1,214 +1,214 @@ -package com.example.raindroidxposed; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.AndroidAppHelper; -import android.content.ComponentName; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Bundle; - -import org.sa.rainbow.raindroid.util.RaindroidMessages; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import de.robv.android.xposed.IXposedHookLoadPackage; -import de.robv.android.xposed.XC_MethodHook; -import de.robv.android.xposed.XposedBridge; -import de.robv.android.xposed.XposedHelpers; -import de.robv.android.xposed.callbacks.XC_LoadPackage; - -/** - * This class implements a bridge from an Android app to - * Rainbow. It uses Xposed to insert probes into appropriate - * methods on apps that are identified as potential vulnerability - * points. - *

- * Created by Bradley Schmerl on 9/23/2015. - */ -public class RaindroidBridgeOLD implements IXposedHookLoadPackage { - - private final Map> m_interestingPackages; - - private boolean m_intercept = true; - public void setIntercept (boolean i) { - m_intercept = i; - } - public boolean isIntercept () { - return m_intercept; - } - - private void log(String s) { - System.out.println(s); - } - - private void log(Throwable e) { - e.printStackTrace(System.out); - } - - public static class NewActivityHook extends XC_MethodHook { - private static volatile Activity m_currentActivity = null; - - public static Activity getCurrentActivity() { - return m_currentActivity; - } - - @Override - protected void afterHookedMethod(MethodHookParam param) throws Throwable { - m_currentActivity = (Activity) param.getResult(); - } - } - - class ActivityMethodHook extends XC_MethodHook { - private final Set m_classes; - private DialogInterface.OnClickListener dialogClickListener; - private int choice = 1; - - public ActivityMethodHook(Set classes) { - super(); - m_classes = classes; - } - - @Override - protected void afterHookedMethod(MethodHookParam param) throws Throwable { - m_intercept = true; - } - - @Override - protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { - if (m_intercept && m_classes != null && m_classes.contains(param.thisObject.getClass().getName())) { - Intent i = (Intent) param.args[0]; - XposedBridge.log(param.thisObject.getClass().toString() + " is sending an intent"); - ComponentName cmp = i.getComponent(); - i.putExtra(RaindroidMessages.RAINDROID_CALLER, param.thisObject.getClass().getName()); - final Context context = AndroidAppHelper.currentApplication().getApplicationContext(); - - if (cmp == null) { - XposedBridge.log("Implicit intent being passed"); - final Object waiter = new Object(); - dialogClickListener = new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - switch (choice) { - case 0: // Send to known good - m_intercept = false; - Intent i = (Intent) param.args[0]; - i.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity")); - try { - ((Method) param.method).invoke(param.thisObject, param.args); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - XposedBridge.log("Failed to call method"); - } - break; - case 1: // Do not send - break; - case 2: // Send as normal - m_intercept = false; - try { - ((Method) param.method).invoke(param.thisObject, param.args); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - XposedBridge.log("Failed to call method"); - } - break; - } - choice = -1; - dialog.dismiss(); - } - }; - - - AlertDialog.Builder builder = new AlertDialog.Builder(NewActivityHook.getCurrentActivity()); - builder.setTitle("Dangerous activity detected. Proceed?") - .setSingleChoiceItems(new String[]{"Send to good", "Do not send", "Send"}, 1, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - choice = which; - } - }) - .setPositiveButton("OK", dialogClickListener) - .show(); - - param.setResult(null); - - } - } - } - } - - class OnCreateMethodHook extends XC_MethodHook { - private final Set m_classes; - - public OnCreateMethodHook(Set classes) { - super(); - m_classes = classes; - } - - @Override - protected void beforeHookedMethod(MethodHookParam param) throws Throwable { - if (m_classes != null && m_classes.contains(param.thisObject.getClass().getName())) { - Activity a = (Activity) param.thisObject; - Intent intent = a.getIntent(); - String rcvr = "UNKNOWN"; - if (intent.hasExtra(RaindroidMessages.RAINDROID_CALLER)) { - rcvr = intent.getStringExtra(RaindroidMessages.RAINDROID_CALLER); - } - XposedBridge.log(a.getPackageName() + " received an intent from " + rcvr); - // Send this event to Rainbow - } - } - } - - @Override - public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable { - // Ensure that we are in an app that we are interested in - if (!m_interestingPackages.keySet().contains(loadPackageParam.packageName)) { - log("Raindroid: package loaded " + loadPackageParam.packageName + " not interested."); - return; - } - - log("Raindroid: package loaded " + loadPackageParam.packageName + " attempting to hook."); - Set classes = m_interestingPackages.get(loadPackageParam.packageName); - if (classes != null && !classes.isEmpty()) { - StringBuilder sb = new StringBuilder(); - for (String cls : classes) { - sb.append(cls).append(", "); - } - sb.delete(sb.length() - 2, sb.length()); - String l = sb.toString(); - log("Raindroid: attempting to hook into " + l); - try { -// XposedHelpers.findAndHookMethod("android.app.Activity", loadPackageParam.classLoader, "startActivityFromChild", Activity.class, Intent.class, int.class, Bundle.class, new ActivityMethodHook(classes)); - XposedHelpers.findAndHookMethod("android.app.Activity", loadPackageParam.classLoader, "startActivity", Intent.class, new ActivityMethodHook(classes)); - XposedHelpers.findAndHookMethod("android.app.Activity", loadPackageParam.classLoader, "onCreate", Bundle.class, new OnCreateMethodHook(classes)); - XposedHelpers.findAndHookMethod("android.app.Instrumentation", loadPackageParam.classLoader, "newActivity", ClassLoader.class, String.class, Intent.class, new NewActivityHook()); - } catch (Throwable e) { - log("Error! could not hook method '" + l + "'.startActivity"); - log(e); - } - } - - } - - - public RaindroidBridgeOLD() { - // Initialize packages that we are interested in - // For now, let's hardwire the example. In future, - // we'll need to do this dynamically, perhaps through - // a file - XposedBridge.log("Loaded RaindroidBridgeOLD"); - m_interestingPackages = new HashMap(); - m_interestingPackages.put("sosf.cmu.edu.intentintercept", Collections.singleton("sosf.cmu.edu.activity1.Activity1")); - m_interestingPackages.put("sosf.cmu.edu.maliciousapp", Collections.singleton("sosf.cmu.edu.maliciousapp.MaliciousActivity")); - } - -} +package com.example.raindroidxposed; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.AndroidAppHelper; +import android.content.ComponentName; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Bundle; + +import org.sa.rainbow.raindroid.util.RaindroidMessages; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import de.robv.android.xposed.IXposedHookLoadPackage; +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedBridge; +import de.robv.android.xposed.XposedHelpers; +import de.robv.android.xposed.callbacks.XC_LoadPackage; + +/** + * This class implements a bridge from an Android app to + * Rainbow. It uses Xposed to insert probes into appropriate + * methods on apps that are identified as potential vulnerability + * points. + *

+ * Created by Bradley Schmerl on 9/23/2015. + */ +public class RaindroidBridgeOLD implements IXposedHookLoadPackage { + + private final Map> m_interestingPackages; + + private boolean m_intercept = true; + public void setIntercept (boolean i) { + m_intercept = i; + } + public boolean isIntercept () { + return m_intercept; + } + + private void log(String s) { + System.out.println(s); + } + + private void log(Throwable e) { + e.printStackTrace(System.out); + } + + public static class NewActivityHook extends XC_MethodHook { + private static volatile Activity m_currentActivity = null; + + public static Activity getCurrentActivity() { + return m_currentActivity; + } + + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + m_currentActivity = (Activity) param.getResult(); + } + } + + class ActivityMethodHook extends XC_MethodHook { + private final Set m_classes; + private DialogInterface.OnClickListener dialogClickListener; + private int choice = 1; + + public ActivityMethodHook(Set classes) { + super(); + m_classes = classes; + } + + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + m_intercept = true; + } + + @Override + protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { + if (m_intercept && m_classes != null && m_classes.contains(param.thisObject.getClass().getName())) { + Intent i = (Intent) param.args[0]; + XposedBridge.log(param.thisObject.getClass().toString() + " is sending an intent"); + ComponentName cmp = i.getComponent(); + i.putExtra(RaindroidMessages.RAINDROID_CALLER, param.thisObject.getClass().getName()); + final Context context = AndroidAppHelper.currentApplication().getApplicationContext(); + + if (cmp == null) { + XposedBridge.log("Implicit intent being passed"); + final Object waiter = new Object(); + dialogClickListener = new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + switch (choice) { + case 0: // Send to known good + m_intercept = false; + Intent i = (Intent) param.args[0]; + i.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity")); + try { + ((Method) param.method).invoke(param.thisObject, param.args); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + XposedBridge.log("Failed to call method"); + } + break; + case 1: // Do not send + break; + case 2: // Send as normal + m_intercept = false; + try { + ((Method) param.method).invoke(param.thisObject, param.args); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + XposedBridge.log("Failed to call method"); + } + break; + } + choice = -1; + dialog.dismiss(); + } + }; + + + AlertDialog.Builder builder = new AlertDialog.Builder(NewActivityHook.getCurrentActivity()); + builder.setTitle("Dangerous activity detected. Proceed?") + .setSingleChoiceItems(new String[]{"Send to good", "Do not send", "Send"}, 1, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + choice = which; + } + }) + .setPositiveButton("OK", dialogClickListener) + .show(); + + param.setResult(null); + + } + } + } + } + + class OnCreateMethodHook extends XC_MethodHook { + private final Set m_classes; + + public OnCreateMethodHook(Set classes) { + super(); + m_classes = classes; + } + + @Override + protected void beforeHookedMethod(MethodHookParam param) throws Throwable { + if (m_classes != null && m_classes.contains(param.thisObject.getClass().getName())) { + Activity a = (Activity) param.thisObject; + Intent intent = a.getIntent(); + String rcvr = "UNKNOWN"; + if (intent.hasExtra(RaindroidMessages.RAINDROID_CALLER)) { + rcvr = intent.getStringExtra(RaindroidMessages.RAINDROID_CALLER); + } + XposedBridge.log(a.getPackageName() + " received an intent from " + rcvr); + // Send this event to Rainbow + } + } + } + + @Override + public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable { + // Ensure that we are in an app that we are interested in + if (!m_interestingPackages.keySet().contains(loadPackageParam.packageName)) { + log("Raindroid: package loaded " + loadPackageParam.packageName + " not interested."); + return; + } + + log("Raindroid: package loaded " + loadPackageParam.packageName + " attempting to hook."); + Set classes = m_interestingPackages.get(loadPackageParam.packageName); + if (classes != null && !classes.isEmpty()) { + StringBuilder sb = new StringBuilder(); + for (String cls : classes) { + sb.append(cls).append(", "); + } + sb.delete(sb.length() - 2, sb.length()); + String l = sb.toString(); + log("Raindroid: attempting to hook into " + l); + try { +// XposedHelpers.findAndHookMethod("android.app.Activity", loadPackageParam.classLoader, "startActivityFromChild", Activity.class, Intent.class, int.class, Bundle.class, new ActivityMethodHook(classes)); + XposedHelpers.findAndHookMethod("android.app.Activity", loadPackageParam.classLoader, "startActivity", Intent.class, new ActivityMethodHook(classes)); + XposedHelpers.findAndHookMethod("android.app.Activity", loadPackageParam.classLoader, "onCreate", Bundle.class, new OnCreateMethodHook(classes)); + XposedHelpers.findAndHookMethod("android.app.Instrumentation", loadPackageParam.classLoader, "newActivity", ClassLoader.class, String.class, Intent.class, new NewActivityHook()); + } catch (Throwable e) { + log("Error! could not hook method '" + l + "'.startActivity"); + log(e); + } + } + + } + + + public RaindroidBridgeOLD() { + // Initialize packages that we are interested in + // For now, let's hardwire the example. In future, + // we'll need to do this dynamically, perhaps through + // a file + XposedBridge.log("Loaded RaindroidBridgeOLD"); + m_interestingPackages = new HashMap(); + m_interestingPackages.put("sosf.cmu.edu.intentintercept", Collections.singleton("sosf.cmu.edu.activity1.Activity1")); + m_interestingPackages.put("sosf.cmu.edu.maliciousapp", Collections.singleton("sosf.cmu.edu.maliciousapp.MaliciousActivity")); + } + +} diff --git a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/ActivityMethodHook.java b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/ActivityMethodHook.java index 2ae09e0ea..8d38f76a6 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/ActivityMethodHook.java +++ b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/ActivityMethodHook.java @@ -1,65 +1,65 @@ -package com.example.raindroidxposed.hooks; - -import android.content.ComponentName; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Message; -import android.os.Messenger; - -import com.example.raindroidxposed.RaindroidBridge; - -import org.sa.rainbow.raindroid.util.RaindroidMessages; - -import java.util.Set; - -import de.robv.android.xposed.XC_MethodHook; -import de.robv.android.xposed.XposedBridge; - -/** - * The method to hook before sending an intent. This will check to see if - * the intent is implicit and then communicate with Raindroid to find out - * what to do. - */ -public class ActivityMethodHook extends XC_MethodHook { - private RaindroidBridge bridge; - private final Set m_classes; - private DialogInterface.OnClickListener dialogClickListener; - private int choice = 1; - - public ActivityMethodHook(RaindroidBridge bridge, Set classes) { - super(); - this.bridge = bridge; - m_classes = classes; - } - - @Override - protected void afterHookedMethod(MethodHookParam param) throws Throwable { - // After the method has been invoked, let's make sure to reintercept. - bridge.setIntercept (true); - } - - @Override - protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { - // Make sure we bind to Raindroid. Need to do this here because we need a - // valid context. - RaindroidBridge.bindToRaindroid(NewActivityHook.getCurrentActivity()); - if (bridge.isIntercept () && m_classes != null && m_classes.contains(param.thisObject.getClass().getName())) { - Intent i = (Intent) param.args[0]; - XposedBridge.log(param.thisObject.getClass().toString() + " is sending an intent"); - // Add the component that is sending the intent to the intent so that we can - // track it on the ohter end, if necessary - ComponentName cmp = i.getComponent(); - i.putExtra(RaindroidMessages.RAINDROID_CALLER, param.thisObject.getClass().getName()); - - // Send a message to the RaindroidService to find out what to do. The actual - // effect is implemented in the IntentDispositioner - Message msg = Message.obtain(null, RaindroidMessages.MSG_RAINDROID_INTENT_SENT); - msg.replyTo = new Messenger(new IntentDispositioner (bridge, param)); - msg.getData().putParcelable(RaindroidMessages.MSG_RANDROID_INTENT_DATA_KEY, i); - RaindroidBridge.sendToRaindroidService(msg); - // This prevents the method from being called -- we will wait for Raindroid - // to tell us what to do, before sending the intent (if we are allowed). - param.setResult(null); - } - } -} +package com.example.raindroidxposed.hooks; + +import android.content.ComponentName; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Message; +import android.os.Messenger; + +import com.example.raindroidxposed.RaindroidBridge; + +import org.sa.rainbow.raindroid.util.RaindroidMessages; + +import java.util.Set; + +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedBridge; + +/** + * The method to hook before sending an intent. This will check to see if + * the intent is implicit and then communicate with Raindroid to find out + * what to do. + */ +public class ActivityMethodHook extends XC_MethodHook { + private RaindroidBridge bridge; + private final Set m_classes; + private DialogInterface.OnClickListener dialogClickListener; + private int choice = 1; + + public ActivityMethodHook(RaindroidBridge bridge, Set classes) { + super(); + this.bridge = bridge; + m_classes = classes; + } + + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + // After the method has been invoked, let's make sure to reintercept. + bridge.setIntercept (true); + } + + @Override + protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { + // Make sure we bind to Raindroid. Need to do this here because we need a + // valid context. + RaindroidBridge.bindToRaindroid(NewActivityHook.getCurrentActivity()); + if (bridge.isIntercept () && m_classes != null && m_classes.contains(param.thisObject.getClass().getName())) { + Intent i = (Intent) param.args[0]; + XposedBridge.log(param.thisObject.getClass().toString() + " is sending an intent"); + // Add the component that is sending the intent to the intent so that we can + // track it on the ohter end, if necessary + ComponentName cmp = i.getComponent(); + i.putExtra(RaindroidMessages.RAINDROID_CALLER, param.thisObject.getClass().getName()); + + // Send a message to the RaindroidService to find out what to do. The actual + // effect is implemented in the IntentDispositioner + Message msg = Message.obtain(null, RaindroidMessages.MSG_RAINDROID_INTENT_SENT); + msg.replyTo = new Messenger(new IntentDispositioner (bridge, param)); + msg.getData().putParcelable(RaindroidMessages.MSG_RANDROID_INTENT_DATA_KEY, i); + RaindroidBridge.sendToRaindroidService(msg); + // This prevents the method from being called -- we will wait for Raindroid + // to tell us what to do, before sending the intent (if we are allowed). + param.setResult(null); + } + } +} diff --git a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/IntentDispositioner.java b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/IntentDispositioner.java index cd313d164..b631010f4 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/IntentDispositioner.java +++ b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/IntentDispositioner.java @@ -1,95 +1,95 @@ -package com.example.raindroidxposed.hooks; - -import android.app.AlertDialog; -import android.content.ComponentName; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Handler; -import android.os.Message; - -import com.example.raindroidxposed.RaindroidBridge; - -import org.sa.rainbow.raindroid.util.RaindroidMessages; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import de.robv.android.xposed.XC_MethodHook; -import de.robv.android.xposed.XposedBridge; - -/** - * Implements various effectors to deal with implicit intents - * 1. Do not send the intent - * 2. Turn the intent into an explicit intent, and send to that activity - * 3. Do nothing - start the activity anyway. - */ -public class IntentDispositioner extends Handler { - private RaindroidBridge m_bridge; - private XC_MethodHook.MethodHookParam m_methodHookParam; - - public IntentDispositioner(RaindroidBridge bridge, XC_MethodHook.MethodHookParam methodHookParam) { - m_bridge = bridge; - m_methodHookParam = methodHookParam; - } - - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case RaindroidMessages.MSG_RAINDROID_EFFECT: - String effect = msg.getData().getString (RaindroidMessages.MSG_RAINDROID_EFFECT_KEY); - doDispositionIntent (effect); - break; - default: - super.handleMessage(msg); - - } - } - - private void doDispositionIntent(String effect) { - if (effect.equals(RaindroidMessages.MSG_RAINBOW_INTENT_NO_EFFECT)) { - sendIntent(); - - } else if (effect.equals(RaindroidMessages.MSG_RAINDROID_INTENT_PREVENT)) { - blockIntent(); - - } else if (effect.equals(RaindroidMessages.MSG_RAINDROID_INTENT_SEND_TO_GOOD)) { - sendIntentToGoodReceiver(); - } - } - - private void sendIntentToGoodReceiver() { - Intent i = (Intent )m_methodHookParam.args[0]; - i.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity")); - sendIntent(); - } - - private void sendIntent() { - m_bridge.setIntercept(false); - try { - ((Method) m_methodHookParam.method).invoke (m_methodHookParam.thisObject, m_methodHookParam.args); - } catch (IllegalAccessException e) { - XposedBridge.log(e); - } catch (InvocationTargetException e) { - XposedBridge.log(e); - } - } - - private void blockIntent() { - m_bridge.setIntercept (true); - XposedBridge.log("Blocking intent sending from " + getIntent ().getStringExtra(RaindroidMessages.RAINDROID_CALLER)); - AlertDialog.Builder builder = new AlertDialog.Builder(NewActivityHook.getCurrentActivity()); - builder.setTitle("The sending of this event has been blocked by Raindroid!") - - .setPositiveButton("OK", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }) - .show(); - } - - private Intent getIntent() { - return (Intent )m_methodHookParam.args [0]; - } -} +package com.example.raindroidxposed.hooks; + +import android.app.AlertDialog; +import android.content.ComponentName; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Handler; +import android.os.Message; + +import com.example.raindroidxposed.RaindroidBridge; + +import org.sa.rainbow.raindroid.util.RaindroidMessages; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedBridge; + +/** + * Implements various effectors to deal with implicit intents + * 1. Do not send the intent + * 2. Turn the intent into an explicit intent, and send to that activity + * 3. Do nothing - start the activity anyway. + */ +public class IntentDispositioner extends Handler { + private RaindroidBridge m_bridge; + private XC_MethodHook.MethodHookParam m_methodHookParam; + + public IntentDispositioner(RaindroidBridge bridge, XC_MethodHook.MethodHookParam methodHookParam) { + m_bridge = bridge; + m_methodHookParam = methodHookParam; + } + + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case RaindroidMessages.MSG_RAINDROID_EFFECT: + String effect = msg.getData().getString (RaindroidMessages.MSG_RAINDROID_EFFECT_KEY); + doDispositionIntent (effect); + break; + default: + super.handleMessage(msg); + + } + } + + private void doDispositionIntent(String effect) { + if (effect.equals(RaindroidMessages.MSG_RAINBOW_INTENT_NO_EFFECT)) { + sendIntent(); + + } else if (effect.equals(RaindroidMessages.MSG_RAINDROID_INTENT_PREVENT)) { + blockIntent(); + + } else if (effect.equals(RaindroidMessages.MSG_RAINDROID_INTENT_SEND_TO_GOOD)) { + sendIntentToGoodReceiver(); + } + } + + private void sendIntentToGoodReceiver() { + Intent i = (Intent )m_methodHookParam.args[0]; + i.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity")); + sendIntent(); + } + + private void sendIntent() { + m_bridge.setIntercept(false); + try { + ((Method) m_methodHookParam.method).invoke (m_methodHookParam.thisObject, m_methodHookParam.args); + } catch (IllegalAccessException e) { + XposedBridge.log(e); + } catch (InvocationTargetException e) { + XposedBridge.log(e); + } + } + + private void blockIntent() { + m_bridge.setIntercept (true); + XposedBridge.log("Blocking intent sending from " + getIntent ().getStringExtra(RaindroidMessages.RAINDROID_CALLER)); + AlertDialog.Builder builder = new AlertDialog.Builder(NewActivityHook.getCurrentActivity()); + builder.setTitle("The sending of this event has been blocked by Raindroid!") + + .setPositiveButton("OK", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }) + .show(); + } + + private Intent getIntent() { + return (Intent )m_methodHookParam.args [0]; + } +} diff --git a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/NewActivityHook.java b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/NewActivityHook.java index e31467f1e..3534074bd 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/NewActivityHook.java +++ b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/NewActivityHook.java @@ -1,22 +1,22 @@ -package com.example.raindroidxposed.hooks; - -import android.app.Activity; - -import de.robv.android.xposed.XC_MethodHook; - -/** - * This class sets up the context, which is used to connect to - * the service. (There might be a better way to do this.) - */ -public class NewActivityHook extends XC_MethodHook { - private static volatile Activity m_currentActivity = null; - - public static Activity getCurrentActivity() { - return m_currentActivity; - } - - @Override - protected void afterHookedMethod(MethodHookParam param) throws Throwable { - m_currentActivity = (Activity) param.getResult(); - } -} +package com.example.raindroidxposed.hooks; + +import android.app.Activity; + +import de.robv.android.xposed.XC_MethodHook; + +/** + * This class sets up the context, which is used to connect to + * the service. (There might be a better way to do this.) + */ +public class NewActivityHook extends XC_MethodHook { + private static volatile Activity m_currentActivity = null; + + public static Activity getCurrentActivity() { + return m_currentActivity; + } + + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + m_currentActivity = (Activity) param.getResult(); + } +} diff --git a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/OnCreateMethodHook.java b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/OnCreateMethodHook.java index 2a9281689..32ce474a6 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/OnCreateMethodHook.java +++ b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/OnCreateMethodHook.java @@ -1,47 +1,47 @@ -package com.example.raindroidxposed.hooks; - -import android.app.Activity; -import android.content.Intent; -import android.os.Message; - -import com.example.raindroidxposed.RaindroidBridge; - -import org.sa.rainbow.raindroid.util.RaindroidMessages; - -import java.util.Set; - -import de.robv.android.xposed.XC_MethodHook; -import de.robv.android.xposed.XposedBridge; - -/** - * - */ -public class OnCreateMethodHook extends XC_MethodHook { - private final Set m_classes; - - public OnCreateMethodHook(Set classes) { - super(); - m_classes = classes; - } - - @Override - protected void beforeHookedMethod(MethodHookParam param) throws Throwable { - RaindroidBridge.bindToRaindroid(NewActivityHook.getCurrentActivity()); - - if (m_classes != null && m_classes.contains(param.thisObject.getClass().getName())) { - Activity a = (Activity) param.thisObject; - Intent intent = a.getIntent(); - String rcvr = "UNKNOWN"; - if (intent.hasExtra(RaindroidMessages.RAINDROID_CALLER)) { - rcvr = intent.getStringExtra(RaindroidMessages.RAINDROID_CALLER); - } - XposedBridge.log(a.getPackageName() + " received an intent from " + rcvr); - // Send this event to Rainbow - Message msg = Message.obtain (null, RaindroidMessages.MSG_RAINDROID_INTENT_RECEIVED); - msg.getData().putParcelable(RaindroidMessages.MSG_RANDROID_INTENT_DATA_KEY, intent); - msg.getData().putString(RaindroidMessages.MSG_RAINDROID_INTENT_RECEIVER_KEY, a.getPackageName()); - msg.getData().putString (RaindroidMessages.MSG_RAINDROID_INTENT_SENDER_KEY, rcvr); - RaindroidBridge.sendToRaindroidService (msg); - } - } -} +package com.example.raindroidxposed.hooks; + +import android.app.Activity; +import android.content.Intent; +import android.os.Message; + +import com.example.raindroidxposed.RaindroidBridge; + +import org.sa.rainbow.raindroid.util.RaindroidMessages; + +import java.util.Set; + +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedBridge; + +/** + * + */ +public class OnCreateMethodHook extends XC_MethodHook { + private final Set m_classes; + + public OnCreateMethodHook(Set classes) { + super(); + m_classes = classes; + } + + @Override + protected void beforeHookedMethod(MethodHookParam param) throws Throwable { + RaindroidBridge.bindToRaindroid(NewActivityHook.getCurrentActivity()); + + if (m_classes != null && m_classes.contains(param.thisObject.getClass().getName())) { + Activity a = (Activity) param.thisObject; + Intent intent = a.getIntent(); + String rcvr = "UNKNOWN"; + if (intent.hasExtra(RaindroidMessages.RAINDROID_CALLER)) { + rcvr = intent.getStringExtra(RaindroidMessages.RAINDROID_CALLER); + } + XposedBridge.log(a.getPackageName() + " received an intent from " + rcvr); + // Send this event to Rainbow + Message msg = Message.obtain (null, RaindroidMessages.MSG_RAINDROID_INTENT_RECEIVED); + msg.getData().putParcelable(RaindroidMessages.MSG_RANDROID_INTENT_DATA_KEY, intent); + msg.getData().putString(RaindroidMessages.MSG_RAINDROID_INTENT_RECEIVER_KEY, a.getPackageName()); + msg.getData().putString (RaindroidMessages.MSG_RAINDROID_INTENT_SENDER_KEY, rcvr); + RaindroidBridge.sendToRaindroidService (msg); + } + } +} diff --git a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/RegisterWithAndroidHook.java b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/RegisterWithAndroidHook.java index 311f4e461..c056d47fa 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/RegisterWithAndroidHook.java +++ b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/hooks/RegisterWithAndroidHook.java @@ -1,38 +1,38 @@ -package com.example.raindroidxposed.hooks; - -import android.app.Application; -import android.content.Context; -import android.os.Message; - -import com.example.raindroidxposed.RaindroidBridge; - -import org.sa.rainbow.raindroid.util.RaindroidMessages; - -import de.robv.android.xposed.XC_MethodHook; -import de.robv.android.xposed.XposedBridge; -import de.robv.android.xposed.XposedHelpers; - -/** - * Created by schmerl on 10/30/2015. - */ -public class RegisterWithAndroidHook extends XC_MethodHook { - private RaindroidBridge m_bridge; - - public RegisterWithAndroidHook(RaindroidBridge bridge) { - m_bridge = bridge; - } - - @Override - protected void afterHookedMethod(MethodHookParam param) throws Throwable { - Application application = (Application) param.thisObject; - Context m_context = (Context )param.args [0]; - if (m_context != null) { - XposedBridge.log(application.getPackageName() + " has been given a context"); - RaindroidBridge.bindToRaindroid(m_context); - } - Message msg = Message.obtain(null, RaindroidMessages.MSG_RAINDROID_APP_STARTED); - msg.getData().putString (RaindroidMessages.MSG_APP_PACKAGE, application.getPackageName()); - RaindroidBridge.sendToRaindroidService(msg); - - } -} +package com.example.raindroidxposed.hooks; + +import android.app.Application; +import android.content.Context; +import android.os.Message; + +import com.example.raindroidxposed.RaindroidBridge; + +import org.sa.rainbow.raindroid.util.RaindroidMessages; + +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedBridge; +import de.robv.android.xposed.XposedHelpers; + +/** + * Created by schmerl on 10/30/2015. + */ +public class RegisterWithAndroidHook extends XC_MethodHook { + private RaindroidBridge m_bridge; + + public RegisterWithAndroidHook(RaindroidBridge bridge) { + m_bridge = bridge; + } + + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + Application application = (Application) param.thisObject; + Context m_context = (Context )param.args [0]; + if (m_context != null) { + XposedBridge.log(application.getPackageName() + " has been given a context"); + RaindroidBridge.bindToRaindroid(m_context); + } + Message msg = Message.obtain(null, RaindroidMessages.MSG_RAINDROID_APP_STARTED); + msg.getData().putString (RaindroidMessages.MSG_APP_PACKAGE, application.getPackageName()); + RaindroidBridge.sendToRaindroidService(msg); + + } +} diff --git a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHider.java b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHider.java index 4a767d445..ccf72e2bb 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHider.java +++ b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHider.java @@ -1,172 +1,172 @@ -package com.example.raindroidxposed.util; - -import android.app.Activity; -import android.os.Build; -import android.view.View; - -/** - * A utility class that helps with showing and hiding system UI such as the - * status bar and navigation/system bar. This class uses backward-compatibility - * techniques described in - * Creating Backward-Compatible UIs to ensure that devices running any - * version of ndroid OS are supported. More specifically, there are separate - * implementations of this abstract class: for newer devices, - * {@link #getInstance} will return a {@link SystemUiHiderHoneycomb} instance, - * while on older devices {@link #getInstance} will return a - * {@link SystemUiHiderBase} instance. - *

- * For more on system bars, see System Bars. - * - * @see android.view.View#setSystemUiVisibility(int) - * @see android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN - */ -public abstract class SystemUiHider { - /** - * When this flag is set, the - * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN} - * flag will be set on older devices, making the status bar "float" on top - * of the activity layout. This is most useful when there are no controls at - * the top of the activity layout. - *

- * This flag isn't used on newer devices because the action - * bar, the most important structural element of an Android app, should - * be visible and not obscured by the system UI. - */ - public static final int FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES = 0x1; - - /** - * When this flag is set, {@link #show()} and {@link #hide()} will toggle - * the visibility of the status bar. If there is a navigation bar, show and - * hide will toggle low profile mode. - */ - public static final int FLAG_FULLSCREEN = 0x2; - - /** - * When this flag is set, {@link #show()} and {@link #hide()} will toggle - * the visibility of the navigation bar, if it's present on the device and - * the device allows hiding it. In cases where the navigation bar is present - * but cannot be hidden, show and hide will toggle low profile mode. - */ - public static final int FLAG_HIDE_NAVIGATION = FLAG_FULLSCREEN | 0x4; - - /** - * The activity associated with this UI hider object. - */ - protected Activity mActivity; - - /** - * The view on which {@link View#setSystemUiVisibility(int)} will be called. - */ - protected View mAnchorView; - - /** - * The current UI hider flags. - * - * @see #FLAG_FULLSCREEN - * @see #FLAG_HIDE_NAVIGATION - * @see #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES - */ - protected int mFlags; - - /** - * The current visibility callback. - */ - protected OnVisibilityChangeListener mOnVisibilityChangeListener = sDummyListener; - - /** - * Creates and returns an instance of {@link SystemUiHider} that is - * appropriate for this device. The object will be either a - * {@link SystemUiHiderBase} or {@link SystemUiHiderHoneycomb} depending on - * the device. - * - * @param activity The activity whose window's system UI should be - * controlled by this class. - * @param anchorView The view on which - * {@link View#setSystemUiVisibility(int)} will be called. - * @param flags Either 0 or any combination of {@link #FLAG_FULLSCREEN}, - * {@link #FLAG_HIDE_NAVIGATION}, and - * {@link #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES}. - */ - public static SystemUiHider getInstance(Activity activity, View anchorView, int flags) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { - return new SystemUiHiderHoneycomb(activity, anchorView, flags); - } else { - return new SystemUiHiderBase(activity, anchorView, flags); - } - } - - protected SystemUiHider(Activity activity, View anchorView, int flags) { - mActivity = activity; - mAnchorView = anchorView; - mFlags = flags; - } - - /** - * Sets up the system UI hider. Should be called from - * {@link Activity#onCreate}. - */ - public abstract void setup(); - - /** - * Returns whether or not the system UI is visible. - */ - public abstract boolean isVisible(); - - /** - * Hide the system UI. - */ - public abstract void hide(); - - /** - * Show the system UI. - */ - public abstract void show(); - - /** - * Toggle the visibility of the system UI. - */ - public void toggle() { - if (isVisible()) { - hide(); - } else { - show(); - } - } - - /** - * Registers a callback, to be triggered when the system UI visibility - * changes. - */ - public void setOnVisibilityChangeListener(OnVisibilityChangeListener listener) { - if (listener == null) { - listener = sDummyListener; - } - - mOnVisibilityChangeListener = listener; - } - - /** - * A dummy no-op callback for use when there is no other listener set. - */ - private static OnVisibilityChangeListener sDummyListener = new OnVisibilityChangeListener() { - @Override - public void onVisibilityChange(boolean visible) { - } - }; - - /** - * A callback interface used to listen for system UI visibility changes. - */ - public interface OnVisibilityChangeListener { - /** - * Called when the system UI visibility has changed. - * - * @param visible True if the system UI is visible. - */ - public void onVisibilityChange(boolean visible); - } -} +package com.example.raindroidxposed.util; + +import android.app.Activity; +import android.os.Build; +import android.view.View; + +/** + * A utility class that helps with showing and hiding system UI such as the + * status bar and navigation/system bar. This class uses backward-compatibility + * techniques described in + * Creating Backward-Compatible UIs to ensure that devices running any + * version of ndroid OS are supported. More specifically, there are separate + * implementations of this abstract class: for newer devices, + * {@link #getInstance} will return a {@link SystemUiHiderHoneycomb} instance, + * while on older devices {@link #getInstance} will return a + * {@link SystemUiHiderBase} instance. + *

+ * For more on system bars, see System Bars. + * + * @see android.view.View#setSystemUiVisibility(int) + * @see android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN + */ +public abstract class SystemUiHider { + /** + * When this flag is set, the + * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN} + * flag will be set on older devices, making the status bar "float" on top + * of the activity layout. This is most useful when there are no controls at + * the top of the activity layout. + *

+ * This flag isn't used on newer devices because the action + * bar, the most important structural element of an Android app, should + * be visible and not obscured by the system UI. + */ + public static final int FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES = 0x1; + + /** + * When this flag is set, {@link #show()} and {@link #hide()} will toggle + * the visibility of the status bar. If there is a navigation bar, show and + * hide will toggle low profile mode. + */ + public static final int FLAG_FULLSCREEN = 0x2; + + /** + * When this flag is set, {@link #show()} and {@link #hide()} will toggle + * the visibility of the navigation bar, if it's present on the device and + * the device allows hiding it. In cases where the navigation bar is present + * but cannot be hidden, show and hide will toggle low profile mode. + */ + public static final int FLAG_HIDE_NAVIGATION = FLAG_FULLSCREEN | 0x4; + + /** + * The activity associated with this UI hider object. + */ + protected Activity mActivity; + + /** + * The view on which {@link View#setSystemUiVisibility(int)} will be called. + */ + protected View mAnchorView; + + /** + * The current UI hider flags. + * + * @see #FLAG_FULLSCREEN + * @see #FLAG_HIDE_NAVIGATION + * @see #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES + */ + protected int mFlags; + + /** + * The current visibility callback. + */ + protected OnVisibilityChangeListener mOnVisibilityChangeListener = sDummyListener; + + /** + * Creates and returns an instance of {@link SystemUiHider} that is + * appropriate for this device. The object will be either a + * {@link SystemUiHiderBase} or {@link SystemUiHiderHoneycomb} depending on + * the device. + * + * @param activity The activity whose window's system UI should be + * controlled by this class. + * @param anchorView The view on which + * {@link View#setSystemUiVisibility(int)} will be called. + * @param flags Either 0 or any combination of {@link #FLAG_FULLSCREEN}, + * {@link #FLAG_HIDE_NAVIGATION}, and + * {@link #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES}. + */ + public static SystemUiHider getInstance(Activity activity, View anchorView, int flags) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + return new SystemUiHiderHoneycomb(activity, anchorView, flags); + } else { + return new SystemUiHiderBase(activity, anchorView, flags); + } + } + + protected SystemUiHider(Activity activity, View anchorView, int flags) { + mActivity = activity; + mAnchorView = anchorView; + mFlags = flags; + } + + /** + * Sets up the system UI hider. Should be called from + * {@link Activity#onCreate}. + */ + public abstract void setup(); + + /** + * Returns whether or not the system UI is visible. + */ + public abstract boolean isVisible(); + + /** + * Hide the system UI. + */ + public abstract void hide(); + + /** + * Show the system UI. + */ + public abstract void show(); + + /** + * Toggle the visibility of the system UI. + */ + public void toggle() { + if (isVisible()) { + hide(); + } else { + show(); + } + } + + /** + * Registers a callback, to be triggered when the system UI visibility + * changes. + */ + public void setOnVisibilityChangeListener(OnVisibilityChangeListener listener) { + if (listener == null) { + listener = sDummyListener; + } + + mOnVisibilityChangeListener = listener; + } + + /** + * A dummy no-op callback for use when there is no other listener set. + */ + private static OnVisibilityChangeListener sDummyListener = new OnVisibilityChangeListener() { + @Override + public void onVisibilityChange(boolean visible) { + } + }; + + /** + * A callback interface used to listen for system UI visibility changes. + */ + public interface OnVisibilityChangeListener { + /** + * Called when the system UI visibility has changed. + * + * @param visible True if the system UI is visible. + */ + public void onVisibilityChange(boolean visible); + } +} diff --git a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHiderBase.java b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHiderBase.java index 8026372ad..c029f75af 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHiderBase.java +++ b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHiderBase.java @@ -1,63 +1,63 @@ -package com.example.raindroidxposed.util; - -import android.app.Activity; -import android.view.View; -import android.view.WindowManager; - -/** - * A base implementation of {@link SystemUiHider}. Uses APIs available in all - * API levels to show and hide the status bar. - */ -public class SystemUiHiderBase extends SystemUiHider { - /** - * Whether or not the system UI is currently visible. This is a cached value - * from calls to {@link #hide()} and {@link #show()}. - */ - private boolean mVisible = true; - - /** - * Constructor not intended to be called by clients. Use - * {@link SystemUiHider#getInstance} to obtain an instance. - */ - protected SystemUiHiderBase(Activity activity, View anchorView, int flags) { - super(activity, anchorView, flags); - } - - @Override - public void setup() { - if ((mFlags & FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES) == 0) { - mActivity.getWindow().setFlags( - WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN - | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, - WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN - | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); - } - } - - @Override - public boolean isVisible() { - return mVisible; - } - - @Override - public void hide() { - if ((mFlags & FLAG_FULLSCREEN) != 0) { - mActivity.getWindow().setFlags( - WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN); - } - mOnVisibilityChangeListener.onVisibilityChange(false); - mVisible = false; - } - - @Override - public void show() { - if ((mFlags & FLAG_FULLSCREEN) != 0) { - mActivity.getWindow().setFlags( - 0, - WindowManager.LayoutParams.FLAG_FULLSCREEN); - } - mOnVisibilityChangeListener.onVisibilityChange(true); - mVisible = true; - } -} +package com.example.raindroidxposed.util; + +import android.app.Activity; +import android.view.View; +import android.view.WindowManager; + +/** + * A base implementation of {@link SystemUiHider}. Uses APIs available in all + * API levels to show and hide the status bar. + */ +public class SystemUiHiderBase extends SystemUiHider { + /** + * Whether or not the system UI is currently visible. This is a cached value + * from calls to {@link #hide()} and {@link #show()}. + */ + private boolean mVisible = true; + + /** + * Constructor not intended to be called by clients. Use + * {@link SystemUiHider#getInstance} to obtain an instance. + */ + protected SystemUiHiderBase(Activity activity, View anchorView, int flags) { + super(activity, anchorView, flags); + } + + @Override + public void setup() { + if ((mFlags & FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES) == 0) { + mActivity.getWindow().setFlags( + WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN + | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, + WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN + | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); + } + } + + @Override + public boolean isVisible() { + return mVisible; + } + + @Override + public void hide() { + if ((mFlags & FLAG_FULLSCREEN) != 0) { + mActivity.getWindow().setFlags( + WindowManager.LayoutParams.FLAG_FULLSCREEN, + WindowManager.LayoutParams.FLAG_FULLSCREEN); + } + mOnVisibilityChangeListener.onVisibilityChange(false); + mVisible = false; + } + + @Override + public void show() { + if ((mFlags & FLAG_FULLSCREEN) != 0) { + mActivity.getWindow().setFlags( + 0, + WindowManager.LayoutParams.FLAG_FULLSCREEN); + } + mOnVisibilityChangeListener.onVisibilityChange(true); + mVisible = true; + } +} diff --git a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHiderHoneycomb.java b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHiderHoneycomb.java index eda407053..c2927cac2 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHiderHoneycomb.java +++ b/ide/raindroid/raindroidxposed/src/main/java/com/example/raindroidxposed/util/SystemUiHiderHoneycomb.java @@ -1,141 +1,141 @@ -package com.example.raindroidxposed.util; - -import android.annotation.TargetApi; -import android.app.Activity; -import android.os.Build; -import android.view.View; -import android.view.WindowManager; - -/** - * An API 11+ implementation of {@link SystemUiHider}. Uses APIs available in - * Honeycomb and later (specifically {@link View#setSystemUiVisibility(int)}) to - * show and hide the system UI. - */ -@TargetApi(Build.VERSION_CODES.HONEYCOMB) -public class SystemUiHiderHoneycomb extends SystemUiHiderBase { - /** - * Flags for {@link View#setSystemUiVisibility(int)} to use when showing the - * system UI. - */ - private int mShowFlags; - - /** - * Flags for {@link View#setSystemUiVisibility(int)} to use when hiding the - * system UI. - */ - private int mHideFlags; - - /** - * Flags to test against the first parameter in - * {@link android.view.View.OnSystemUiVisibilityChangeListener#onSystemUiVisibilityChange(int)} - * to determine the system UI visibility state. - */ - private int mTestFlags; - - /** - * Whether or not the system UI is currently visible. This is cached from - * {@link android.view.View.OnSystemUiVisibilityChangeListener}. - */ - private boolean mVisible = true; - - /** - * Constructor not intended to be called by clients. Use - * {@link SystemUiHider#getInstance} to obtain an instance. - */ - protected SystemUiHiderHoneycomb(Activity activity, View anchorView, int flags) { - super(activity, anchorView, flags); - - mShowFlags = View.SYSTEM_UI_FLAG_VISIBLE; - mHideFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE; - mTestFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE; - - if ((mFlags & FLAG_FULLSCREEN) != 0) { - // If the client requested fullscreen, add flags relevant to hiding - // the status bar. Note that some of these constants are new as of - // API 16 (Jelly Bean). It is safe to use them, as they are inlined - // at compile-time and do nothing on pre-Jelly Bean devices. - mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; - mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_FULLSCREEN; - } - - if ((mFlags & FLAG_HIDE_NAVIGATION) != 0) { - // If the client requested hiding navigation, add relevant flags. - mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; - mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; - mTestFlags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; - } - } - - /** - * {@inheritDoc} - */ - @Override - public void setup() { - mAnchorView.setOnSystemUiVisibilityChangeListener(mSystemUiVisibilityChangeListener); - } - - /** - * {@inheritDoc} - */ - @Override - public void hide() { - mAnchorView.setSystemUiVisibility(mHideFlags); - } - - /** - * {@inheritDoc} - */ - @Override - public void show() { - mAnchorView.setSystemUiVisibility(mShowFlags); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isVisible() { - return mVisible; - } - - private View.OnSystemUiVisibilityChangeListener mSystemUiVisibilityChangeListener - = new View.OnSystemUiVisibilityChangeListener() { - @Override - public void onSystemUiVisibilityChange(int vis) { - // Test against mTestFlags to see if the system UI is visible. - if ((vis & mTestFlags) != 0) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { - // Pre-Jelly Bean, we must manually hide the action bar - // and use the old window flags API. - mActivity.getActionBar().hide(); - mActivity.getWindow().setFlags( - WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN); - } - - // Trigger the registered listener and cache the visibility - // state. - mOnVisibilityChangeListener.onVisibilityChange(false); - mVisible = false; - - } else { - mAnchorView.setSystemUiVisibility(mShowFlags); - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { - // Pre-Jelly Bean, we must manually show the action bar - // and use the old window flags API. - mActivity.getActionBar().show(); - mActivity.getWindow().setFlags( - 0, - WindowManager.LayoutParams.FLAG_FULLSCREEN); - } - - // Trigger the registered listener and cache the visibility - // state. - mOnVisibilityChangeListener.onVisibilityChange(true); - mVisible = true; - } - } - }; -} +package com.example.raindroidxposed.util; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.os.Build; +import android.view.View; +import android.view.WindowManager; + +/** + * An API 11+ implementation of {@link SystemUiHider}. Uses APIs available in + * Honeycomb and later (specifically {@link View#setSystemUiVisibility(int)}) to + * show and hide the system UI. + */ +@TargetApi(Build.VERSION_CODES.HONEYCOMB) +public class SystemUiHiderHoneycomb extends SystemUiHiderBase { + /** + * Flags for {@link View#setSystemUiVisibility(int)} to use when showing the + * system UI. + */ + private int mShowFlags; + + /** + * Flags for {@link View#setSystemUiVisibility(int)} to use when hiding the + * system UI. + */ + private int mHideFlags; + + /** + * Flags to test against the first parameter in + * {@link android.view.View.OnSystemUiVisibilityChangeListener#onSystemUiVisibilityChange(int)} + * to determine the system UI visibility state. + */ + private int mTestFlags; + + /** + * Whether or not the system UI is currently visible. This is cached from + * {@link android.view.View.OnSystemUiVisibilityChangeListener}. + */ + private boolean mVisible = true; + + /** + * Constructor not intended to be called by clients. Use + * {@link SystemUiHider#getInstance} to obtain an instance. + */ + protected SystemUiHiderHoneycomb(Activity activity, View anchorView, int flags) { + super(activity, anchorView, flags); + + mShowFlags = View.SYSTEM_UI_FLAG_VISIBLE; + mHideFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE; + mTestFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE; + + if ((mFlags & FLAG_FULLSCREEN) != 0) { + // If the client requested fullscreen, add flags relevant to hiding + // the status bar. Note that some of these constants are new as of + // API 16 (Jelly Bean). It is safe to use them, as they are inlined + // at compile-time and do nothing on pre-Jelly Bean devices. + mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; + mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_FULLSCREEN; + } + + if ((mFlags & FLAG_HIDE_NAVIGATION) != 0) { + // If the client requested hiding navigation, add relevant flags. + mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; + mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; + mTestFlags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; + } + } + + /** + * {@inheritDoc} + */ + @Override + public void setup() { + mAnchorView.setOnSystemUiVisibilityChangeListener(mSystemUiVisibilityChangeListener); + } + + /** + * {@inheritDoc} + */ + @Override + public void hide() { + mAnchorView.setSystemUiVisibility(mHideFlags); + } + + /** + * {@inheritDoc} + */ + @Override + public void show() { + mAnchorView.setSystemUiVisibility(mShowFlags); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isVisible() { + return mVisible; + } + + private View.OnSystemUiVisibilityChangeListener mSystemUiVisibilityChangeListener + = new View.OnSystemUiVisibilityChangeListener() { + @Override + public void onSystemUiVisibilityChange(int vis) { + // Test against mTestFlags to see if the system UI is visible. + if ((vis & mTestFlags) != 0) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { + // Pre-Jelly Bean, we must manually hide the action bar + // and use the old window flags API. + mActivity.getActionBar().hide(); + mActivity.getWindow().setFlags( + WindowManager.LayoutParams.FLAG_FULLSCREEN, + WindowManager.LayoutParams.FLAG_FULLSCREEN); + } + + // Trigger the registered listener and cache the visibility + // state. + mOnVisibilityChangeListener.onVisibilityChange(false); + mVisible = false; + + } else { + mAnchorView.setSystemUiVisibility(mShowFlags); + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { + // Pre-Jelly Bean, we must manually show the action bar + // and use the old window flags API. + mActivity.getActionBar().show(); + mActivity.getWindow().setFlags( + 0, + WindowManager.LayoutParams.FLAG_FULLSCREEN); + } + + // Trigger the registered listener and cache the visibility + // state. + mOnVisibilityChangeListener.onVisibilityChange(true); + mVisible = true; + } + } + }; +} diff --git a/ide/raindroid/raindroidxposed/src/main/java/org/sa/rainbow/raindroid/util/RaindroidMessages.java b/ide/raindroid/raindroidxposed/src/main/java/org/sa/rainbow/raindroid/util/RaindroidMessages.java index fb05d3d1a..e04f30065 100644 --- a/ide/raindroid/raindroidxposed/src/main/java/org/sa/rainbow/raindroid/util/RaindroidMessages.java +++ b/ide/raindroid/raindroidxposed/src/main/java/org/sa/rainbow/raindroid/util/RaindroidMessages.java @@ -1,41 +1,41 @@ -package org.sa.rainbow.raindroid.util; - -/** - * Created by schmerl on 10/27/2015. - */ -public class RaindroidMessages { - - public static final int MSG_RAINDROID_INTENT_SENT = 1; - public static final int MSG_RAINDROID_INTENT_RECEIVED = 2; - public static final int MSG_RAINDROID_APP_STARTED = 3; - public static final int MSG_RAINDROID_APP_STOPPED = 4; - - public static final String MSG_RANDROID_INTENT_DATA_KEY = "SENT_INTENT"; - public static final String MSG_RAINDROID_INTENT_PREVENT = "__prevent__"; - public static final String MSG_RAINDROID_INTENT_SEND_TO_GOOD = "__send_to_good__"; - public static final String MSG_RAINBOW_INTENT_NO_EFFECT = "__no_effect__"; - public static final String MSG_RAINDROID_EFFECT_KEY = "__RAINDROID__EFFECT__"; - - public static final int MSG_RAINDROID_EFFECT = 2; - public static final String RAINDROID_CALLER = "__RAINDROID_CALLER__"; - public static final String MSG_RAINDROID_INTENT_RECEIVER_KEY = "INTENT_SENDER"; - public static final String MSG_RAINDROID_INTENT_SENDER_KEY = "INTENT_RECEIVER"; - public static final String MSG_APP_PACKAGE = "PACKAGE_NAME"; - - - public static String getTag () { - StringBuilder tag = new StringBuilder (); - final StackTraceElement[] ste = Thread.currentThread().getStackTrace(); - for (int i = 0; i < ste.length; i++) { - if (ste[i].getMethodName().equals ("getTag")) { - tag.append ("("); - tag.append (ste[i+1].getFileName() + ":" + ste[i+1].getLineNumber()); - tag.append ("):"); - tag.append (ste [i+1].getClassName()); - tag.append ("."); - tag.append (ste[i+1].getMethodName()); - } - } - return tag.toString(); - } -} +package org.sa.rainbow.raindroid.util; + +/** + * Created by schmerl on 10/27/2015. + */ +public class RaindroidMessages { + + public static final int MSG_RAINDROID_INTENT_SENT = 1; + public static final int MSG_RAINDROID_INTENT_RECEIVED = 2; + public static final int MSG_RAINDROID_APP_STARTED = 3; + public static final int MSG_RAINDROID_APP_STOPPED = 4; + + public static final String MSG_RANDROID_INTENT_DATA_KEY = "SENT_INTENT"; + public static final String MSG_RAINDROID_INTENT_PREVENT = "__prevent__"; + public static final String MSG_RAINDROID_INTENT_SEND_TO_GOOD = "__send_to_good__"; + public static final String MSG_RAINBOW_INTENT_NO_EFFECT = "__no_effect__"; + public static final String MSG_RAINDROID_EFFECT_KEY = "__RAINDROID__EFFECT__"; + + public static final int MSG_RAINDROID_EFFECT = 2; + public static final String RAINDROID_CALLER = "__RAINDROID_CALLER__"; + public static final String MSG_RAINDROID_INTENT_RECEIVER_KEY = "INTENT_SENDER"; + public static final String MSG_RAINDROID_INTENT_SENDER_KEY = "INTENT_RECEIVER"; + public static final String MSG_APP_PACKAGE = "PACKAGE_NAME"; + + + public static String getTag () { + StringBuilder tag = new StringBuilder (); + final StackTraceElement[] ste = Thread.currentThread().getStackTrace(); + for (int i = 0; i < ste.length; i++) { + if (ste[i].getMethodName().equals ("getTag")) { + tag.append ("("); + tag.append (ste[i+1].getFileName() + ":" + ste[i+1].getLineNumber()); + tag.append ("):"); + tag.append (ste [i+1].getClassName()); + tag.append ("."); + tag.append (ste[i+1].getMethodName()); + } + } + return tag.toString(); + } +} diff --git a/ide/raindroid/raindroidxposed/src/main/res/values-v11/styles.xml b/ide/raindroid/raindroidxposed/src/main/res/values-v11/styles.xml index 0d4af1385..f72515d8e 100644 --- a/ide/raindroid/raindroidxposed/src/main/res/values-v11/styles.xml +++ b/ide/raindroid/raindroidxposed/src/main/res/values-v11/styles.xml @@ -1,15 +1,15 @@ - - - - - - - + + + + + + + diff --git a/ide/raindroid/raindroidxposed/src/main/res/values-w820dp/dimens.xml b/ide/raindroid/raindroidxposed/src/main/res/values-w820dp/dimens.xml index 62df1875a..63fc81644 100644 --- a/ide/raindroid/raindroidxposed/src/main/res/values-w820dp/dimens.xml +++ b/ide/raindroid/raindroidxposed/src/main/res/values-w820dp/dimens.xml @@ -1,6 +1,6 @@ - - - 64dp - + + + 64dp + diff --git a/ide/raindroid/raindroidxposed/src/main/res/values/attrs.xml b/ide/raindroid/raindroidxposed/src/main/res/values/attrs.xml index 0917430c8..7ce840eb6 100644 --- a/ide/raindroid/raindroidxposed/src/main/res/values/attrs.xml +++ b/ide/raindroid/raindroidxposed/src/main/res/values/attrs.xml @@ -1,12 +1,12 @@ - - - - - - - - - + + + + + + + + + diff --git a/ide/raindroid/raindroidxposed/src/main/res/values/colors.xml b/ide/raindroid/raindroidxposed/src/main/res/values/colors.xml index ee4d8919e..327c0604c 100644 --- a/ide/raindroid/raindroidxposed/src/main/res/values/colors.xml +++ b/ide/raindroid/raindroidxposed/src/main/res/values/colors.xml @@ -1,5 +1,5 @@ - - - #66000000 - - + + + #66000000 + + diff --git a/ide/raindroid/raindroidxposed/src/main/res/values/dimens.xml b/ide/raindroid/raindroidxposed/src/main/res/values/dimens.xml index 295b5a9de..47c822467 100644 --- a/ide/raindroid/raindroidxposed/src/main/res/values/dimens.xml +++ b/ide/raindroid/raindroidxposed/src/main/res/values/dimens.xml @@ -1,5 +1,5 @@ - - - 16dp - 16dp - + + + 16dp + 16dp + diff --git a/ide/raindroid/raindroidxposed/src/main/res/values/strings.xml b/ide/raindroid/raindroidxposed/src/main/res/values/strings.xml index 4e32469bc..84d80d060 100644 --- a/ide/raindroid/raindroidxposed/src/main/res/values/strings.xml +++ b/ide/raindroid/raindroidxposed/src/main/res/values/strings.xml @@ -1,11 +1,11 @@ - - RaindroidXposed - DangerousActivity - - Hello world! - Settings - Dummy Button - DUMMY\nCONTENT - Dangerous Activity Detected - Raindroid has detected a potentially malicious action. Please select one of the mitigations below. - + + RaindroidXposed + DangerousActivity + + Hello world! + Settings + Dummy Button + DUMMY\nCONTENT + Dangerous Activity Detected + Raindroid has detected a potentially malicious action. Please select one of the mitigations below. + diff --git a/ide/raindroid/raindroidxposed/src/main/res/values/styles.xml b/ide/raindroid/raindroidxposed/src/main/res/values/styles.xml index be5dfbab6..8d8c40ef6 100644 --- a/ide/raindroid/raindroidxposed/src/main/res/values/styles.xml +++ b/ide/raindroid/raindroidxposed/src/main/res/values/styles.xml @@ -1,27 +1,27 @@ - - - - - - - - - - - - + + + + + + + + - - -

Z.com News - Hello World! (High-fidelity Settings)

-This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. - - - - -END - -?> + 1 && time()%$content == 0) { + echo << + +Please come back... + + +I (the server) am swamped right now!!
+Please kindly come back in a couple of minutes.
+Sorry for the inconvenience, and thanks for understanding! + + +REJECT; + exit(); +} + +/* +$mysql_url = ''; +$mysql_user = ''; +$mysql_password = ''; +$mysql_db = ''; + +$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) + or die('Could not connect: ' . mysql_error()); + +$mydb = mysql_select_db($mysql_db, $link); +if(!$mydb) { + die('Could not select Test database: ' . mysql_error()); +} + +// Performing SQL query +$query = "SELECT COUNT(*) FROM cur"; +$result = mysql_query($query, $link) + or die('Query COUNT failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if ($row != false) { + $numItems = $row[0]; +} + +$idx = rand(1, $numItems); +$query = "SELECT cur_text FROM cur LIMIT $idx,1"; +$result = mysql_query($query, $link) + or die('Query item $idx failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if($row != false) { + $text = $row[0]; +} +*/ +$idx = 0; +$text = ""; + +echo << + +Somewhere Over the Rainbow + + + +

Z.com News - Hello World! (High-fidelity Settings)

+This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. + + + + +END + +?> diff --git a/targets/znews-ss-client/model/DoSFam.acme b/targets/znews-ss-client/model/DoSFam.acme index 517612eea..2e54d6974 100644 --- a/targets/znews-ss-client/model/DoSFam.acme +++ b/targets/znews-ss-client/model/DoSFam.acme @@ -1,46 +1,46 @@ -Family DoSFam = { - - Element Type PotentiallyMaliciousT = { - - Property deploymentLocation : string; - - Property maliciousness : float << default : float = 0.0; >> ; - - } - - Element Type MaliciousT extends PotentiallyMaliciousT with { - rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; - } - - Element Type SuspiciousT extends PotentiallyMaliciousT with { - rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD && maliciousness <= MALICIOUS_THRESHOLD; - } - - Element Type NormalT extends PotentiallyMaliciousT with { - rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; - - Element Type BlackholerT = { - - Property blackholed : Set {string} << default : Set {string} = {}; >> ; - - } - Port Type BlackholedPortT = { - - Property isBlackholed : boolean = true; - - } - - Port Type CaptchaPortT = { - Property captchaEnabled : boolean << default : boolean = false;>>; - } - - Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; - Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; - rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | - exists bh : BlackholerT in self.COMPONENTS | - contains(c.deploymentLocation, bh.blackholed); - rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.components | - forall ip : string in lb.blackholed | - forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | - c.maliciousness > self.MALICIOUS_THRESHOLD; +Family DoSFam = { + + Element Type PotentiallyMaliciousT = { + + Property deploymentLocation : string; + + Property maliciousness : float << default : float = 0.0; >> ; + + } + + Element Type MaliciousT extends PotentiallyMaliciousT with { + rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; + } + + Element Type SuspiciousT extends PotentiallyMaliciousT with { + rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD && maliciousness <= MALICIOUS_THRESHOLD; + } + + Element Type NormalT extends PotentiallyMaliciousT with { + rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; + + Element Type BlackholerT = { + + Property blackholed : Set {string} << default : Set {string} = {}; >> ; + + } + Port Type BlackholedPortT = { + + Property isBlackholed : boolean = true; + + } + + Port Type CaptchaPortT = { + Property captchaEnabled : boolean << default : boolean = false;>>; + } + + Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; + Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; + rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | + exists bh : BlackholerT in self.COMPONENTS | + contains(c.deploymentLocation, bh.blackholed); + rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.components | + forall ip : string in lb.blackholed | + forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | + c.maliciousness > self.MALICIOUS_THRESHOLD; } \ No newline at end of file diff --git a/targets/znews-ss-client/model/TargetEnv.acme b/targets/znews-ss-client/model/TargetEnv.acme index 4331c55b7..2ec6be259 100644 --- a/targets/znews-ss-client/model/TargetEnv.acme +++ b/targets/znews-ss-client/model/TargetEnv.acme @@ -1,4 +1,4 @@ -System TargetEnv = { - -} - +System TargetEnv = { + +} + diff --git a/targets/znews-ss-client/model/TargetEnvType.acme b/targets/znews-ss-client/model/TargetEnvType.acme index a91a99173..91e499a0e 100644 --- a/targets/znews-ss-client/model/TargetEnvType.acme +++ b/targets/znews-ss-client/model/TargetEnvType.acme @@ -1,67 +1,67 @@ -Family EnvType = { - - Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; - - Role Type ArchRoleT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type PartPortT = { - - } - Component Type ArchElementT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type NetworkRoleT = { - - } - Connector Type MappingT = { - - } - Role Type PartRoleT = { - - } - Connector Type EdgeT = { - - Property bandwidthAvg : ResourceStatePropT; - - Property capacity : ResourceStatePropT; - - } - Component Type NodeT = { - - Property cpuOverall : ResourceStatePropT; - - Property memoryMain : ResourceStatePropT; - - Property storageLocal : ResourceStatePropT; - - Property socketPool : ResourceStatePropT; - - Property batteryOverall : ResourceStatePropT; - - } - Port Type NetworkPortT = { - - } - Connector Type ArchConnT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type ArchPortT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type ContainerRoleT = { - - } - Port Type ContainmentPortT = { - - } -} - +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type PartPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type NetworkRoleT = { + + } + Connector Type MappingT = { + + } + Role Type PartRoleT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Port Type NetworkPortT = { + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type ContainerRoleT = { + + } + Port Type ContainmentPortT = { + + } +} + diff --git a/targets/znews-ss-client/model/TargetEnvType.mtd b/targets/znews-ss-client/model/TargetEnvType.mtd index 6817ebfa8..9d8d87f85 100644 --- a/targets/znews-ss-client/model/TargetEnvType.mtd +++ b/targets/znews-ss-client/model/TargetEnvType.mtd @@ -1,475 +1,475 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews-ss-client/model/ZNewsSys.mtd b/targets/znews-ss-client/model/ZNewsSys.mtd index 9975f54af..e847ff51b 100644 --- a/targets/znews-ss-client/model/ZNewsSys.mtd +++ b/targets/znews-ss-client/model/ZNewsSys.mtd @@ -1,396 +1,396 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews-ss-client/model/gauges.yml b/targets/znews-ss-client/model/gauges.yml index eb44d96a4..639858eb0 100644 --- a/targets/znews-ss-client/model/gauges.yml +++ b/targets/znews-ss-client/model/gauges.yml @@ -1,301 +1,301 @@ -# -# Gauge Type and Gauge Instance Specifications -# - time periods generally in milliseconds -# -# History: -# - [SWC 2007.01.18] Created file, populated ZNews gauge descriptions. -# - [SWC 2007.04.09] Changed LatencyGaugeT to use RtLatencyMultiHostGauge. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# - [SWC 2007.04.11] Added ResponseTimeGaugeT -# - [BRS 2013.11.13] Changed to new format -# -gauge-types: - - ClientGaugeT: - commands: - addClient: "ZNewsFam.addClient(String,String)" - deleteClient: "ZNewsFam.deleteClient(String)" - setClientRequestRate: "ClientT.setClientRequestRate(float)" - setupParams: - targetIP: - type: String - default: "localhost" - window: - type: long - default: 30000 - discardAfter: - type: long - default: 1800000 - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.ClientGauge" - configParams: - targetProbeType: - type: String - default: ~ - - ClientResponseTimeGaugeT: - commands: - responseTime: ClientT.setResponseTime (float) - setupParams: - targetIP: - type: string - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.ClientResponseTimeGauge" - configParams: - targetProbeType: - type: String - default: ~ - comment: "Gets the response time given to the client according to the load balancer" - - MaliciousnessGaugeT: - commands: - setMaliciousness: ClientT.setMaliciousness (float) - setupParams: - targetIP: - type: string - default: "localhost" - beaconPeriod: - type: long - default: 300000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.RequestRateBasedMaliciousnessGauge" - configParams: - maliciousRequestRate: - type: float - default: 10.0 - requestRateProperty: - type: String - default: reqRate - comment: "Gets a request rate for a client and sets the malciousness based on that" - - BlackHoleGaugeT: - commands: - blockedIPs: "BlackholerT.setBlackholed({String})" - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.BlackholeGauge" - configParams: - targetProbeType: - type: String - default: ~ - - ThrottleGaugeT: - commands: - throttledIPs: "ThrottlerT.setThrottled({String})" - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.ThrottleGauge" - configParams: - targetProbeType: - type: String - default: ~ - - CaptchaGaugeT: - commands: - enablement : ProxyT.setCaptchaEnabled (boolean) - clientMgmt : CaptchaHandlerT.setCaptchaResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 5000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.CaptchaGauge" - configParams: - targetProbeType: - type: String - default: ~ - - AuthenticationEnablementGaugeT: - commands: - clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 5000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge" - configParams: - targetProbeType: - type: String - default: ~ - - ServerEnablementGaugeT: - commands: - removeServer: ServerT.deleteServer - addServer: "ProxyT.connectNewServer (String, String, String)" - enableServer: ServerT.enableServer (boolean) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 10000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.ServerEnablementGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - mode: - type: String - default: "enable" - comment: "ServerEnablementGaugeT reports creation/deletion or enablement/disablement of servers. mode can be either enable|new" - - FidelityGaugeT: - commands: - fidelity : ServerT.setFidelity(int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.FidelityGauge" - configParams: - samplingFrequency: - type: long - default: 2500 - targetProbeType: - type: String - default: ~ - comment: "FidelityGaugeT measures and reports the fidelity level of served content" - -gauge-instances: - - MG1: - type: MaliciousnessGaugeT - model: "ZNewsSys:Acme" - commands: - setMaliciousness: "$.setMaliciousness($)" - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - maliciousRequestRate: 3.0 - - ClG1: - type: ClientGaugeT - model: "ZNewsSys:Acme" - commands: - "addClient": "ZNewsSys.addClient(LB0,$)" - "removeClient": "ZNewsSys.removeClient($)" - "setClientRequestRate": "ClientT.setClientRequestRate($)" - setupValues: - targetIP: "${customize.system.target.master}" - window: 10000 - discardAfter: 180001 - configValues: - reportingPeriod: 5000 - targetProbeType: "client@${customize.system.target.lb}" - - CRTG1: - type: ClientResponseTimeGaugeT - model: "ZNewsSys:Acme" - commands: - "responseTime": "ClientT.setResponseTime(rt)" - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - targetProbeType: "client" - - BHG1: - type: BlackHoleGaugeT - model: "ZNewsSys:Acme" - commands: - "blockedIPs": LB0.setBlackholed ($) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - reportingPeriod: 10000 - targetProbeType: blackhole - - TG1: - type: ThrottleGaugeT - model: "ZNewsSys:Acme" - commands: - "throttledIPs": LB0.setThrottled ($) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - reportingPeriod: 10000 - targetProbeType: throttle - - CG1: - type: CaptchaGaugeT - model: "ZNewsSys:Acme" - commands: - "enabled": LB0.setCaptchaEnabled($) - "clientMgmt(${customize.system.target.client1})": Client0.setCaptchaResponse (0) - "clientMgmt(${customize.system.target.client2})": Client1.setCaptchaResponse (0) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - samplingFrequency: 1000 - targetProbeType: captchaprobe - - AEG1: - type: AuthenticationEnablementGaugeT - model: "ZNewsSys:Acme" - commands: - "clientMgmt(${customize.system.target.client1})": Client0.setAuthenticationResponse (0) - "clientMgmt(${customize.system.target.client2})": Client1.setAuthenticationResponse (0) - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - samplingFrequency: 1000 - targetProbeType: authenticationprobe - - SEG1: - type: ServerEnablementGaugeT - model: "ZNewsSys:Acme" - commands: - "removeServer(x)": x.deleteServer - "connectServer(x)": "LB0.connectNewServer (Server0, $, $)" - "enableServer(x)": "LB0.enableServer (x, $)" - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - targetProbeType: "enablementprobe@${customize.system.target.lb}" - samplingFrequency: 1000 - mode: new - comment: "This needs to be located on the master because it needs access to the model" +# +# Gauge Type and Gauge Instance Specifications +# - time periods generally in milliseconds +# +# History: +# - [SWC 2007.01.18] Created file, populated ZNews gauge descriptions. +# - [SWC 2007.04.09] Changed LatencyGaugeT to use RtLatencyMultiHostGauge. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# - [SWC 2007.04.11] Added ResponseTimeGaugeT +# - [BRS 2013.11.13] Changed to new format +# +gauge-types: + + ClientGaugeT: + commands: + addClient: "ZNewsFam.addClient(String,String)" + deleteClient: "ZNewsFam.deleteClient(String)" + setClientRequestRate: "ClientT.setClientRequestRate(float)" + setupParams: + targetIP: + type: String + default: "localhost" + window: + type: long + default: 30000 + discardAfter: + type: long + default: 1800000 + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.ClientGauge" + configParams: + targetProbeType: + type: String + default: ~ + + ClientResponseTimeGaugeT: + commands: + responseTime: ClientT.setResponseTime (float) + setupParams: + targetIP: + type: string + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.ClientResponseTimeGauge" + configParams: + targetProbeType: + type: String + default: ~ + comment: "Gets the response time given to the client according to the load balancer" + + MaliciousnessGaugeT: + commands: + setMaliciousness: ClientT.setMaliciousness (float) + setupParams: + targetIP: + type: string + default: "localhost" + beaconPeriod: + type: long + default: 300000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.RequestRateBasedMaliciousnessGauge" + configParams: + maliciousRequestRate: + type: float + default: 10.0 + requestRateProperty: + type: String + default: reqRate + comment: "Gets a request rate for a client and sets the malciousness based on that" + + BlackHoleGaugeT: + commands: + blockedIPs: "BlackholerT.setBlackholed({String})" + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.BlackholeGauge" + configParams: + targetProbeType: + type: String + default: ~ + + ThrottleGaugeT: + commands: + throttledIPs: "ThrottlerT.setThrottled({String})" + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.ThrottleGauge" + configParams: + targetProbeType: + type: String + default: ~ + + CaptchaGaugeT: + commands: + enablement : ProxyT.setCaptchaEnabled (boolean) + clientMgmt : CaptchaHandlerT.setCaptchaResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 5000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.CaptchaGauge" + configParams: + targetProbeType: + type: String + default: ~ + + AuthenticationEnablementGaugeT: + commands: + clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 5000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge" + configParams: + targetProbeType: + type: String + default: ~ + + ServerEnablementGaugeT: + commands: + removeServer: ServerT.deleteServer + addServer: "ProxyT.connectNewServer (String, String, String)" + enableServer: ServerT.enableServer (boolean) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 10000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.ServerEnablementGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + mode: + type: String + default: "enable" + comment: "ServerEnablementGaugeT reports creation/deletion or enablement/disablement of servers. mode can be either enable|new" + + FidelityGaugeT: + commands: + fidelity : ServerT.setFidelity(int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.FidelityGauge" + configParams: + samplingFrequency: + type: long + default: 2500 + targetProbeType: + type: String + default: ~ + comment: "FidelityGaugeT measures and reports the fidelity level of served content" + +gauge-instances: + + MG1: + type: MaliciousnessGaugeT + model: "ZNewsSys:Acme" + commands: + setMaliciousness: "$.setMaliciousness($)" + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + maliciousRequestRate: 3.0 + + ClG1: + type: ClientGaugeT + model: "ZNewsSys:Acme" + commands: + "addClient": "ZNewsSys.addClient(LB0,$)" + "removeClient": "ZNewsSys.removeClient($)" + "setClientRequestRate": "ClientT.setClientRequestRate($)" + setupValues: + targetIP: "${customize.system.target.master}" + window: 10000 + discardAfter: 180001 + configValues: + reportingPeriod: 5000 + targetProbeType: "client@${customize.system.target.lb}" + + CRTG1: + type: ClientResponseTimeGaugeT + model: "ZNewsSys:Acme" + commands: + "responseTime": "ClientT.setResponseTime(rt)" + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + targetProbeType: "client" + + BHG1: + type: BlackHoleGaugeT + model: "ZNewsSys:Acme" + commands: + "blockedIPs": LB0.setBlackholed ($) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + reportingPeriod: 10000 + targetProbeType: blackhole + + TG1: + type: ThrottleGaugeT + model: "ZNewsSys:Acme" + commands: + "throttledIPs": LB0.setThrottled ($) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + reportingPeriod: 10000 + targetProbeType: throttle + + CG1: + type: CaptchaGaugeT + model: "ZNewsSys:Acme" + commands: + "enabled": LB0.setCaptchaEnabled($) + "clientMgmt(${customize.system.target.client1})": Client0.setCaptchaResponse (0) + "clientMgmt(${customize.system.target.client2})": Client1.setCaptchaResponse (0) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + samplingFrequency: 1000 + targetProbeType: captchaprobe + + AEG1: + type: AuthenticationEnablementGaugeT + model: "ZNewsSys:Acme" + commands: + "clientMgmt(${customize.system.target.client1})": Client0.setAuthenticationResponse (0) + "clientMgmt(${customize.system.target.client2})": Client1.setAuthenticationResponse (0) + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + samplingFrequency: 1000 + targetProbeType: authenticationprobe + + SEG1: + type: ServerEnablementGaugeT + model: "ZNewsSys:Acme" + commands: + "removeServer(x)": x.deleteServer + "connectServer(x)": "LB0.connectNewServer (Server0, $, $)" + "enableServer(x)": "LB0.enableServer (x, $)" + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + targetProbeType: "enablementprobe@${customize.system.target.lb}" + samplingFrequency: 1000 + mode: new + comment: "This needs to be located on the master because it needs access to the model" \ No newline at end of file diff --git a/targets/znews-ss-client/model/op.map b/targets/znews-ss-client/model/op.map index 867bb0232..5cf840f9c 100644 --- a/targets/znews-ss-client/model/op.map +++ b/targets/znews-ss-client/model/op.map @@ -1,8 +1,8 @@ -setFidelity: changeState -blackhole: changeState -unblackhole: changeState -enableCaptcha: changeState -disableCaptcha: changeState -activateServer: start -deactivateServer: stop - +setFidelity: changeState +blackhole: changeState +unblackhole: changeState +enableCaptcha: changeState +disableCaptcha: changeState +activateServer: start +deactivateServer: stop + diff --git a/targets/znews-ss-client/rainbow-10.0.0.173.properties b/targets/znews-ss-client/rainbow-10.0.0.173.properties index 6a838d963..9ebc1d58a 100644 --- a/targets/znews-ss-client/rainbow-10.0.0.173.properties +++ b/targets/znews-ss-client/rainbow-10.0.0.173.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.0.146 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.0.173 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.0.146 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.0.173 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-client/rainbow-10.0.0.183.properties b/targets/znews-ss-client/rainbow-10.0.0.183.properties index 3e3b1ba8b..2e5ef12a8 100644 --- a/targets/znews-ss-client/rainbow-10.0.0.183.properties +++ b/targets/znews-ss-client/rainbow-10.0.0.183.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.0.146 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.0.183 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.0.146 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.0.183 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-client/rainbow-10.0.0.210.properties b/targets/znews-ss-client/rainbow-10.0.0.210.properties index c6db960bc..7477ff667 100644 --- a/targets/znews-ss-client/rainbow-10.0.0.210.properties +++ b/targets/znews-ss-client/rainbow-10.0.0.210.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.0.146 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.0.210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.0.146 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.0.210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-client/rainbow-10.0.0.98.properties b/targets/znews-ss-client/rainbow-10.0.0.98.properties index c7c7a7f1b..ff0895701 100644 --- a/targets/znews-ss-client/rainbow-10.0.0.98.properties +++ b/targets/znews-ss-client/rainbow-10.0.0.98.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.0.146 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.0.98 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.0.146 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.0.98 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-client/rainbow-10.5.6.5.properties b/targets/znews-ss-client/rainbow-10.5.6.5.properties index f92704d09..e5cf62d61 100644 --- a/targets/znews-ss-client/rainbow-10.5.6.5.properties +++ b/targets/znews-ss-client/rainbow-10.5.6.5.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.5 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.5 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-client/rainbow-10.5.6.6.properties b/targets/znews-ss-client/rainbow-10.5.6.6.properties index 9ea44d2bd..7b9c3b575 100644 --- a/targets/znews-ss-client/rainbow-10.5.6.6.properties +++ b/targets/znews-ss-client/rainbow-10.5.6.6.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.6 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.6 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-client/rainbow.properties b/targets/znews-ss-client/rainbow.properties index b9bd60cfa..617029b81 100644 --- a/targets/znews-ss-client/rainbow.properties +++ b/targets/znews-ss-client/rainbow.properties @@ -1,127 +1,127 @@ -################################################################################ -# Purpose: Common configuration file for the Rainbow infrastructure. -# Properties are loaded by class org.sa.rainbow.Rainbow . -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -### -# Default values for location specific properties, meaning that, if the -# rainbow-.properties file does not specify a value, the default value -# set here is used. - -### Utility mechanism configuration -#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL -logging.level = DEBUG -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log -# (default) -#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" -#logging.max.size = 1024 -#logging.max.backups = 5 - -### Rainbow component customization -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = 127.0.0.1 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.0.146 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.event.service = eseb -eBus Relay - -rainbow.delegate.beaconperiod = 10000 -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory - -### Rainbow models -rainbow.model.number=3 - -# Rainbow Acme model of ZNN -rainbow.model.path_0 = model/ZNewsSys.acme -rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory -rainbow.model.name_0 = ZNewsSys -rainbow.model.saveOnClose_0=true -rainbow.model.saveLocation_0=model/ZNewSys-post.acme - -# Rainbow utility model - keeps current utility along desired utility dimensions -# specified in stitch/utilities.yml -rainbow.model.path_1 = stitch/utilities.yml -rainbow.model.load.class_1=org.sa.rainbow.model.utility.UtilityCommandFactory -rainbow.model.name_1=ZNewsSys - -# Rainbow utility history model - keeps utility history -rainbow.model.load.class_2=org.sa.rainbow.model.utility.UtilityHistoryCommandFactory -rainbow.model.name_2=ZNewsSys -rainbow.model.saveOnClose_2=true -rainbow.model.saveLocation_2=model/uh.csv - - -### Rainbow analyses -rainbow.analyses.size = 2 -# Checks architecture for architectural errors -rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator -# Calculates utility of the system after each change to the arch model -rainbow.analyses_1 = org.sa.rainbow.evaluator.utility.UtilityEvaluator - -#Rainbow adaptation & stitch components -rainbow.adaptation.manager.size = 1 -rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager -rainbow.adaptation.manager.model_0=ZNewsSys:Acme - -rainbow.adaptation.executor.size = 1 -rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.StitchExecutor -rainbow.adaptation.executor.model_0=ZNewsSys:Acme - -rainbow.effector.manager.size = 1 -rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager - - -customize.model.evaluate.period = 2000 -## Translator customization -#- Gauge spec -customize.gauges.path = model/gauges.yml -#- Probe spec -customize.probes.path = system/probes.yml -#- Operator spec as mapping to effector -customize.archop.map.path = model/op.map -#- Effector spec -customize.effectors.path = system/effectors.yml -## Adaptation Manager -#- Directory of Stitch adaptation script -customize.scripts.path = stitch -#- Utilities description file, Strategy evaluation config, and minimum score threshold -customize.utility.path = stitch/utilities.yml -customize.utility.trackStrategy = uSF -customize.utility.score.minimum.threshold = 0.33 -customize.utility.scenario = scenario 1 -#- Whether to enable prediction, ONLY enable if system has predictor probes! -#customize.prediction.enable = false - -## System configuration information -# These properties may be referred to in various files -# in the target (e.g., Acme, gauges, effectors, probes) -# and are replaced by Rainbow with the actual values -customize.system.target.master = ${rainbow.deployment.location} -customize.system.target.lb = 10.0.0.173 -customize.system.target.lb.httpPort = 1081 -customize.system.target.web0 = 10.0.0.210 -customize.system.target.web0.httpPort = 1080 -customize.system.target.web1 = 10.0.0.98 -customize.system.target.web1.httpPort = 1080 -customize.system.target.db = 10.0.0.21 -customize.system.target.web2 = 10.0.0.183 -customize.system.target.web2.httpPort=1080 -customize.system.target.web2.disabled=true -customize.system.target.client1=10.0.0.146 -customize.system.target.client2=10.0.0.1 -customize.system.target.bad=10.0.0.1 +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +logging.level = DEBUG +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = 127.0.0.1 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.0.146 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.event.service = eseb +eBus Relay + +rainbow.delegate.beaconperiod = 10000 +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory + +### Rainbow models +rainbow.model.number=3 + +# Rainbow Acme model of ZNN +rainbow.model.path_0 = model/ZNewsSys.acme +rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory +rainbow.model.name_0 = ZNewsSys +rainbow.model.saveOnClose_0=true +rainbow.model.saveLocation_0=model/ZNewSys-post.acme + +# Rainbow utility model - keeps current utility along desired utility dimensions +# specified in stitch/utilities.yml +rainbow.model.path_1 = stitch/utilities.yml +rainbow.model.load.class_1=org.sa.rainbow.model.utility.UtilityCommandFactory +rainbow.model.name_1=ZNewsSys + +# Rainbow utility history model - keeps utility history +rainbow.model.load.class_2=org.sa.rainbow.model.utility.UtilityHistoryCommandFactory +rainbow.model.name_2=ZNewsSys +rainbow.model.saveOnClose_2=true +rainbow.model.saveLocation_2=model/uh.csv + + +### Rainbow analyses +rainbow.analyses.size = 2 +# Checks architecture for architectural errors +rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator +# Calculates utility of the system after each change to the arch model +rainbow.analyses_1 = org.sa.rainbow.evaluator.utility.UtilityEvaluator + +#Rainbow adaptation & stitch components +rainbow.adaptation.manager.size = 1 +rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager +rainbow.adaptation.manager.model_0=ZNewsSys:Acme + +rainbow.adaptation.executor.size = 1 +rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.StitchExecutor +rainbow.adaptation.executor.model_0=ZNewsSys:Acme + +rainbow.effector.manager.size = 1 +rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager + + +customize.model.evaluate.period = 2000 +## Translator customization +#- Gauge spec +customize.gauges.path = model/gauges.yml +#- Probe spec +customize.probes.path = system/probes.yml +#- Operator spec as mapping to effector +customize.archop.map.path = model/op.map +#- Effector spec +customize.effectors.path = system/effectors.yml +## Adaptation Manager +#- Directory of Stitch adaptation script +customize.scripts.path = stitch +#- Utilities description file, Strategy evaluation config, and minimum score threshold +customize.utility.path = stitch/utilities.yml +customize.utility.trackStrategy = uSF +customize.utility.score.minimum.threshold = 0.33 +customize.utility.scenario = scenario 1 +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# These properties may be referred to in various files +# in the target (e.g., Acme, gauges, effectors, probes) +# and are replaced by Rainbow with the actual values +customize.system.target.master = ${rainbow.deployment.location} +customize.system.target.lb = 10.0.0.173 +customize.system.target.lb.httpPort = 1081 +customize.system.target.web0 = 10.0.0.210 +customize.system.target.web0.httpPort = 1080 +customize.system.target.web1 = 10.0.0.98 +customize.system.target.web1.httpPort = 1080 +customize.system.target.db = 10.0.0.21 +customize.system.target.web2 = 10.0.0.183 +customize.system.target.web2.httpPort=1080 +customize.system.target.web2.disabled=true +customize.system.target.client1=10.0.0.146 +customize.system.target.client2=10.0.0.1 +customize.system.target.bad=10.0.0.1 diff --git a/targets/znews-ss-client/rainbow.properties-all-in-one-machine b/targets/znews-ss-client/rainbow.properties-all-in-one-machine index f05013820..349283e56 100644 --- a/targets/znews-ss-client/rainbow.properties-all-in-one-machine +++ b/targets/znews-ss-client/rainbow.properties-all-in-one-machine @@ -1,112 +1,112 @@ -################################################################################ -# Purpose: Common configuration file for the Rainbow infrastructure. -# Properties are loaded by class org.sa.rainbow.Rainbow . -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -### -# Default values for location specific properties, meaning that, if the -# rainbow-.properties file does not specify a value, the default value -# set here is used. - -### Utility mechanism configuration -#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL -logging.level = DEBUG -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log -# (default) -#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" -#logging.max.size = 1024 -#logging.max.backups = 5 - -### Rainbow component customization -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = 127.0.0.1 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.2.2 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.event.service = eseb -eBus Relay - -rainbow.delegate.beaconperiod = 10000 -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory - -#Rainbow models -rainbow.model.number=1 -rainbow.model.path_0 = model/ZNewsSys.acme -rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory -rainbow.model.name_0 = ZNewsSys - -#Rainbow analyses -rainbow.analyses.size = 1 -rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator - -#Rainbow adaptation & stitch components -rainbow.adaptation.manager.size = 1 -rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager -rainbow.adaptation.manager.model_0=ZNewsSys:Acme - -rainbow.adaptation.executor.size = 1 -rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.Executor -rainbow.adaptation.executor.model_0=ZNewsSys:Acme - -rainbow.effector.manager.size = 1 -rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager - - -customize.model.evaluate.period = 2000 -## Translator customization -#- Gauge spec -customize.gauges.path = model/gauges.yml -#- Probe spec -customize.probes.path = system/probes.yml -#- Operator spec as mapping to effector -customize.archop.map.path = model/op.map -#- Effector spec -customize.effectors.path = system/effectors.yml -## Adaptation Manager -#- Directory of Stitch adaptation script -customize.scripts.path = stitch -#- Utilities description file, Strategy evaluation config, and minimum score threshold -customize.utility.path = stitch/utilities.yml -customize.utility.trackStrategy = uSF -customize.utility.score.minimum.threshold = 0.33 -customize.utility.scenario = scenario 2 -#- Whether to enable prediction, ONLY enable if system has predictor probes! -#customize.prediction.enable = false - -## System configuration information -# -#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: -#customize.system.sim.path = znewspred/znews-transbw.sim -#- if real target system: -#customize.system.target.0 = ${rainbow.master.location.host} -#customize.system.target.1 = 10.0.2.15 -#customize.system.target.1 = waterfall.able.cs.cmu.edu -#customize.system.target.0 = localhost -#customize.system.target.2 = oracle -#customize.system.target.size = 3 -#customize.system.target.size = 2 -customize.system.target.master = ${rainbow.deployment.location} -customize.system.target.lb = 10.5.6.1 -customize.system.target.lb.httpPort = 1081 -customize.system.target.web0 = 10.5.6.1 -customize.system.target.web0.httpPort = 1080 -customize.system.target.web1 = 10.5.6.1 -customize.system.target.web1.httpPort = 1082 -customize.system.target.db = 10.5.6.1 -#customize.system.target.0 = ${rainbow.deployment.location} -#customize.system.target.1 = 10.5.6.1 -#customize.system.target.size = 2 +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +logging.level = DEBUG +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = 127.0.0.1 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.2.2 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.event.service = eseb +eBus Relay + +rainbow.delegate.beaconperiod = 10000 +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory + +#Rainbow models +rainbow.model.number=1 +rainbow.model.path_0 = model/ZNewsSys.acme +rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory +rainbow.model.name_0 = ZNewsSys + +#Rainbow analyses +rainbow.analyses.size = 1 +rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator + +#Rainbow adaptation & stitch components +rainbow.adaptation.manager.size = 1 +rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager +rainbow.adaptation.manager.model_0=ZNewsSys:Acme + +rainbow.adaptation.executor.size = 1 +rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.Executor +rainbow.adaptation.executor.model_0=ZNewsSys:Acme + +rainbow.effector.manager.size = 1 +rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager + + +customize.model.evaluate.period = 2000 +## Translator customization +#- Gauge spec +customize.gauges.path = model/gauges.yml +#- Probe spec +customize.probes.path = system/probes.yml +#- Operator spec as mapping to effector +customize.archop.map.path = model/op.map +#- Effector spec +customize.effectors.path = system/effectors.yml +## Adaptation Manager +#- Directory of Stitch adaptation script +customize.scripts.path = stitch +#- Utilities description file, Strategy evaluation config, and minimum score threshold +customize.utility.path = stitch/utilities.yml +customize.utility.trackStrategy = uSF +customize.utility.score.minimum.threshold = 0.33 +customize.utility.scenario = scenario 2 +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# +#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: +#customize.system.sim.path = znewspred/znews-transbw.sim +#- if real target system: +#customize.system.target.0 = ${rainbow.master.location.host} +#customize.system.target.1 = 10.0.2.15 +#customize.system.target.1 = waterfall.able.cs.cmu.edu +#customize.system.target.0 = localhost +#customize.system.target.2 = oracle +#customize.system.target.size = 3 +#customize.system.target.size = 2 +customize.system.target.master = ${rainbow.deployment.location} +customize.system.target.lb = 10.5.6.1 +customize.system.target.lb.httpPort = 1081 +customize.system.target.web0 = 10.5.6.1 +customize.system.target.web0.httpPort = 1080 +customize.system.target.web1 = 10.5.6.1 +customize.system.target.web1.httpPort = 1082 +customize.system.target.db = 10.5.6.1 +#customize.system.target.0 = ${rainbow.deployment.location} +#customize.system.target.1 = 10.5.6.1 +#customize.system.target.size = 2 diff --git a/targets/znews-ss-client/stitch/README.txt b/targets/znews-ss-client/stitch/README.txt index fe0c94a76..1a5abb8c4 100644 --- a/targets/znews-ss-client/stitch/README.txt +++ b/targets/znews-ss-client/stitch/README.txt @@ -1,2 +1,2 @@ -Extension: Stitch scripts must have the extension ".s"; otherwise, the -Adaptation Manager will not know to load it. +Extension: Stitch scripts must have the extension ".s"; otherwise, the +Adaptation Manager will not know to load it. diff --git a/targets/znews-ss-client/stitch/dosStrategies.s b/targets/znews-ss-client/stitch/dosStrategies.s index 1ea44ac4d..935af78ed 100644 --- a/targets/znews-ss-client/stitch/dosStrategies.s +++ b/targets/znews-ss-client/stitch/dosStrategies.s @@ -1,107 +1,107 @@ -/* - * Adaptation script for security attacks - */ - -module dos.strategies; -import op "org.sa.rainbow.stitch.lib.*"; -import op "org.sa.rainbow.model.acme.znn.ZNN"; -import lib "dosTactics.s"; -import lib "newssiteTactics.s"; - -//define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); - -define boolean haveMaliciousAndSuspicious = exists c : D.ZNewsClientT in M.components | (c.maliciousness >= M.SUSPICIOUS_THRESHOLD); - -define boolean unhandledMalicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness >= M.MALICIOUS_THRESHOLD) && !((exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.blackholed)) || c.captcha == -1 || c.authenticate == -1)); - -// There are people who are suspicious but haven't been throttled -define boolean unhandledSuspicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness < M.MALICIOUS_THRESHOLD && c.maliciousness > M.SUSPICIOUS_THRESHOLD) && !((exists b : D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.throttled)) || c.captcha == -1 || c.authenticate == -1)); - -// There are clients blackholed that are not malicious -define boolean cUnfairlyPenalizedClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD))); - -// There are clients throttled that are not suspicous -define boolean cUnfairlyThrottledClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSPICOUS_THRESHOLD && c.maliciousness <= M.SUSPICIOUS_THRESHOLD))); - -define boolean aboveMaliciousThreshold = M.aboveMaliciousThreshold (M); - - -// We haven't captchaed -define boolean cNotChallenging = exists c : D.ZNewsLBT in M.components | (c.captchaEnabled == false); - -// Non-malicious clients are suffering high response times -define boolean cHiRespTime = exists c : T.ClientT/*,D.ZNewsClientT*/ in M.components | (c.experRespTime > M.MAX_RESPTIME); - -// There is atleast one reserve server available -define boolean serversAvailable = ZNN.availableServices(M,T.ServerT) > 0; - -/* Stop the attack by placing attackers into a blackhole. This strategy is triggered - * by the presence of an attacker and an impact on response time - */ -strategy EliminateStrategy -[ cHiRespTime && aboveMaliciousThreshold && (unhandledMalicious || unhandledSuspicious) ] { - t0: (unhandledMalicious || unhandledSuspicious) -> blackholeAttacker() @[5000 /*ms*/] { - t1: (!unhandledMalicious) -> done; - t1a: (unhandledSuspicious) -> throttleSuspicious () @[5000] { - t2a: (default) -> TNULL; // in this case, we have no more steps to take - t2b: (success) -> done; - } - } - t3: (default) -> TNULL; -} - -strategy RestoreStrategy -[cUnfairlyPenalizedClients || cUnfairlyThrottledClients] { - t0: (cUnfairlyPenalizedClients) -> unblackholeAttacker () @[2000 /*ms*/] { - t1 : (!cUnfairlyPenalizedClients) -> done; - t1a: (default) -> TNULL; - } - t2 : (cUnfairlyThrottledClients) -> unthrottle () @[2000] { - t2a: (!cUnfairlyThrottledClients) -> done; - t2b: (default) -> TNULL; - } -} - -strategy Challenge [cHiRespTime && aboveMaliciousThreshold && (unhandledMalicious || unhandledSuspicious)] { - t0: (cNotChallenging) -> addCaptcha () @[5000] { - t1: (success) -> done; - t1a: (default) -> TNULL; - } - t2: (!cNotChallenging) -> forceReauthentication () @[5000] { - t3: (success) -> done; - t3a: (default) -> TNULL; - - } -} - - - -strategy DisableChallenges [!haveMaliciousAndSuspicious && !cNotChallenging] { - t0: (!cNotChallenging) -> removeCaptcha () @[1000] { - t1: (cNotChallenging) -> done; - } -} - - -strategy SimpleReduceResponseTime -[cHiRespTime && aboveMaliciousThreshold && (unhandledMalicious || unhandledSuspicious)] { - t0: (/*hiLoad*/ cHiRespTime) -> enlistServers(1) @[1000 /*ms*/] { - t1: (!cHiRespTime) -> done; - t2: (cHiRespTime) -> lowerFidelity(2, 100) @[3000 /*ms*/] { - t2a: (!cHiRespTime) -> done; - t2b: (default) -> TNULL; // in this case, we have no more steps to take - } - } -} - -/* This strategy allocates more capacity to counter the impact of a DoS attack. - */ -//strategy IncreaseCapacityStrategy -//[ styleApplies && cHiRespTime && serversAvailable] { -// t0: (/* under attack */ cHiRespTime) -> enlistServer(1) @[1000 /*ms*/] { -// t1: (!cHiRespTime) -> done; -// t1a: (default) -> TNULL; // in this case, we have no more steps to take -// } -//} - - +/* + * Adaptation script for security attacks + */ + +module dos.strategies; +import op "org.sa.rainbow.stitch.lib.*"; +import op "org.sa.rainbow.model.acme.znn.ZNN"; +import lib "dosTactics.s"; +import lib "newssiteTactics.s"; + +//define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); + +define boolean haveMaliciousAndSuspicious = exists c : D.ZNewsClientT in M.components | (c.maliciousness >= M.SUSPICIOUS_THRESHOLD); + +define boolean unhandledMalicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness >= M.MALICIOUS_THRESHOLD) && !((exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.blackholed)) || c.captcha == -1 || c.authenticate == -1)); + +// There are people who are suspicious but haven't been throttled +define boolean unhandledSuspicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness < M.MALICIOUS_THRESHOLD && c.maliciousness > M.SUSPICIOUS_THRESHOLD) && !((exists b : D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.throttled)) || c.captcha == -1 || c.authenticate == -1)); + +// There are clients blackholed that are not malicious +define boolean cUnfairlyPenalizedClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD))); + +// There are clients throttled that are not suspicous +define boolean cUnfairlyThrottledClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSPICOUS_THRESHOLD && c.maliciousness <= M.SUSPICIOUS_THRESHOLD))); + +define boolean aboveMaliciousThreshold = M.aboveMaliciousThreshold (M); + + +// We haven't captchaed +define boolean cNotChallenging = exists c : D.ZNewsLBT in M.components | (c.captchaEnabled == false); + +// Non-malicious clients are suffering high response times +define boolean cHiRespTime = exists c : T.ClientT/*,D.ZNewsClientT*/ in M.components | (c.experRespTime > M.MAX_RESPTIME); + +// There is atleast one reserve server available +define boolean serversAvailable = ZNN.availableServices(M,T.ServerT) > 0; + +/* Stop the attack by placing attackers into a blackhole. This strategy is triggered + * by the presence of an attacker and an impact on response time + */ +strategy EliminateStrategy +[ cHiRespTime && aboveMaliciousThreshold && (unhandledMalicious || unhandledSuspicious) ] { + t0: (unhandledMalicious || unhandledSuspicious) -> blackholeAttacker() @[5000 /*ms*/] { + t1: (!unhandledMalicious) -> done; + t1a: (unhandledSuspicious) -> throttleSuspicious () @[5000] { + t2a: (default) -> TNULL; // in this case, we have no more steps to take + t2b: (success) -> done; + } + } + t3: (default) -> TNULL; +} + +strategy RestoreStrategy +[cUnfairlyPenalizedClients || cUnfairlyThrottledClients] { + t0: (cUnfairlyPenalizedClients) -> unblackholeAttacker () @[2000 /*ms*/] { + t1 : (!cUnfairlyPenalizedClients) -> done; + t1a: (default) -> TNULL; + } + t2 : (cUnfairlyThrottledClients) -> unthrottle () @[2000] { + t2a: (!cUnfairlyThrottledClients) -> done; + t2b: (default) -> TNULL; + } +} + +strategy Challenge [cHiRespTime && aboveMaliciousThreshold && (unhandledMalicious || unhandledSuspicious)] { + t0: (cNotChallenging) -> addCaptcha () @[5000] { + t1: (success) -> done; + t1a: (default) -> TNULL; + } + t2: (!cNotChallenging) -> forceReauthentication () @[5000] { + t3: (success) -> done; + t3a: (default) -> TNULL; + + } +} + + + +strategy DisableChallenges [!haveMaliciousAndSuspicious && !cNotChallenging] { + t0: (!cNotChallenging) -> removeCaptcha () @[1000] { + t1: (cNotChallenging) -> done; + } +} + + +strategy SimpleReduceResponseTime +[cHiRespTime && aboveMaliciousThreshold && (unhandledMalicious || unhandledSuspicious)] { + t0: (/*hiLoad*/ cHiRespTime) -> enlistServers(1) @[1000 /*ms*/] { + t1: (!cHiRespTime) -> done; + t2: (cHiRespTime) -> lowerFidelity(2, 100) @[3000 /*ms*/] { + t2a: (!cHiRespTime) -> done; + t2b: (default) -> TNULL; // in this case, we have no more steps to take + } + } +} + +/* This strategy allocates more capacity to counter the impact of a DoS attack. + */ +//strategy IncreaseCapacityStrategy +//[ styleApplies && cHiRespTime && serversAvailable] { +// t0: (/* under attack */ cHiRespTime) -> enlistServer(1) @[1000 /*ms*/] { +// t1: (!cHiRespTime) -> done; +// t1a: (default) -> TNULL; // in this case, we have no more steps to take +// } +//} + + diff --git a/targets/znews-ss-client/stitch/dosTactics.s b/targets/znews-ss-client/stitch/dosTactics.s index b2db07c05..c1303bcd3 100644 --- a/targets/znews-ss-client/stitch/dosTactics.s +++ b/targets/znews-ss-client/stitch/dosTactics.s @@ -1,160 +1,160 @@ -module dos.strategies; - -import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T, ZNewsDosFam as D} ; -import op "org.sa.rainbow.stitch.lib.*"; - -//-------------------------------------------------------------------------------------------------- -// ! exists c : ClientT in self.components | (c.isMalicious and !c.is_blackholed) -// -// Failing this would cause the strategy to fire -// In the long run, isMalicious could be a float that captures the probability -// that a client is malicious -- in this case, we would have a threshold value -// -// Countermeasure #3: Black Hole the attacker(s) -// Blackholing means replying with ICMP giving reason for Black hole the attacking -// client by redirecting connections from a client -// for some period of time (i.e. black hole the traffic). -// -tactic blackholeAttacker () { - condition { - exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.blackholed))); - - // currently just checking if the client is identified as malicious. - // exists c:D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD; - } - action { - // Find the attacker. Currently, this is done by checking if client is identified as an attacker - // the blackHole() routine re-routes all traffic from a client away from the backed servers - // thereby preventing attackers from consuming ZNN resources. - // - set evilClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD}; - set blackholedClients = M.LB0.blackholed; - for (T.ClientT target : evilClients) { - blackholedClients = Set.add (blackholedClients, target.deploymentLocation); - } - M.setBlackholed (M.LB0, blackholedClients); - } - effect { - // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? - // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true - // if the client is blackholed and false otherwise - forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.blackholed))); - //forall c:T.ClientT in M.components | (c.maliciousness > M.MALICIOUS_THRESHOLD) -> !c.isBlackholed)); - } -} - -tactic unblackholeAttacker () { - condition { - exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.blackholed) && c.maliciousness <= M.MALICIOUS_THRESHOLD); - } - action { - set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.MALICIOUS_THRESHOLD}; - set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.blackholed) > 0}; - for (D.ZNewsLBT l : lbs) { - set blackholedClients = l.blackholed; - for (D.ZNewsClientT c : reformedClients) { - // Curiously, if the unblackhole is only in the op.map and - // not in the the EffectOp class, then the parameters need - // to be paired with their parameter name - // Thus, (...,"client", c.deploymentLocation) here - // compared to blackhole above, which is actually - // a method provided in the EffectOp class - blackholedClients = Set.remove (blackholedClients, c.deploymentLocation); - } - M.setBlackholed (l, blackholedClients); - } - } - effect { - forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD)); - } -} - -tactic throttleSuspicious () { - condition { - exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.throttled))); - } - action { - // Find the attacker. Currently, this is done by checking if client is identified as an attacker - // the blackHole() routine re-routes all traffic from a client away from the backed servers - // thereby preventing attackers from consuming ZNN resources. - // - set suspciousClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.SUSCPICIOUS_THRESHOLD}; - set throttledClients = M.LB0.throttled; - for (T.ClientT target : suspciousClients) { - throttledClients = Set.add (throttledClients, target.deploymentLocation); - } - M.setThrottled (M.LB0, throttledClients); - } - effect { - // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? - // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true - // if the client is blackholed and false otherwise - forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.throttled))); - } -} - -tactic unthrottle () { - condition { - exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.throttled) && c.maliciousness <= M.SUSCPICIOUS_THRESHOLD); - } - action { - set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.SUSCPICIOUS_THRESHOLD}; - set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.throttled) > 0}; - for (D.ZNewsLBT l : lbs) { - set throttledClients = l.throttled; - for (D.ZNewsClientT c : reformedClients) { - throttledClients = Set.remove (throttledClients, c.deploymentLocation); - } - M.setThrottled (l, throttledClients); - } - } - effect { - forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSCPICIOUS_THRESHOLD)); - } -} - -tactic forceReauthentication () { - condition { - true; - } - action { - for (ProxyT lb : M.components) { - M.forceReauthentication (lb); - } - } - effect { - true; - } -} - -tactic addCaptcha () { - condition { - exists lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; - } - action { - set lbs = {select l : D.ZNewsLBT in M.components | !l.captchaEnabled}; - for (D.ZNewsLBT l : lbs) { - M.setCaptchaEnabled (l, true); - } - } - effect { - forall lb:D.ZNewsLBT in M.components | lb.captchaEnabled; - } -} - -tactic removeCaptcha () { - condition { - exists lb:D.ZNewsLBT in M.components | lb.captchaEnabled; - } - action { - set lbs = {select l : D.ZNewsLBT in M.components | l.captchaEnabled}; - for (D.ZNewsLBT l : lbs) { - M.setCaptchaEnabled (l, false); - } - } - effect { - forall lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; - } -} - - +module dos.strategies; + +import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T, ZNewsDosFam as D} ; +import op "org.sa.rainbow.stitch.lib.*"; + +//-------------------------------------------------------------------------------------------------- +// ! exists c : ClientT in self.components | (c.isMalicious and !c.is_blackholed) +// +// Failing this would cause the strategy to fire +// In the long run, isMalicious could be a float that captures the probability +// that a client is malicious -- in this case, we would have a threshold value +// +// Countermeasure #3: Black Hole the attacker(s) +// Blackholing means replying with ICMP giving reason for Black hole the attacking +// client by redirecting connections from a client +// for some period of time (i.e. black hole the traffic). +// +tactic blackholeAttacker () { + condition { + exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.blackholed))); + + // currently just checking if the client is identified as malicious. + // exists c:D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD; + } + action { + // Find the attacker. Currently, this is done by checking if client is identified as an attacker + // the blackHole() routine re-routes all traffic from a client away from the backed servers + // thereby preventing attackers from consuming ZNN resources. + // + set evilClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD}; + set blackholedClients = M.LB0.blackholed; + for (T.ClientT target : evilClients) { + blackholedClients = Set.add (blackholedClients, target.deploymentLocation); + } + M.setBlackholed (M.LB0, blackholedClients); + } + effect { + // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? + // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true + // if the client is blackholed and false otherwise + forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.blackholed))); + //forall c:T.ClientT in M.components | (c.maliciousness > M.MALICIOUS_THRESHOLD) -> !c.isBlackholed)); + } +} + +tactic unblackholeAttacker () { + condition { + exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.blackholed) && c.maliciousness <= M.MALICIOUS_THRESHOLD); + } + action { + set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.MALICIOUS_THRESHOLD}; + set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.blackholed) > 0}; + for (D.ZNewsLBT l : lbs) { + set blackholedClients = l.blackholed; + for (D.ZNewsClientT c : reformedClients) { + // Curiously, if the unblackhole is only in the op.map and + // not in the the EffectOp class, then the parameters need + // to be paired with their parameter name + // Thus, (...,"client", c.deploymentLocation) here + // compared to blackhole above, which is actually + // a method provided in the EffectOp class + blackholedClients = Set.remove (blackholedClients, c.deploymentLocation); + } + M.setBlackholed (l, blackholedClients); + } + } + effect { + forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD)); + } +} + +tactic throttleSuspicious () { + condition { + exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.throttled))); + } + action { + // Find the attacker. Currently, this is done by checking if client is identified as an attacker + // the blackHole() routine re-routes all traffic from a client away from the backed servers + // thereby preventing attackers from consuming ZNN resources. + // + set suspciousClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.SUSCPICIOUS_THRESHOLD}; + set throttledClients = M.LB0.throttled; + for (T.ClientT target : suspciousClients) { + throttledClients = Set.add (throttledClients, target.deploymentLocation); + } + M.setThrottled (M.LB0, throttledClients); + } + effect { + // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? + // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true + // if the client is blackholed and false otherwise + forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.throttled))); + } +} + +tactic unthrottle () { + condition { + exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.throttled) && c.maliciousness <= M.SUSCPICIOUS_THRESHOLD); + } + action { + set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.SUSCPICIOUS_THRESHOLD}; + set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.throttled) > 0}; + for (D.ZNewsLBT l : lbs) { + set throttledClients = l.throttled; + for (D.ZNewsClientT c : reformedClients) { + throttledClients = Set.remove (throttledClients, c.deploymentLocation); + } + M.setThrottled (l, throttledClients); + } + } + effect { + forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSCPICIOUS_THRESHOLD)); + } +} + +tactic forceReauthentication () { + condition { + true; + } + action { + for (ProxyT lb : M.components) { + M.forceReauthentication (lb); + } + } + effect { + true; + } +} + +tactic addCaptcha () { + condition { + exists lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; + } + action { + set lbs = {select l : D.ZNewsLBT in M.components | !l.captchaEnabled}; + for (D.ZNewsLBT l : lbs) { + M.setCaptchaEnabled (l, true); + } + } + effect { + forall lb:D.ZNewsLBT in M.components | lb.captchaEnabled; + } +} + +tactic removeCaptcha () { + condition { + exists lb:D.ZNewsLBT in M.components | lb.captchaEnabled; + } + action { + set lbs = {select l : D.ZNewsLBT in M.components | l.captchaEnabled}; + for (D.ZNewsLBT l : lbs) { + M.setCaptchaEnabled (l, false); + } + } + effect { + forall lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; + } +} + + diff --git a/targets/znews-ss-client/stitch/newssiteTactics.s b/targets/znews-ss-client/stitch/newssiteTactics.s index 891770c68..41d6ad58a 100644 --- a/targets/znews-ss-client/stitch/newssiteTactics.s +++ b/targets/znews-ss-client/stitch/newssiteTactics.s @@ -1,118 +1,118 @@ -module newssite.tactics; - -import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T}; -import op "org.sa.rainbow.stitch.lib.*"; -import op "org.sa.rainbow.model.acme.znn.ZNN"; - - -/** - * Enlist n free servers into service pool. - * Utility: [v] R; [^] C; [<>] F - */ -tactic enlistServers (int n) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // there should be enough available server resources - ZNN.availableServices(M, T.ServerT) >= n; - } - action { - set servers = Set.randomSubset(ZNN.findServices(M, T.ServerT), n); - for (T.ServerT freeSvr : servers) { - M.enableServer (freeSvr, true); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Deactivate n servers from service pool into free pool. - * Utility: [^] R; [v] C; [<>] F - */ -tactic dischargeServers (int n) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there should be enough servers to discharge - Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; - } - action { - set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; - set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); - for (T.ServerT s : subLowUtilSvrs) { - M.enableServer (s, false); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Lowers fidelity by integral steps for percent of requests. - * Utility: [v] R; [v] C; [v] F - */ -tactic lowerFidelity (int step, float fracReq) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // exists server with fidelity to lower - exists s : T.ServerT in M.components | s.fidelity > step; - } - action { - // retrieve set of servers who still have enough fidelity grade to lower - set servers = { select s : T.ServerT in M.components | s.fidelity > step }; - for (T.ServerT s : servers) { - M.setFidelity(s, s.fidelity - step); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Raises fidelity by integral steps for percent of requests. - * Utility: [^] R; [^] C; [^] F - */ -tactic raiseFidelity (int step, float fracReq) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there exists some client with below low-threshold response time - exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - } - action { - // first find the lowest fidelity set - set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; -/* smarter way of doing things... - int lowestFidelity = M.MAX_FIDELITY_LEVEL; - for (T.ServerT s : servers) { - if (s.fidelity < lowestFidelity) { - lowestFidelity = s.fidelity; - } - } - // find only servers with this lowest fidelity setting, and raise fidelity - servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; -*/ - for (T.ServerT s : servers) { - M.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/* - T5) delayClients(set clients) - utility: [^] R; [v] C; [v] F - T6) blockClients(set clients) - utility: [^] R; [v] C; [v] F -*/ +module newssite.tactics; + +import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T}; +import op "org.sa.rainbow.stitch.lib.*"; +import op "org.sa.rainbow.model.acme.znn.ZNN"; + + +/** + * Enlist n free servers into service pool. + * Utility: [v] R; [^] C; [<>] F + */ +tactic enlistServers (int n) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // there should be enough available server resources + ZNN.availableServices(M, T.ServerT) >= n; + } + action { + set servers = Set.randomSubset(ZNN.findServices(M, T.ServerT), n); + for (T.ServerT freeSvr : servers) { + M.enableServer (freeSvr, true); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Deactivate n servers from service pool into free pool. + * Utility: [^] R; [v] C; [<>] F + */ +tactic dischargeServers (int n) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there should be enough servers to discharge + Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; + } + action { + set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; + set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); + for (T.ServerT s : subLowUtilSvrs) { + M.enableServer (s, false); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Lowers fidelity by integral steps for percent of requests. + * Utility: [v] R; [v] C; [v] F + */ +tactic lowerFidelity (int step, float fracReq) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // exists server with fidelity to lower + exists s : T.ServerT in M.components | s.fidelity > step; + } + action { + // retrieve set of servers who still have enough fidelity grade to lower + set servers = { select s : T.ServerT in M.components | s.fidelity > step }; + for (T.ServerT s : servers) { + M.setFidelity(s, s.fidelity - step); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Raises fidelity by integral steps for percent of requests. + * Utility: [^] R; [^] C; [^] F + */ +tactic raiseFidelity (int step, float fracReq) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there exists some client with below low-threshold response time + exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + } + action { + // first find the lowest fidelity set + set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; +/* smarter way of doing things... + int lowestFidelity = M.MAX_FIDELITY_LEVEL; + for (T.ServerT s : servers) { + if (s.fidelity < lowestFidelity) { + lowestFidelity = s.fidelity; + } + } + // find only servers with this lowest fidelity setting, and raise fidelity + servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; +*/ + for (T.ServerT s : servers) { + M.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/* + T5) delayClients(set clients) + utility: [^] R; [v] C; [v] F + T6) blockClients(set clients) + utility: [^] R; [v] C; [v] F +*/ diff --git a/targets/znews-ss-client/stitch/old/newssiteStrategies.s b/targets/znews-ss-client/stitch/old/newssiteStrategies.s index 3eef21719..55f3bf8a9 100644 --- a/targets/znews-ss-client/stitch/old/newssiteStrategies.s +++ b/targets/znews-ss-client/stitch/old/newssiteStrategies.s @@ -1,117 +1,117 @@ -/* - * Adaptation script for the News Site example. - */ - -module newssite.strategies; - -import lib "newssiteTactics.s"; - -define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); -define boolean cViolation = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - -define set servers = {select s : T.ServerT in M.components | true}; -define set unhappyClients = {select c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME}; -define int numClients = Set.size({select c : T.ClientT in M.components | true}); -define int numUnhappy = Set.size(unhappyClients); -define float numUnhappyFloat = 1.0*numUnhappy; - -define boolean hiLoad = exists s : T.ServerT in M.components | s.load > M.MAX_UTIL; -define boolean hiRespTime = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; -define boolean lowRespTime = exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - -define float totalCost = Model.sumOverProperty("cost", servers); -define boolean hiCost = totalCost >= M.THRESHOLD_COST; - -define float avgFidelity = Model.sumOverProperty("fidelity", servers) / Set.size(servers); -define boolean lowFi = avgFidelity < M.THRESHOLD_FIDELITY; - -/* This Strategy is simple in that, while it encounters any anomaly in - * experienced response time, it firsts enlists one new server, then lowers - * fidelity one step, and quits - */ -strategy SimpleReduceResponseTime -[ styleApplies && cViolation ] { - t0: (/*hiLoad*/ cViolation) -> enlistServers(1) @[1000 /*ms*/] { - t1: (!cViolation) -> done; - t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[3000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> TNULL; // in this case, we have no more steps to take - } - } -} - -/* This Strategy is smarter in that it looks for a percentage of clients with - * anomalous experienced response time, in which case it enlists a few servers - * in sequence, then lowers fidelity a few steps, then starts delaying Clients - */ -strategy SmarterReduceResponseTime -[ styleApplies && cViolation ] { - define boolean unhappy = numUnhappyFloat/numClients > M.TOLERABLE_PERCENT_UNHAPPY; - - t0: (unhappy) -> enlistServers(1) @[500 /*ms*/] { - t1: (!cViolation) -> done; - t2: (unhappy) -> enlistServers(1) @[2000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (unhappy) -> lowerFidelity(2, 100) @[2000 /*ms*/] { - t2b1: (!cViolation) -> done; - t2b2: (unhappy) -> do[1] t2; - t2b3: (default) -> TNULL; // in this case, we have no more steps to take - } - } - } -} - -/* This Strategy (experimental!) has the sophistication of reducing fidelity - * for a percentage of requests depending on percentage of unhappy clients - */ -strategy SophisticatedReduceResponseTime -[ styleApplies && cViolation && M.SUPPORT_FRACTION_GRADIENT ] { - define boolean unhappy1 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_1; // e.g., 10% - define boolean unhappy2 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_2; // e.g., 25% - define boolean unhappy3 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_3; // e.g., 50% - - t1: (hiLoad) -> enlistServers(2) @[500 /*ms*/] { - t1a: (!cViolation) -> done; - t1b: (default) -> TNULL; - } - t2: (unhappy1) -> lowerFidelity(1, M.FRACTION_GRADIENT_1) @[500 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> do[1] t1; - } - t3: (unhappy2) -> lowerFidelity(2, M.FRACTION_GRADIENT_2) @[500 /*ms*/] { - t3a: (!cViolation) -> done; - t3b: (default) -> do[1] t1; - } - t4: (unhappy3) -> lowerFidelity(4, M.FRACTION_GRADIENT_3) @[500 /*ms*/] { - t4a: (!cViolation) -> done; - t4b: (unhappy3) -> enlistServers(2) @[1000 /*ms*/] { - t4b1: (!cViolation) -> done; - t4b2: (default) -> do[1] t1; - } - t4c: (default) -> do[1] t1; - } -} - -/* This Strategy is triggered by the total server costs rising above acceptable - * threshold; this Strategy reduces the number of active servers - */ -strategy ReduceOverallCost -[ styleApplies && hiCost ] { - t0: (hiCost) -> dischargeServers(1) @[2000 /*ms*/] { - t1: (!hiCost) -> done; - t2: (lowRespTime && hiCost) -> do[2] t0; - t3: (default) -> TNULL; - } -} - -/* This Strategy is triggered by overall fidelity being below acceptable - * threshold; this Strategy raises the fidelity of the servers - */ -strategy ImproveOverallFidelity -[ styleApplies && lowFi ] { - t0: (lowFi) -> raiseFidelity(2, 100) @[800 /*ms*/] { - t1: (!lowFi) -> done; - t2: (lowRespTime && lowFi) -> do[1] t0; - t3: (default) -> TNULL; - } -} +/* + * Adaptation script for the News Site example. + */ + +module newssite.strategies; + +import lib "newssiteTactics.s"; + +define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); +define boolean cViolation = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + +define set servers = {select s : T.ServerT in M.components | true}; +define set unhappyClients = {select c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME}; +define int numClients = Set.size({select c : T.ClientT in M.components | true}); +define int numUnhappy = Set.size(unhappyClients); +define float numUnhappyFloat = 1.0*numUnhappy; + +define boolean hiLoad = exists s : T.ServerT in M.components | s.load > M.MAX_UTIL; +define boolean hiRespTime = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; +define boolean lowRespTime = exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + +define float totalCost = Model.sumOverProperty("cost", servers); +define boolean hiCost = totalCost >= M.THRESHOLD_COST; + +define float avgFidelity = Model.sumOverProperty("fidelity", servers) / Set.size(servers); +define boolean lowFi = avgFidelity < M.THRESHOLD_FIDELITY; + +/* This Strategy is simple in that, while it encounters any anomaly in + * experienced response time, it firsts enlists one new server, then lowers + * fidelity one step, and quits + */ +strategy SimpleReduceResponseTime +[ styleApplies && cViolation ] { + t0: (/*hiLoad*/ cViolation) -> enlistServers(1) @[1000 /*ms*/] { + t1: (!cViolation) -> done; + t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[3000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> TNULL; // in this case, we have no more steps to take + } + } +} + +/* This Strategy is smarter in that it looks for a percentage of clients with + * anomalous experienced response time, in which case it enlists a few servers + * in sequence, then lowers fidelity a few steps, then starts delaying Clients + */ +strategy SmarterReduceResponseTime +[ styleApplies && cViolation ] { + define boolean unhappy = numUnhappyFloat/numClients > M.TOLERABLE_PERCENT_UNHAPPY; + + t0: (unhappy) -> enlistServers(1) @[500 /*ms*/] { + t1: (!cViolation) -> done; + t2: (unhappy) -> enlistServers(1) @[2000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (unhappy) -> lowerFidelity(2, 100) @[2000 /*ms*/] { + t2b1: (!cViolation) -> done; + t2b2: (unhappy) -> do[1] t2; + t2b3: (default) -> TNULL; // in this case, we have no more steps to take + } + } + } +} + +/* This Strategy (experimental!) has the sophistication of reducing fidelity + * for a percentage of requests depending on percentage of unhappy clients + */ +strategy SophisticatedReduceResponseTime +[ styleApplies && cViolation && M.SUPPORT_FRACTION_GRADIENT ] { + define boolean unhappy1 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_1; // e.g., 10% + define boolean unhappy2 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_2; // e.g., 25% + define boolean unhappy3 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_3; // e.g., 50% + + t1: (hiLoad) -> enlistServers(2) @[500 /*ms*/] { + t1a: (!cViolation) -> done; + t1b: (default) -> TNULL; + } + t2: (unhappy1) -> lowerFidelity(1, M.FRACTION_GRADIENT_1) @[500 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> do[1] t1; + } + t3: (unhappy2) -> lowerFidelity(2, M.FRACTION_GRADIENT_2) @[500 /*ms*/] { + t3a: (!cViolation) -> done; + t3b: (default) -> do[1] t1; + } + t4: (unhappy3) -> lowerFidelity(4, M.FRACTION_GRADIENT_3) @[500 /*ms*/] { + t4a: (!cViolation) -> done; + t4b: (unhappy3) -> enlistServers(2) @[1000 /*ms*/] { + t4b1: (!cViolation) -> done; + t4b2: (default) -> do[1] t1; + } + t4c: (default) -> do[1] t1; + } +} + +/* This Strategy is triggered by the total server costs rising above acceptable + * threshold; this Strategy reduces the number of active servers + */ +strategy ReduceOverallCost +[ styleApplies && hiCost ] { + t0: (hiCost) -> dischargeServers(1) @[2000 /*ms*/] { + t1: (!hiCost) -> done; + t2: (lowRespTime && hiCost) -> do[2] t0; + t3: (default) -> TNULL; + } +} + +/* This Strategy is triggered by overall fidelity being below acceptable + * threshold; this Strategy raises the fidelity of the servers + */ +strategy ImproveOverallFidelity +[ styleApplies && lowFi ] { + t0: (lowFi) -> raiseFidelity(2, 100) @[800 /*ms*/] { + t1: (!lowFi) -> done; + t2: (lowRespTime && lowFi) -> do[1] t0; + t3: (default) -> TNULL; + } +} diff --git a/targets/znews-ss-client/stitch/old/newssiteTactics.s b/targets/znews-ss-client/stitch/old/newssiteTactics.s index a0efdb740..0684601ef 100644 --- a/targets/znews-ss-client/stitch/old/newssiteTactics.s +++ b/targets/znews-ss-client/stitch/old/newssiteTactics.s @@ -1,118 +1,118 @@ -module newssite.tactics; - -import model "ZNewsSys.acme" { ZNewsSys as M, ZNewsFam as T }; -import op "znews1.operator.EffectOp" { EffectOp as S }; -import op "org.sa.rainbow.stitch.lib.*"; - - -/** - * Enlist n free servers into service pool. - * Utility: [v] R; [^] C; [<>] F - */ -tactic enlistServers (int n) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // there should be enough available server resources - Model.availableServices(T.ServerT) >= n; - } - action { - set servers = Set.randomSubset(Model.findServices(T.ServerT), n); - for (T.ServerT freeSvr : servers) { - S.activateServer(freeSvr); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Deactivate n servers from service pool into free pool. - * Utility: [^] R; [v] C; [<>] F - */ -tactic dischargeServers (int n) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there should be enough servers to discharge - Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; - } - action { - set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; - set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); - for (T.ServerT s : subLowUtilSvrs) { - S.deactivateServer(s); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Lowers fidelity by integral steps for percent of requests. - * Utility: [v] R; [v] C; [v] F - */ -tactic lowerFidelity (int step, float fracReq) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // exists server with fidelity to lower - exists s : T.ServerT in M.components | s.fidelity > step; - } - action { - // retrieve set of servers who still have enough fidelity grade to lower - set servers = { select s : T.ServerT in M.components | s.fidelity > step }; - for (T.ServerT s : servers) { - S.setFidelity(s, s.fidelity - step); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Raises fidelity by integral steps for percent of requests. - * Utility: [^] R; [^] C; [^] F - */ -tactic raiseFidelity (int step, float fracReq) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there exists some client with below low-threshold response time - exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - } - action { - // first find the lowest fidelity set - set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; -/* smarter way of doing things... - int lowestFidelity = M.MAX_FIDELITY_LEVEL; - for (T.ServerT s : servers) { - if (s.fidelity < lowestFidelity) { - lowestFidelity = s.fidelity; - } - } - // find only servers with this lowest fidelity setting, and raise fidelity - servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; -*/ - for (T.ServerT s : servers) { - S.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/* - T5) delayClients(set clients) - utility: [^] R; [v] C; [v] F - T6) blockClients(set clients) - utility: [^] R; [v] C; [v] F -*/ +module newssite.tactics; + +import model "ZNewsSys.acme" { ZNewsSys as M, ZNewsFam as T }; +import op "znews1.operator.EffectOp" { EffectOp as S }; +import op "org.sa.rainbow.stitch.lib.*"; + + +/** + * Enlist n free servers into service pool. + * Utility: [v] R; [^] C; [<>] F + */ +tactic enlistServers (int n) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // there should be enough available server resources + Model.availableServices(T.ServerT) >= n; + } + action { + set servers = Set.randomSubset(Model.findServices(T.ServerT), n); + for (T.ServerT freeSvr : servers) { + S.activateServer(freeSvr); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Deactivate n servers from service pool into free pool. + * Utility: [^] R; [v] C; [<>] F + */ +tactic dischargeServers (int n) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there should be enough servers to discharge + Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; + } + action { + set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; + set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); + for (T.ServerT s : subLowUtilSvrs) { + S.deactivateServer(s); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Lowers fidelity by integral steps for percent of requests. + * Utility: [v] R; [v] C; [v] F + */ +tactic lowerFidelity (int step, float fracReq) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // exists server with fidelity to lower + exists s : T.ServerT in M.components | s.fidelity > step; + } + action { + // retrieve set of servers who still have enough fidelity grade to lower + set servers = { select s : T.ServerT in M.components | s.fidelity > step }; + for (T.ServerT s : servers) { + S.setFidelity(s, s.fidelity - step); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Raises fidelity by integral steps for percent of requests. + * Utility: [^] R; [^] C; [^] F + */ +tactic raiseFidelity (int step, float fracReq) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there exists some client with below low-threshold response time + exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + } + action { + // first find the lowest fidelity set + set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; +/* smarter way of doing things... + int lowestFidelity = M.MAX_FIDELITY_LEVEL; + for (T.ServerT s : servers) { + if (s.fidelity < lowestFidelity) { + lowestFidelity = s.fidelity; + } + } + // find only servers with this lowest fidelity setting, and raise fidelity + servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; +*/ + for (T.ServerT s : servers) { + S.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/* + T5) delayClients(set clients) + utility: [^] R; [v] C; [v] F + T6) blockClients(set clients) + utility: [^] R; [v] C; [v] F +*/ diff --git a/targets/znews-ss-client/stitch/utilities.yml b/targets/znews-ss-client/stitch/utilities.yml index 057e48819..b1afa7129 100644 --- a/targets/znews-ss-client/stitch/utilities.yml +++ b/targets/znews-ss-client/stitch/utilities.yml @@ -1,151 +1,151 @@ -# Created October 22nd, 2013 (Javier Camara) -# -# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y -# is the utility in the range [0,1] -# -# History: -# - [JC 2013.10.22] Created file, defined utilities for Dos Attack Demo. -# - [JC 2013.11.1] Added user annoyance to the utility profile. -model: - name: ZNewsSys - type: Acme -utilities: - uR: - label: "Average Response Time" - mapping: "[EAvg]ClientT.experRespTime" - description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" - utility: - 0: 1.00 - 100: 1.00 - 200: 0.99 - 500: 0.90 - 1000: 0.75 - 1500: 0.50 - 2000: 0.25 - 4000: 0.00 - uC: - label: "Average Server Cost" - mapping: "[EXPR]size(/self/components:ServerT[isArchEnabled])" - description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers. Adapted to a 3-server configuration." - utility: - 0: 1.00 - 1: 0.90 - 2: 0.30 - 3: 0.10 - uM: - label: "Malicious Clients" - mapping: "[EXPR](2*size(/self/components:PotentiallyMaliciousT[maliciousness > self.MALICIOUS_THRESHOLD]))/(size(/self/components:PotentiallyMaliciousT)+1)*100" - description: "Percentage of malicious clients." - utility: - 0: 1.00 - 5: 1.00 - 20: 0.80 - 50: 0.40 - 70: 0.00 - uA: - label: "Average User Annoyance" - mapping: "[EAvg]ClientT.annoyance" - description: "Client experienced annoyance level, should be defined as an int property 'ClientT.annoyance' in the architecture, with a range 0-100" - utility: - 0: 1.00 - 100: 0.00 - -# Weighted utility preferences, each set should sum to 1. -# Three scenarios: -# 1.) Priority is given to eliminating malicious clients. -# 2.) Priority is given to optimizing good client experience (both serving them in a timely manner, and minimizing annoyance). -# 3.) Priority is given to keeping cost down. -# Note: Original Weight of uR is now split 50/50% among uR and uA in every scenario. -weights: - scenario 1: - uR: 0.15 - uM: 0.6 - uC: 0.1 - uA: 0.15 - scenario 2: - uR: 0.3 - uM: 0.3 - uC: 0.1 - uA: 0.3 - scenario 3: - uR: 0.2 - uM: 0.2 - uC: 0.4 - uA: 0.2 - -# Tactic quality attribute vectors -# -vectors: -# Utility: [^] R; [<>] M; [v] C; [<>]A -# assume each server will drop response time by 1000 ms and increase cost by 1 unit - enlistServers: - uR: -1000 - uM: 0 - uC: +1.00 - uA: 0 - -# Utility: [^] R; [<>] M; [^] C; [v]A -# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit, increases annoyance of users 5% for low-quality service - lowerFidelity: - uR: -500 - uM: 0 - uC: -0.10 - uA: +5 - -# Utility: [^] R; [^] M; [v] C; [v]A -# assume that adding the captcha reduces response time by 250 ms, reduces level of malicious users by 90%, increases cost 1/2 unit, and increases user annoyance by 50% - addCaptcha: - uR: -250 - uM: -90 - uC: +0.50 - uA: +50 - -# Utility: [^] R; [^] M; [<>] C; [v]A -# assume that forcing users to reauthenticate reduces response time by 250 ms, reduces level of malicious users by 70%, and increases user annoyance by 50% - forceReauthentication: - uR: -250 - uM: -70 - uC: 0.00 - uA: +50 - -# Utility: [^] R; [^] M; [<>] C; [v]A -# assume that blackholing potential attackers reduces response time by 1000 ms, reduces level of malicious users by 100%, and increases user annoyance by 100% - blackholeAttacker: - uR: -1000 - uM: -100 - uC: 0.00 - uA: +50 - -# Utility: [^] R; [<>] M; [<>] C; [v]A -# assume that throttling suspicious clients reduces response time by 500 ms, and increases user annoyance by 50% - throttleSuspicious: - uR: -500 -# uM may need to change if we decide to substitute % of malicious clients by % of malicious user throughput - uM: 0 - uC: 0.00 - uA: +25 - -# Utility: [^] R; [<>] M; [^] C; [^]A -# assume that removing the captcha reduces cost 1/2 unit, and reduces user annoyance by 50% - removeCaptcha: - uR: -500 - uM: 0 - uC: -0.50 - uA: -50 - -# Utility: [<>] R; [<>] M; [<>] C; [^]A -# assume that removing the captcha reduces user annoyance by 100% - unblackholeAttacker: - uR: 0 - uM: 0 - uC: 0.00 - uA: -100 - -# Utility: [<>] R; [<>] M; [<>] C; [^]A -# assume that unthrottling suspicious clients reduces user annoyance by 50% - unthrottle: - uR: 0 - uM: 0 - uC: 0.00 - uA: -50 - +# Created October 22nd, 2013 (Javier Camara) +# +# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y +# is the utility in the range [0,1] +# +# History: +# - [JC 2013.10.22] Created file, defined utilities for Dos Attack Demo. +# - [JC 2013.11.1] Added user annoyance to the utility profile. +model: + name: ZNewsSys + type: Acme +utilities: + uR: + label: "Average Response Time" + mapping: "[EAvg]ClientT.experRespTime" + description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" + utility: + 0: 1.00 + 100: 1.00 + 200: 0.99 + 500: 0.90 + 1000: 0.75 + 1500: 0.50 + 2000: 0.25 + 4000: 0.00 + uC: + label: "Average Server Cost" + mapping: "[EXPR]size(/self/components:ServerT[isArchEnabled])" + description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers. Adapted to a 3-server configuration." + utility: + 0: 1.00 + 1: 0.90 + 2: 0.30 + 3: 0.10 + uM: + label: "Malicious Clients" + mapping: "[EXPR](2*size(/self/components:PotentiallyMaliciousT[maliciousness > self.MALICIOUS_THRESHOLD]))/(size(/self/components:PotentiallyMaliciousT)+1)*100" + description: "Percentage of malicious clients." + utility: + 0: 1.00 + 5: 1.00 + 20: 0.80 + 50: 0.40 + 70: 0.00 + uA: + label: "Average User Annoyance" + mapping: "[EAvg]ClientT.annoyance" + description: "Client experienced annoyance level, should be defined as an int property 'ClientT.annoyance' in the architecture, with a range 0-100" + utility: + 0: 1.00 + 100: 0.00 + +# Weighted utility preferences, each set should sum to 1. +# Three scenarios: +# 1.) Priority is given to eliminating malicious clients. +# 2.) Priority is given to optimizing good client experience (both serving them in a timely manner, and minimizing annoyance). +# 3.) Priority is given to keeping cost down. +# Note: Original Weight of uR is now split 50/50% among uR and uA in every scenario. +weights: + scenario 1: + uR: 0.15 + uM: 0.6 + uC: 0.1 + uA: 0.15 + scenario 2: + uR: 0.3 + uM: 0.3 + uC: 0.1 + uA: 0.3 + scenario 3: + uR: 0.2 + uM: 0.2 + uC: 0.4 + uA: 0.2 + +# Tactic quality attribute vectors +# +vectors: +# Utility: [^] R; [<>] M; [v] C; [<>]A +# assume each server will drop response time by 1000 ms and increase cost by 1 unit + enlistServers: + uR: -1000 + uM: 0 + uC: +1.00 + uA: 0 + +# Utility: [^] R; [<>] M; [^] C; [v]A +# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit, increases annoyance of users 5% for low-quality service + lowerFidelity: + uR: -500 + uM: 0 + uC: -0.10 + uA: +5 + +# Utility: [^] R; [^] M; [v] C; [v]A +# assume that adding the captcha reduces response time by 250 ms, reduces level of malicious users by 90%, increases cost 1/2 unit, and increases user annoyance by 50% + addCaptcha: + uR: -250 + uM: -90 + uC: +0.50 + uA: +50 + +# Utility: [^] R; [^] M; [<>] C; [v]A +# assume that forcing users to reauthenticate reduces response time by 250 ms, reduces level of malicious users by 70%, and increases user annoyance by 50% + forceReauthentication: + uR: -250 + uM: -70 + uC: 0.00 + uA: +50 + +# Utility: [^] R; [^] M; [<>] C; [v]A +# assume that blackholing potential attackers reduces response time by 1000 ms, reduces level of malicious users by 100%, and increases user annoyance by 100% + blackholeAttacker: + uR: -1000 + uM: -100 + uC: 0.00 + uA: +50 + +# Utility: [^] R; [<>] M; [<>] C; [v]A +# assume that throttling suspicious clients reduces response time by 500 ms, and increases user annoyance by 50% + throttleSuspicious: + uR: -500 +# uM may need to change if we decide to substitute % of malicious clients by % of malicious user throughput + uM: 0 + uC: 0.00 + uA: +25 + +# Utility: [^] R; [<>] M; [^] C; [^]A +# assume that removing the captcha reduces cost 1/2 unit, and reduces user annoyance by 50% + removeCaptcha: + uR: -500 + uM: 0 + uC: -0.50 + uA: -50 + +# Utility: [<>] R; [<>] M; [<>] C; [^]A +# assume that removing the captcha reduces user annoyance by 100% + unblackholeAttacker: + uR: 0 + uM: 0 + uC: 0.00 + uA: -100 + +# Utility: [<>] R; [<>] M; [<>] C; [^]A +# assume that unthrottling suspicious clients reduces user annoyance by 50% + unthrottle: + uR: 0 + uM: 0 + uC: 0.00 + uA: -50 + diff --git a/targets/znews-ss-client/system/debpkgs.txt b/targets/znews-ss-client/system/debpkgs.txt index 96003b50f..544fb5fca 100644 --- a/targets/znews-ss-client/system/debpkgs.txt +++ b/targets/znews-ss-client/system/debpkgs.txt @@ -1,19 +1,19 @@ - -Debian packages required: -* sysstat - iostat, vmstat, etc. - -Nice packages: -* bc - calculator (under section "math") -* ganglia-monitor?? - for the Ganglia monitoring framework - -If compiling own Apache HTTPd 2.0.x, PHP, and MySQL... -Things to have in the system in order to compile/build: -- libncurses5 -- gcc/g++ 4.0 (3.3+ should work) -- pkg-config -- make/automake(1.8)/autoconf -- flex (lex generator) -- gettext -- openssl/libssl-dev -- zlib-dev -- libxml2/libxml2-dev + +Debian packages required: +* sysstat - iostat, vmstat, etc. + +Nice packages: +* bc - calculator (under section "math") +* ganglia-monitor?? - for the Ganglia monitoring framework + +If compiling own Apache HTTPd 2.0.x, PHP, and MySQL... +Things to have in the system in order to compile/build: +- libncurses5 +- gcc/g++ 4.0 (3.3+ should work) +- pkg-config +- make/automake(1.8)/autoconf +- flex (lex generator) +- gettext +- openssl/libssl-dev +- zlib-dev +- libxml2/libxml2-dev diff --git a/targets/znews-ss-client/system/effectors.yml b/targets/znews-ss-client/system/effectors.yml index 16cde6d7d..021915722 100644 --- a/targets/znews-ss-client/system/effectors.yml +++ b/targets/znews-ss-client/system/effectors.yml @@ -1,354 +1,354 @@ -# Created January 30, 2007 (Shang-Wen Cheng) -# -# Effector descriptions. -# -# History: -# - [SWC 2007.01.30] Created file, populated ZNews effector descriptions. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# -vars: -# _effectors.commonPath: "${rainbow.path}/system/effectors" -# @ZNN_HOME will be replaced by the rainbow-install script -# _effectors.commonPath: "@ZNN_HOME/effectors" - _effectors.commonPath: "/home/ec2-user/effectors" - - -effector-types: - addNewServerT: - command: connectNewServer($) - type: script - scriptInfo: - path : "${_effectors.commonPath}/create_new_server_instance.sh" - argument: "-l {0} -d ${customize.system.target.db} -w 200 -p /home/ec2-user/addNewServer.out" - - blackholeT: - command: ProxyT.setBlackholed ($) - type: script - scriptInfo: - path:"${effectors.commonPath}/ip-block-mgmt" - argument: "block {0}" - - throttleT: - command: ProxyT.setThrottled ($) - type: script - scriptInfo: - path: "${effectors.commonPath}/ip-throttle-mgmt" - arguments: "throttle {0}" - - flushAuthenticationT: - command: ProxyT.flushAuthentication() - type: script - scriptInfo: - path: "${_effectors.commonPath}/force-reauthentication" - - enableCaptchaT: - command: "ProxyT.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/captcha" - argument: "on /home/znn/captcha.on" - - disableCaptchaT: - command: "ProxyT.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/captcha" - argument: "off /home/znn/captcha.on" - - setFidelityT: - command: "ProxyT.setFidelity($)" - arguments: - web-port : int - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-$" - - enable-serverT: - command: "enableServer ($, true)" - arguments: - web-port : int - type: script - scriptInfo: - path : "${_effectors.commonPath}/enable-server" - argument : "on {0}:$" - - disable-serverT: - command: "enableServer ($, false)" - arguments: - web-port : int - type: script - scriptInfo: - path: "${_effectors.commonPath}/enable-server" - argument: "off {0}:$" - - -effectors: - - addNewServer: - effector-type: addNewServerT - location: "${customize.system.target.master}" - - blackhole: - location: "${customize.system.target.lb}" - command: setBlackholed ($) - type: script - scriptInfo: - path : "${_effectors.commonPath}/ip-block-mgmt" - argument: "block {0}" - - throttle: - location: "${customize.system.target.lb}" - command: setThrottled($) - type: script - scriptInfo: - path: "${_effectors.commonPath}/ip-throttle-mgmt" - argument: "throttle {0}" - - flushAuthentication-web0: - location: "${cusomize.system.target.web0}" - command: "${customize.system.target.lb}.forceReauthentication()" - type: script - scriptInfo: - path: "${_effectors.commonPath}/force-reauthentication" - - flushAuthentication-web1: - location: "${cusomize.system.target.web1}" - command: "${customize.system.target.lb}.forceReauthentication()" - type: script - scriptInfo: - path: "${_effectors.commonPath}/force-reauthentication" - - flushAuthentication-web2: - location: "${cusomize.system.target.web2}" - command: "${customize.system.target.lb}.forceReauthentication()" - type: script - scriptInfo: - path: "${_effectors.commonPath}/force-reauthentication" - - enableCaptcha-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-lb: - location: "${customize.system.target.lb}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-web2: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/captcha" - argument: "on /home/znn/captcha.on" - - disableCaptcha-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-lb: - location: "${customize.system.target.lb}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-web2: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/captcha" - argument: "off /home/znn/captcha.on" - - setFidelity-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web0.httpPort}" - - setFidelity-web1: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web1.httpPort}" - - setFidelity-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web2.httpPort}" - - enable-server-web0: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web0}, true)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/enable-server" - argument : "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - disable-server-web0: - location: "${customize.system.target.lb}" - command: "LB0.enableServer (${customize.system.target.web0}, false)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/enable-server" - argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - enable-server-web1: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web1}, true)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/enable-server" - argument : "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - disable-server-web1: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web1}, false)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/enable-server" - argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - enable-server-web2: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web2}, true)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/enable-server" - argument : "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - disable-server-web2: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web2}, false)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/enable-server" - argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - delete-server-web0: - location: "${customize.system.target.lb}" - command: "${customize.system.target.web0}.deleteServer ()" - type: script - scriptInfo: - path: "${_effectors.commonPath}/enable-server" - argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - add-server-web0: - location: "${customize.system.target.lb}" - command: "LB0.connectServer (${customize.system.target.web0})" - type: script - scriptInfo: - path: "${_effectors.commonPath}/enable-server" - argument: "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - delete-server-web1: - location: "${customize.system.target.lb}" - command: "${customize.system.target.web1}.deleteServer ()" - type: script - scriptInfo: - path: "${_effectors.commonPath}/enable-server" - argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - add-server-web1: - location: "${customize.system.target.lb}" - command: "LB0.connectServer (${customize.system.target.web1})" - type: script - scriptInfo: - path: "${_effectors.commonPath}/enable-server" - argument: "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - delete-server-web2: - location: "${customize.system.target.lb}" - command: "${customize.system.target.web2}.deleteServer ()" - type: script - scriptInfo: - path: "${_effectors.commonPath}/enable-server" - argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - add-server-web2: - location: "${customize.system.target.lb}" - command: "LB0.connectServer (${customize.system.target.web2})" - type: script - scriptInfo: - path: "${_effectors.commonPath}/enable-server" - argument: "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - -unused-effectors: - unblackhole: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path: "${_effectors.commonPath}/ip-block-mgmt" - argument: "unblock {clients}" - killDelegate2: -# Causes the designated RainbowDelegate to exit process -# Illustrates effector time-out as well as tests executor execution - location: "${customize.system.target.3}" - type: java - javaInfo: - class : org.sa.rainbow.translator.effectors.KillDelegateEffector - - # test from GUI with , SetFidelity, fidelity=<1|3|5> - - - activateServer1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/turnServer.pl" - argument: "-s on" - deactivateServer1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/turnServer.pl" - argument: "-s off" -# test from GUI with , RandomReject, frequency=<0..?> - randomReject1: - location: "${customize.system.target.2}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/setRandomReject.pl" - argument: "-r {frequency}" - killDelegate1: - location: "${customize.system.target.2}" - type: java - javaInfo: - class : org.sa.rainbow.translator.effectors.KillDelegateEffector +# Created January 30, 2007 (Shang-Wen Cheng) +# +# Effector descriptions. +# +# History: +# - [SWC 2007.01.30] Created file, populated ZNews effector descriptions. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# +vars: +# _effectors.commonPath: "${rainbow.path}/system/effectors" +# @ZNN_HOME will be replaced by the rainbow-install script +# _effectors.commonPath: "@ZNN_HOME/effectors" + _effectors.commonPath: "/home/ec2-user/effectors" + + +effector-types: + addNewServerT: + command: connectNewServer($) + type: script + scriptInfo: + path : "${_effectors.commonPath}/create_new_server_instance.sh" + argument: "-l {0} -d ${customize.system.target.db} -w 200 -p /home/ec2-user/addNewServer.out" + + blackholeT: + command: ProxyT.setBlackholed ($) + type: script + scriptInfo: + path:"${effectors.commonPath}/ip-block-mgmt" + argument: "block {0}" + + throttleT: + command: ProxyT.setThrottled ($) + type: script + scriptInfo: + path: "${effectors.commonPath}/ip-throttle-mgmt" + arguments: "throttle {0}" + + flushAuthenticationT: + command: ProxyT.flushAuthentication() + type: script + scriptInfo: + path: "${_effectors.commonPath}/force-reauthentication" + + enableCaptchaT: + command: "ProxyT.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/captcha" + argument: "on /home/znn/captcha.on" + + disableCaptchaT: + command: "ProxyT.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/captcha" + argument: "off /home/znn/captcha.on" + + setFidelityT: + command: "ProxyT.setFidelity($)" + arguments: + web-port : int + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-$" + + enable-serverT: + command: "enableServer ($, true)" + arguments: + web-port : int + type: script + scriptInfo: + path : "${_effectors.commonPath}/enable-server" + argument : "on {0}:$" + + disable-serverT: + command: "enableServer ($, false)" + arguments: + web-port : int + type: script + scriptInfo: + path: "${_effectors.commonPath}/enable-server" + argument: "off {0}:$" + + +effectors: + + addNewServer: + effector-type: addNewServerT + location: "${customize.system.target.master}" + + blackhole: + location: "${customize.system.target.lb}" + command: setBlackholed ($) + type: script + scriptInfo: + path : "${_effectors.commonPath}/ip-block-mgmt" + argument: "block {0}" + + throttle: + location: "${customize.system.target.lb}" + command: setThrottled($) + type: script + scriptInfo: + path: "${_effectors.commonPath}/ip-throttle-mgmt" + argument: "throttle {0}" + + flushAuthentication-web0: + location: "${cusomize.system.target.web0}" + command: "${customize.system.target.lb}.forceReauthentication()" + type: script + scriptInfo: + path: "${_effectors.commonPath}/force-reauthentication" + + flushAuthentication-web1: + location: "${cusomize.system.target.web1}" + command: "${customize.system.target.lb}.forceReauthentication()" + type: script + scriptInfo: + path: "${_effectors.commonPath}/force-reauthentication" + + flushAuthentication-web2: + location: "${cusomize.system.target.web2}" + command: "${customize.system.target.lb}.forceReauthentication()" + type: script + scriptInfo: + path: "${_effectors.commonPath}/force-reauthentication" + + enableCaptcha-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-lb: + location: "${customize.system.target.lb}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-web2: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/captcha" + argument: "on /home/znn/captcha.on" + + disableCaptcha-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-lb: + location: "${customize.system.target.lb}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-web2: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/captcha" + argument: "off /home/znn/captcha.on" + + setFidelity-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web0.httpPort}" + + setFidelity-web1: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web1.httpPort}" + + setFidelity-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web2.httpPort}" + + enable-server-web0: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web0}, true)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/enable-server" + argument : "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + disable-server-web0: + location: "${customize.system.target.lb}" + command: "LB0.enableServer (${customize.system.target.web0}, false)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/enable-server" + argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + enable-server-web1: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web1}, true)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/enable-server" + argument : "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + disable-server-web1: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web1}, false)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/enable-server" + argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + enable-server-web2: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web2}, true)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/enable-server" + argument : "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + disable-server-web2: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web2}, false)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/enable-server" + argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + delete-server-web0: + location: "${customize.system.target.lb}" + command: "${customize.system.target.web0}.deleteServer ()" + type: script + scriptInfo: + path: "${_effectors.commonPath}/enable-server" + argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + add-server-web0: + location: "${customize.system.target.lb}" + command: "LB0.connectServer (${customize.system.target.web0})" + type: script + scriptInfo: + path: "${_effectors.commonPath}/enable-server" + argument: "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + delete-server-web1: + location: "${customize.system.target.lb}" + command: "${customize.system.target.web1}.deleteServer ()" + type: script + scriptInfo: + path: "${_effectors.commonPath}/enable-server" + argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + add-server-web1: + location: "${customize.system.target.lb}" + command: "LB0.connectServer (${customize.system.target.web1})" + type: script + scriptInfo: + path: "${_effectors.commonPath}/enable-server" + argument: "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + delete-server-web2: + location: "${customize.system.target.lb}" + command: "${customize.system.target.web2}.deleteServer ()" + type: script + scriptInfo: + path: "${_effectors.commonPath}/enable-server" + argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + add-server-web2: + location: "${customize.system.target.lb}" + command: "LB0.connectServer (${customize.system.target.web2})" + type: script + scriptInfo: + path: "${_effectors.commonPath}/enable-server" + argument: "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + +unused-effectors: + unblackhole: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path: "${_effectors.commonPath}/ip-block-mgmt" + argument: "unblock {clients}" + killDelegate2: +# Causes the designated RainbowDelegate to exit process +# Illustrates effector time-out as well as tests executor execution + location: "${customize.system.target.3}" + type: java + javaInfo: + class : org.sa.rainbow.translator.effectors.KillDelegateEffector + + # test from GUI with , SetFidelity, fidelity=<1|3|5> + + + activateServer1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/turnServer.pl" + argument: "-s on" + deactivateServer1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/turnServer.pl" + argument: "-s off" +# test from GUI with , RandomReject, frequency=<0..?> + randomReject1: + location: "${customize.system.target.2}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/setRandomReject.pl" + argument: "-r {frequency}" + killDelegate1: + location: "${customize.system.target.2}" + type: java + javaInfo: + class : org.sa.rainbow.translator.effectors.KillDelegateEffector diff --git a/targets/znews-ss-client/system/effectors/changeFidelity.pl b/targets/znews-ss-client/system/effectors/changeFidelity.pl index a24df7cef..80123eba4 100644 --- a/targets/znews-ss-client/system/effectors/changeFidelity.pl +++ b/targets/znews-ss-client/system/effectors/changeFidelity.pl @@ -1,83 +1,83 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -my $isCygwin = 0; -my $uname; -if ( -e "/bin/uname" ) { - $uname = `/bin/uname`; -} elsif ( -e "/usr/bin/uname" ) { - $uname = `/usr/bin/uname`; -} else { - $uname = "UNKNOWN"; -} -if ($uname =~ /CYGWIN/i) { - $isCygwin = 1; -} - -chomp(my $SCRIPT_DIR = `/usr/bin/dirname "$0"`); -my $APACHE_CONF_DIR = ($isCygwin) ? - "/cygdrive/c/server/Apache2/conf" : - "/etc/apache2"; -my $APACHE_CONF_FILE = ($isCygwin) ? - "httpd.conf" : - "apache2.conf"; -my $APACHE_SITE_DIR = "$APACHE_CONF_DIR/sites-available"; -my $APACHE_SITE_FILE = "z.com"; -my $SOURCE_CONF_DIR = ($isCygwin) ? - "$SCRIPT_DIR/fidelity.conf/cygwin" : - "$SCRIPT_DIR/fidelity.conf/oracle"; - -sub usage() { - print STDERR << "EOF"; - -This effector program changes the webserver fidelity level (1,3,5). - - usage: $0 [option] -l level - - -h : this (help) message - -l level : the new fidelity setting, should be 1, 3, or 5 (0 for original) - -EOF - exit; -} - -# get options -my %opts; -getopts('hl:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{l})); - -my $level = $opts{l}; -usage() if ($level != 0 && $level != 1 && $level != 3 && $level != 5); - -my $fExt = "-f"; -if ($level == 0) { - if ($isCygwin) { - $fExt = ".default"; - } else { - $fExt .= "5"; - } -} else { - $fExt .= $level; -} - -if ($isCygwin) { - - print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; - print `/usr/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; - print "\nGracefully restarting Apache..."; - print `/cygdrive/c/server/Apache2/bin/Apache.exe -w -n "Apache2" -k restart`; - print "\nDone."; - -} else { - - print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; - print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; - print "\nSwapping site to level $level..."; - print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_SITE_FILE$fExt $APACHE_SITE_DIR/$APACHE_SITE_FILE`; - print "\nGracefully restarting Apache..."; - print `/etc/init.d/apache2 reload`; - print "\nDone."; - -} +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +my $isCygwin = 0; +my $uname; +if ( -e "/bin/uname" ) { + $uname = `/bin/uname`; +} elsif ( -e "/usr/bin/uname" ) { + $uname = `/usr/bin/uname`; +} else { + $uname = "UNKNOWN"; +} +if ($uname =~ /CYGWIN/i) { + $isCygwin = 1; +} + +chomp(my $SCRIPT_DIR = `/usr/bin/dirname "$0"`); +my $APACHE_CONF_DIR = ($isCygwin) ? + "/cygdrive/c/server/Apache2/conf" : + "/etc/apache2"; +my $APACHE_CONF_FILE = ($isCygwin) ? + "httpd.conf" : + "apache2.conf"; +my $APACHE_SITE_DIR = "$APACHE_CONF_DIR/sites-available"; +my $APACHE_SITE_FILE = "z.com"; +my $SOURCE_CONF_DIR = ($isCygwin) ? + "$SCRIPT_DIR/fidelity.conf/cygwin" : + "$SCRIPT_DIR/fidelity.conf/oracle"; + +sub usage() { + print STDERR << "EOF"; + +This effector program changes the webserver fidelity level (1,3,5). + + usage: $0 [option] -l level + + -h : this (help) message + -l level : the new fidelity setting, should be 1, 3, or 5 (0 for original) + +EOF + exit; +} + +# get options +my %opts; +getopts('hl:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{l})); + +my $level = $opts{l}; +usage() if ($level != 0 && $level != 1 && $level != 3 && $level != 5); + +my $fExt = "-f"; +if ($level == 0) { + if ($isCygwin) { + $fExt = ".default"; + } else { + $fExt .= "5"; + } +} else { + $fExt .= $level; +} + +if ($isCygwin) { + + print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; + print `/usr/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; + print "\nGracefully restarting Apache..."; + print `/cygdrive/c/server/Apache2/bin/Apache.exe -w -n "Apache2" -k restart`; + print "\nDone."; + +} else { + + print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; + print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; + print "\nSwapping site to level $level..."; + print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_SITE_FILE$fExt $APACHE_SITE_DIR/$APACHE_SITE_FILE`; + print "\nGracefully restarting Apache..."; + print `/etc/init.d/apache2 reload`; + print "\nDone."; + +} diff --git a/targets/znews-ss-client/system/effectors/dummyBlackhole.pl b/targets/znews-ss-client/system/effectors/dummyBlackhole.pl index 0a9e46e42..81ed3be30 100644 --- a/targets/znews-ss-client/system/effectors/dummyBlackhole.pl +++ b/targets/znews-ss-client/system/effectors/dummyBlackhole.pl @@ -1,24 +1,24 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -sub usage () { - print STDERR << "EOF"; - -This effector program is a dummy blackholer. - - usege: $0 [option] -i IP - - -i IP: the IP address that should be blackholed - -EOF - exit; -} - -#get options -my %opts; -getopts ('i:',\%opts) or usage (); -usage () if (!defined($opts{i})); -my $IP = $opts{i} -print "Blackholing $IP...\n"; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +sub usage () { + print STDERR << "EOF"; + +This effector program is a dummy blackholer. + + usege: $0 [option] -i IP + + -i IP: the IP address that should be blackholed + +EOF + exit; +} + +#get options +my %opts; +getopts ('i:',\%opts) or usage (); +usage () if (!defined($opts{i})); +my $IP = $opts{i} +print "Blackholing $IP...\n"; diff --git a/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf b/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf index 4adbba299..5b13550db 100644 --- a/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf +++ b/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf @@ -1,967 +1,967 @@ -### Fidelity-5 Conf file -## - full featured -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -AddType application/x-httpd-php .php - -# configure the path to php.ini -PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.php index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -AddType text/html .shtml -AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-5 Conf file +## - full featured +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +AddType application/x-httpd-php .php + +# configure the path to php.ini +PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.php index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +AddType text/html .shtml +AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 b/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 index 95dd86268..6907bc89d 100644 --- a/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 +++ b/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 @@ -1,974 +1,974 @@ -### Fidelity-1 Conf file -## - reduced timeout from 300 to 30 sec -## - reduced max keep alive reqs from 100 to 10 -## - threads per child reduced from 250 to 10 -## - set an upper limit of max requests per child to 5 -## - excluded user dir function -## - excluded modules dav, imap, rewrite, userdir -## - reduced Directory Options to indexes & symlink only -## - reduced AllowOverride to None -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 30 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 10 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 10 -MaxRequestsPerChild 5 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -#LoadModule cgi_module modules/mod_cgi.so -#LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -#LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -#LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -#LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -#AddType application/x-httpd-php .php - -# configure the path to php.ini -#PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www1" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options Indexes SymLinksIfOwnerMatch - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride None - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -#UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - -# -# Options Indexes -# AllowOverride None -# Order allow,deny -# Allow from all -# -# -# SetHandler type-map -# -# -# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 -# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 -# - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# -# -# AllowOverride None -# Options None -# Order allow,deny -# Allow from all -# - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -#AddType application/x-compress .Z -#AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# -# -# Include conf/ssl.conf -# - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-1 Conf file +## - reduced timeout from 300 to 30 sec +## - reduced max keep alive reqs from 100 to 10 +## - threads per child reduced from 250 to 10 +## - set an upper limit of max requests per child to 5 +## - excluded user dir function +## - excluded modules dav, imap, rewrite, userdir +## - reduced Directory Options to indexes & symlink only +## - reduced AllowOverride to None +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 30 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 10 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 10 +MaxRequestsPerChild 5 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule cgi_module modules/mod_cgi.so +#LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +#LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +#LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +#LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +#AddType application/x-httpd-php .php + +# configure the path to php.ini +#PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www1" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options Indexes SymLinksIfOwnerMatch + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride None + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +#UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + +# +# Options Indexes +# AllowOverride None +# Order allow,deny +# Allow from all +# +# +# SetHandler type-map +# +# +# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 +# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 +# + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +# +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +# + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +#AddType application/x-compress .Z +#AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# +# +# Include conf/ssl.conf +# + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 b/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 index 7fd0f402b..eaab99348 100644 --- a/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 +++ b/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 @@ -1,971 +1,971 @@ -### Fidelity-3 Conf file -## - excluded CGI handling -## - excluded PHP module -## - excluded SSI -## - excluded compression type -## - excluded server manual -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -#LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -#AddType application/x-httpd-php .php - -# configure the path to php.ini -#PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www3" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - -# -# Options Indexes -# AllowOverride None -# Order allow,deny -# Allow from all -# -# -# SetHandler type-map -# -# -# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 -# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 -# - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# -# -# AllowOverride None -# Options None -# Order allow,deny -# Allow from all -# - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -#AddType application/x-compress .Z -#AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-3 Conf file +## - excluded CGI handling +## - excluded PHP module +## - excluded SSI +## - excluded compression type +## - excluded server manual +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +#AddType application/x-httpd-php .php + +# configure the path to php.ini +#PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www3" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + +# +# Options Indexes +# AllowOverride None +# Order allow,deny +# Allow from all +# +# +# SetHandler type-map +# +# +# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 +# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 +# + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +# +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +# + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +#AddType application/x-compress .Z +#AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 b/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 index 4adbba299..5b13550db 100644 --- a/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 +++ b/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 @@ -1,967 +1,967 @@ -### Fidelity-5 Conf file -## - full featured -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -AddType application/x-httpd-php .php - -# configure the path to php.ini -PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.php index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -AddType text/html .shtml -AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-5 Conf file +## - full featured +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +AddType application/x-httpd-php .php + +# configure the path to php.ini +PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.php index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +AddType text/html .shtml +AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf.default b/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf.default index 20dd3c11d..ff8505b79 100644 --- a/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf.default +++ b/targets/znews-ss-client/system/effectors/fidelity.conf/cygwin/httpd.conf.default @@ -1,952 +1,952 @@ -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -#LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -#LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin admin@able.cs.cmu.edu - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/Apache2/htdocs" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options Indexes FollowSymLinks - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride None - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +#LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +#LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin admin@able.cs.cmu.edu + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/Apache2/htdocs" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options Indexes FollowSymLinks + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride None + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# diff --git a/targets/znews-ss-client/system/effectors/setRandomReject.pl b/targets/znews-ss-client/system/effectors/setRandomReject.pl index 5d6b91697..58f70c7b0 100644 --- a/targets/znews-ss-client/system/effectors/setRandomReject.pl +++ b/targets/znews-ss-client/system/effectors/setRandomReject.pl @@ -1,35 +1,35 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -my $APACHE_WWW_DIR = "/home/owen/project/rainbow/delegate/targets/znews1-d/system/webpages/www5"; - -sub usage() { - print STDERR << "EOF"; - -This effector program affects random reject frequency (0 or mod over seconds). - - usage: $0 [option] -r [0|modval] - - -h : this (help) message - -r 0|mod : the modulus value for request rejection (0 for NO reject) - -EOF - exit; -} - -# get options -my %opts; -getopts('hr:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{r})); - -my $modVal = $opts{r}; -usage() if ($modVal < 0 && $modVal > 10); - -my $file = "reject.mod"; -print "Setting reject modulus value to $modVal..."; -open(FOUT, ">$APACHE_WWW_DIR/$file"); -print FOUT $modVal; -close(FOUT); -print "\nDone."; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +my $APACHE_WWW_DIR = "/home/owen/project/rainbow/delegate/targets/znews1-d/system/webpages/www5"; + +sub usage() { + print STDERR << "EOF"; + +This effector program affects random reject frequency (0 or mod over seconds). + + usage: $0 [option] -r [0|modval] + + -h : this (help) message + -r 0|mod : the modulus value for request rejection (0 for NO reject) + +EOF + exit; +} + +# get options +my %opts; +getopts('hr:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{r})); + +my $modVal = $opts{r}; +usage() if ($modVal < 0 && $modVal > 10); + +my $file = "reject.mod"; +print "Setting reject modulus value to $modVal..."; +open(FOUT, ">$APACHE_WWW_DIR/$file"); +print FOUT $modVal; +close(FOUT); +print "\nDone."; diff --git a/targets/znews-ss-client/system/effectors/turnServer.pl b/targets/znews-ss-client/system/effectors/turnServer.pl index 8cc10dd33..9d46f681e 100644 --- a/targets/znews-ss-client/system/effectors/turnServer.pl +++ b/targets/znews-ss-client/system/effectors/turnServer.pl @@ -1,36 +1,36 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; -use IO::Handle; - -sub usage() { - print STDERR << "EOF"; - -This effector program turns the webserver on or off - - usage: $0 [option] -s on|off - - -h : this (help) message - -s on|off : on or off to start/stop webserver - -EOF - exit; -} - -# get options -my %opts; -getopts('hs:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{s})); - -my $switch = $opts{s}; -usage() if ($switch ne "on" && $switch ne "off"); - -if ($switch eq "on") { - print "\nStarting Apache..."; - print `/etc/init.d/apache2 start`; -} else { - print "\nStopping Apache..."; - print `/etc/init.d/apache2 stop`; -} -print "\nDone."; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; +use IO::Handle; + +sub usage() { + print STDERR << "EOF"; + +This effector program turns the webserver on or off + + usage: $0 [option] -s on|off + + -h : this (help) message + -s on|off : on or off to start/stop webserver + +EOF + exit; +} + +# get options +my %opts; +getopts('hs:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{s})); + +my $switch = $opts{s}; +usage() if ($switch ne "on" && $switch ne "off"); + +if ($switch eq "on") { + print "\nStarting Apache..."; + print `/etc/init.d/apache2 start`; +} else { + print "\nStopping Apache..."; + print `/etc/init.d/apache2 stop`; +} +print "\nDone."; diff --git a/targets/znews-ss-client/system/probes.yml b/targets/znews-ss-client/system/probes.yml index e89381f4d..41fdf800b 100644 --- a/targets/znews-ss-client/system/probes.yml +++ b/targets/znews-ss-client/system/probes.yml @@ -1,36 +1,36 @@ -# -# Probe descriptions. -# -# History: -# - [SWC 2007.03.18] Created file, populated new probe descriptions. -# - [SWC 2007.04.09] Added array of host names as arguments to PingRTTProbe. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# - [SWC 2007.04.11] Added ClientProxyProbe -# -vars: -# _probes.commonPath: "${rainbow.path}/system/probes" - _probes.znn_home:"/home/ec2-user" - _probes.commonPath: "${_probes.znn_home}/rainbow/org.sa.rainbow.sdk.znews/targets/znews-ss/system/probes/" - -probes: - -# ClientProbe: -# alias: client -# location: "${customize.system.target.lb}" -# type: java -# javaInfo: -# class: org.sa.rainbow.translator.znn.probes.ClientProbe -# period: 2000 -# args.length: 1 -# args.0: ${_probes.znn_home}/sw-bin/httpd-lb-2.4.2/logs/access_log - - ClientProbe: - alias: client - location: "${customize.system.target.lb}" - type: script - scriptInfo: - mode: continual - path: "/usr/bin/tail" - argument: "-f -s 5 ${_probes.znn_home}/sw-bin/httpd-lb-2.4.2/logs/access_log" - - +# +# Probe descriptions. +# +# History: +# - [SWC 2007.03.18] Created file, populated new probe descriptions. +# - [SWC 2007.04.09] Added array of host names as arguments to PingRTTProbe. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# - [SWC 2007.04.11] Added ClientProxyProbe +# +vars: +# _probes.commonPath: "${rainbow.path}/system/probes" + _probes.znn_home:"/home/ec2-user" + _probes.commonPath: "${_probes.znn_home}/rainbow/org.sa.rainbow.sdk.znews/targets/znews-ss/system/probes/" + +probes: + +# ClientProbe: +# alias: client +# location: "${customize.system.target.lb}" +# type: java +# javaInfo: +# class: org.sa.rainbow.translator.znn.probes.ClientProbe +# period: 2000 +# args.length: 1 +# args.0: ${_probes.znn_home}/sw-bin/httpd-lb-2.4.2/logs/access_log + + ClientProbe: + alias: client + location: "${customize.system.target.lb}" + type: script + scriptInfo: + mode: continual + path: "/usr/bin/tail" + argument: "-f -s 5 ${_probes.znn_home}/sw-bin/httpd-lb-2.4.2/logs/access_log" + + diff --git a/targets/znews-ss-client/system/probes/apachetopProbe.pl b/targets/znews-ss-client/system/probes/apachetopProbe.pl index 79ba71042..9f8989f04 100644 --- a/targets/znews-ss-client/system/probes/apachetopProbe.pl +++ b/targets/znews-ss-client/system/probes/apachetopProbe.pl @@ -1,90 +1,90 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 5000; # 5 sec delay -my $APACHETOP_LOG = "../../log/apachetop.log"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -if (! -e $APACHETOP_LOG) { # create empty file - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line,$sendBeacon); -while (!shouldTerminate($sock)) { - $sendBeacon = 1; - while ($line = ) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - $sendBeacon = 0; - } - if ($sendBeacon) { # announce something to be alive - announce($ALIAS, "\n", [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 5000; # 5 sec delay +my $APACHETOP_LOG = "../../log/apachetop.log"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +if (! -e $APACHETOP_LOG) { # create empty file + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line,$sendBeacon); +while (!shouldTerminate($sock)) { + $sendBeacon = 1; + while ($line = ) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + $sendBeacon = 0; + } + if ($sendBeacon) { # announce something to be alive + announce($ALIAS, "\n", [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-client/system/probes/cygwin/apachetopProbe-single.pl b/targets/znews-ss-client/system/probes/cygwin/apachetopProbe-single.pl index 966358241..762a0686a 100644 --- a/targets/znews-ss-client/system/probes/cygwin/apachetopProbe-single.pl +++ b/targets/znews-ss-client/system/probes/cygwin/apachetopProbe-single.pl @@ -1,98 +1,98 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 10; -my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; -my $APACHETOP_LOG = "apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# fork to the apachetop program -my $pid = fork(); -if ($pid == 0) { ### child process - if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); - } - exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; - exit(0); -} - -### parent process - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line); -while (!shouldTerminate($sock)) { - $line = ; - if (defined($line)) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 10; +my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; +my $APACHETOP_LOG = "apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# fork to the apachetop program +my $pid = fork(); +if ($pid == 0) { ### child process + if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); + } + exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; + exit(0); +} + +### parent process + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line); +while (!shouldTerminate($sock)) { + $line = ; + if (defined($line)) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-client/system/probes/cygwin/apachetopProbe.pl b/targets/znews-ss-client/system/probes/cygwin/apachetopProbe.pl index 79ba71042..9f8989f04 100644 --- a/targets/znews-ss-client/system/probes/cygwin/apachetopProbe.pl +++ b/targets/znews-ss-client/system/probes/cygwin/apachetopProbe.pl @@ -1,90 +1,90 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 5000; # 5 sec delay -my $APACHETOP_LOG = "../../log/apachetop.log"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -if (! -e $APACHETOP_LOG) { # create empty file - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line,$sendBeacon); -while (!shouldTerminate($sock)) { - $sendBeacon = 1; - while ($line = ) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - $sendBeacon = 0; - } - if ($sendBeacon) { # announce something to be alive - announce($ALIAS, "\n", [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 5000; # 5 sec delay +my $APACHETOP_LOG = "../../log/apachetop.log"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +if (! -e $APACHETOP_LOG) { # create empty file + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line,$sendBeacon); +while (!shouldTerminate($sock)) { + $sendBeacon = 1; + while ($line = ) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + $sendBeacon = 0; + } + if ($sendBeacon) { # announce something to be alive + announce($ALIAS, "\n", [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-client/system/probes/cygwin/fidelityProbe.pl b/targets/znews-ss-client/system/probes/cygwin/fidelityProbe.pl index 21dc6255d..abb411a4d 100644 --- a/targets/znews-ss-client/system/probes/cygwin/fidelityProbe.pl +++ b/targets/znews-ss-client/system/probes/cygwin/fidelityProbe.pl @@ -1,100 +1,100 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "fidelity"; -my $NAME = "FidelityProbe"; -my $DELAY = 1000; -my $REPEATEVERY = 5; -my $APACHE_CONF_DIR = "/cygdrive/c/server/Apache2/conf"; -my $APACHE_CONF_FILE = "httpd.conf"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current server fidelity (1,3,5) to Probe Relay file/socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic server fidelity info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub determineFidelity () { - my $fid = 0; - - open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); - my $firstLine = ; # read the first line - if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { - $fid = $1; - } - close(FIN); - - return $fid; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -my $repeatCnt = $REPEATEVERY; -my $savedFidelity = 0; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # compute new fidelity status - my $fidelity = determineFidelity(); - if ($fidelity != $savedFidelity || $repeatCnt == 0) { - $savedFidelity = $fidelity; #store new fidelity - my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - - if ($repeatCnt == 0) { - $repeatCnt = $REPEATEVERY; - } - } else { - $repeatCnt--; - } -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "fidelity"; +my $NAME = "FidelityProbe"; +my $DELAY = 1000; +my $REPEATEVERY = 5; +my $APACHE_CONF_DIR = "/cygdrive/c/server/Apache2/conf"; +my $APACHE_CONF_FILE = "httpd.conf"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current server fidelity (1,3,5) to Probe Relay file/socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic server fidelity info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub determineFidelity () { + my $fid = 0; + + open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); + my $firstLine = ; # read the first line + if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { + $fid = $1; + } + close(FIN); + + return $fid; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +my $repeatCnt = $REPEATEVERY; +my $savedFidelity = 0; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # compute new fidelity status + my $fidelity = determineFidelity(); + if ($fidelity != $savedFidelity || $repeatCnt == 0) { + $savedFidelity = $fidelity; #store new fidelity + my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + + if ($repeatCnt == 0) { + $repeatCnt = $REPEATEVERY; + } + } else { + $repeatCnt--; + } +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-client/system/probes/cygwin/loadProbe.pl b/targets/znews-ss-client/system/probes/cygwin/loadProbe.pl index b50e32b17..0ff60debb 100644 --- a/targets/znews-ss-client/system/probes/cygwin/loadProbe.pl +++ b/targets/znews-ss-client/system/probes/cygwin/loadProbe.pl @@ -1,98 +1,98 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "load"; -my $NAME = "LoadProbe"; -my $DELAY = 1000; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current CPU usage to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic CPU usage info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub cpuTime () { - my ($user, $nice, $sys, $idle); - - local(*FIN); - open(FIN, ") { - chomp; - if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/o) { - ($user, $nice, $sys, $idle) = ($1, $2, $3, $4); - last; - } - } - close(FIN); - return ($user, $nice, $sys, $idle); -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# save current cpu ticks -my($userSv, $niceSv, $sysSv, $idleSv) = cpuTime(); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # retrieve new cpu ticks - my ($userN, $niceN, $sysN, $idleN) = cpuTime(); - # compute delta cpu ticks - my ($user, $nice, $sys, $idle) = - ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv); - # store the new saved ticks - ($userSv, $niceSv, $sysSv, $idleSv) = ($userN, $niceN, $sysN, $idleN); - my $total = $user + $nice + $sys + $idle; - my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), - $user/$total, $nice/$total, $sys/$total, $idle/$total); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "load"; +my $NAME = "LoadProbe"; +my $DELAY = 1000; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current CPU usage to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic CPU usage info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub cpuTime () { + my ($user, $nice, $sys, $idle); + + local(*FIN); + open(FIN, ") { + chomp; + if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/o) { + ($user, $nice, $sys, $idle) = ($1, $2, $3, $4); + last; + } + } + close(FIN); + return ($user, $nice, $sys, $idle); +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# save current cpu ticks +my($userSv, $niceSv, $sysSv, $idleSv) = cpuTime(); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # retrieve new cpu ticks + my ($userN, $niceN, $sysN, $idleN) = cpuTime(); + # compute delta cpu ticks + my ($user, $nice, $sys, $idle) = + ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv); + # store the new saved ticks + ($userSv, $niceSv, $sysSv, $idleSv) = ($userN, $niceN, $sysN, $idleN); + my $total = $user + $nice + $sys + $idle; + my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), + $user/$total, $nice/$total, $sys/$total, $idle/$total); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-client/system/probes/cygwin/probe-cygwin.bat b/targets/znews-ss-client/system/probes/cygwin/probe-cygwin.bat index 4f192949d..b912671dd 100644 --- a/targets/znews-ss-client/system/probes/cygwin/probe-cygwin.bat +++ b/targets/znews-ss-client/system/probes/cygwin/probe-cygwin.bat @@ -1,8 +1,8 @@ -@echo off - -C: -chdir C:\server\cygwin\bin -set DEMO_MODE=%1 -set DEMO_TITLE=%2 - -bash --login -i +@echo off + +C: +chdir C:\server\cygwin\bin +set DEMO_MODE=%1 +set DEMO_TITLE=%2 + +bash --login -i diff --git a/targets/znews-ss-client/system/probes/cygwin/runApachetop.pl b/targets/znews-ss-client/system/probes/cygwin/runApachetop.pl index aca341ab9..0970d810f 100644 --- a/targets/znews-ss-client/system/probes/cygwin/runApachetop.pl +++ b/targets/znews-ss-client/system/probes/cygwin/runApachetop.pl @@ -1,16 +1,16 @@ -#!/usr/bin/perl -w - -use strict; - -############################# -my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; -my $APACHETOP_LOG = "/cygdrive/c/server/rainbow/oracle/targets/znews1/log/apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - -if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; +#!/usr/bin/perl -w + +use strict; + +############################# +my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; +my $APACHETOP_LOG = "/cygdrive/c/server/rainbow/oracle/targets/znews1/log/apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + +if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; diff --git a/targets/znews-ss-client/system/probes/diskIOProbe-diskstats.pl b/targets/znews-ss-client/system/probes/diskIOProbe-diskstats.pl index e4a1e3ba5..a40e58938 100644 --- a/targets/znews-ss-client/system/probes/diskIOProbe-diskstats.pl +++ b/targets/znews-ss-client/system/probes/diskIOProbe-diskstats.pl @@ -1,125 +1,125 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "diskio"; -my $NAME = "DiskIOProbe"; -my $DELAY = 4000; -############################# - -# Determine diskstats format -my $statfile; -my $uname = `uname -a`; -if ($uname =~ /Linux\s+(.+?)\s+(\d+[.]\d+)/) { - if ($2 eq "2.6") { - $statfile = "/proc/diskstats"; -# } elsif ($2 <= 2.5) { -# $statfile = "/proc/partitions"; # granularity of info more coarse - } -} else { - print "Linux version unsupported for diskstat access! Unable to continue probing\n"; - exit -1; -} - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current accumulated Disk IO to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic Disk IO info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub diskUsage () { - my ($MINOR, $FIRST, $TMIO) = (2, 4, 14); # index to stat entry - my (@accumStat) = (0,0,0,0,0,0,0,0,0,0,0); - my (@dstat); #$rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio - - open(FIN, "< $statfile"); - while () { - chomp; - @dstat = split(/\s+/); # blank zeroth element due to space(s) in beginning - if ($dstat[$MINOR] == 0 && $dstat[$TMIO] > 0) { # accum reading from device - for my $i ($FIRST..$#dstat) { - $accumStat[$i-$FIRST] += $dstat[$i]; - } - #print "Accumulated @accumStat\n"; - } - } - close(FIN); - return @accumStat; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# zero out disk IO stats -my($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) - = (0,0,0,0,0,0,0,0,0,0,0); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - # retrieve new disk IO stats - my ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN) = diskUsage(); - # compute delta stats for all except 9th and 10th - my ($rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio) = - ($rcmpN-$rcmpS, $rmrgN-$rmrgS, $rsectN-$rsectS, $rmsN-$rmsS, $wcmpN-$wcmpS, - $wmrgN-$wmrgS, $wsectN-$wsectS, $wmsN-$wmsS, $curioN, $curmsN, $tmioN-$tmioS); - # store the new saved ticks - ($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) = - ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN); - # each sector is 512 bytes as of kernel 2.4, so divide 2 to get kb - #print "D: $rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio\n" if ($doPrint); - my $kbRead = $rsect/2.0; - my $kbRps = ($rms == 0) ? 0 : ($kbRead / $rms) * 1000; # sec = 1000 ms - my $kbWritten = $wsect/2.0; - my $kbWps = ($wms == 0) ? 0 : ($kbWritten / $wms) * 1000; - my $tps = ($rms+$wms == 0) ? 0 : ($rcmp+$wcmp)/($rms+$wms) * 1000; - my $rpt = sprintf("[%s] %9.2f %9.2f %9.2f %9d %9d %9d %9d %9d\n", "".localtime(), - $tps, $kbRps, $kbWps, $kbRead, $kbWritten, $curio, $curms, $tmio); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "diskio"; +my $NAME = "DiskIOProbe"; +my $DELAY = 4000; +############################# + +# Determine diskstats format +my $statfile; +my $uname = `uname -a`; +if ($uname =~ /Linux\s+(.+?)\s+(\d+[.]\d+)/) { + if ($2 eq "2.6") { + $statfile = "/proc/diskstats"; +# } elsif ($2 <= 2.5) { +# $statfile = "/proc/partitions"; # granularity of info more coarse + } +} else { + print "Linux version unsupported for diskstat access! Unable to continue probing\n"; + exit -1; +} + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current accumulated Disk IO to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic Disk IO info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub diskUsage () { + my ($MINOR, $FIRST, $TMIO) = (2, 4, 14); # index to stat entry + my (@accumStat) = (0,0,0,0,0,0,0,0,0,0,0); + my (@dstat); #$rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio + + open(FIN, "< $statfile"); + while () { + chomp; + @dstat = split(/\s+/); # blank zeroth element due to space(s) in beginning + if ($dstat[$MINOR] == 0 && $dstat[$TMIO] > 0) { # accum reading from device + for my $i ($FIRST..$#dstat) { + $accumStat[$i-$FIRST] += $dstat[$i]; + } + #print "Accumulated @accumStat\n"; + } + } + close(FIN); + return @accumStat; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# zero out disk IO stats +my($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) + = (0,0,0,0,0,0,0,0,0,0,0); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + # retrieve new disk IO stats + my ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN) = diskUsage(); + # compute delta stats for all except 9th and 10th + my ($rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio) = + ($rcmpN-$rcmpS, $rmrgN-$rmrgS, $rsectN-$rsectS, $rmsN-$rmsS, $wcmpN-$wcmpS, + $wmrgN-$wmrgS, $wsectN-$wsectS, $wmsN-$wmsS, $curioN, $curmsN, $tmioN-$tmioS); + # store the new saved ticks + ($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) = + ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN); + # each sector is 512 bytes as of kernel 2.4, so divide 2 to get kb + #print "D: $rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio\n" if ($doPrint); + my $kbRead = $rsect/2.0; + my $kbRps = ($rms == 0) ? 0 : ($kbRead / $rms) * 1000; # sec = 1000 ms + my $kbWritten = $wsect/2.0; + my $kbWps = ($wms == 0) ? 0 : ($kbWritten / $wms) * 1000; + my $tps = ($rms+$wms == 0) ? 0 : ($rcmp+$wcmp)/($rms+$wms) * 1000; + my $rpt = sprintf("[%s] %9.2f %9.2f %9.2f %9d %9d %9d %9d %9d\n", "".localtime(), + $tps, $kbRps, $kbWps, $kbRead, $kbWritten, $curio, $curms, $tmio); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-client/system/probes/diskIOProbe.pl b/targets/znews-ss-client/system/probes/diskIOProbe.pl index ec3391891..fe4b002b3 100644 --- a/targets/znews-ss-client/system/probes/diskIOProbe.pl +++ b/targets/znews-ss-client/system/probes/diskIOProbe.pl @@ -1,101 +1,101 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "diskio"; -my $NAME = "DiskIOProbe"; -my $DELAY = 5000; -############################# - -# Determine diskstats format -my $IOSTAT = "/usr/bin/iostat"; -if (! -e $IOSTAT) { - print "No iostat found, please install the sysstat package to continue!\n"; - exit -1; -} -my $IOSTAT_ARGS = "-k " . ($DELAY/1000); # period, with indefinite ouput - -sub usage() { - print STDERR << "EOF"; - -This program dumps periodic Disk IO status to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic Disk IO info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# init disk IO stats vars -my($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); -my($isInitial, $cntCycle) = (1, 0); -open(FIN, "$IOSTAT $IOSTAT_ARGS |") - || die "Can't fork $IOSTAT: $!"; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - # retrieve new disk IO stats - while () { - chomp; - if (/^Device:/i) { - ++$cntCycle; - if ($isInitial && $cntCycle > 1) { # no longer initial - print "Filtered initial round!\n" if ($doPrint); - $isInitial = 0; - } - } - if (!$isInitial && - /^(\w+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/) { - ($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB) = ($1, $2, $3, $4, $5, $6); - last; - } - } - my $rpt = sprintf("[%s] %s %.2f %.2f %.2f %d %d\n", "".localtime(), - $dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -close(FIN) || die "Bad $IOSTAT: $! $?"; -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "diskio"; +my $NAME = "DiskIOProbe"; +my $DELAY = 5000; +############################# + +# Determine diskstats format +my $IOSTAT = "/usr/bin/iostat"; +if (! -e $IOSTAT) { + print "No iostat found, please install the sysstat package to continue!\n"; + exit -1; +} +my $IOSTAT_ARGS = "-k " . ($DELAY/1000); # period, with indefinite ouput + +sub usage() { + print STDERR << "EOF"; + +This program dumps periodic Disk IO status to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic Disk IO info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# init disk IO stats vars +my($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); +my($isInitial, $cntCycle) = (1, 0); +open(FIN, "$IOSTAT $IOSTAT_ARGS |") + || die "Can't fork $IOSTAT: $!"; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + # retrieve new disk IO stats + while () { + chomp; + if (/^Device:/i) { + ++$cntCycle; + if ($isInitial && $cntCycle > 1) { # no longer initial + print "Filtered initial round!\n" if ($doPrint); + $isInitial = 0; + } + } + if (!$isInitial && + /^(\w+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/) { + ($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB) = ($1, $2, $3, $4, $5, $6); + last; + } + } + my $rpt = sprintf("[%s] %s %.2f %.2f %.2f %d %d\n", "".localtime(), + $dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +close(FIN) || die "Bad $IOSTAT: $! $?"; +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-client/system/probes/fidelityProbe.pl b/targets/znews-ss-client/system/probes/fidelityProbe.pl index d5a8214ff..d22e3f086 100644 --- a/targets/znews-ss-client/system/probes/fidelityProbe.pl +++ b/targets/znews-ss-client/system/probes/fidelityProbe.pl @@ -1,100 +1,100 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "fidelity"; -my $NAME = "FidelityProbe"; -my $DELAY = 1000; -my $REPEATEVERY = 5; -my $APACHE_CONF_DIR = "/etc/apache2"; -my $APACHE_CONF_FILE = "apache2.conf"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current server fidelity (1,3,5) to Probe Relay file/socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic server fidelity info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub determineFidelity () { - my $fid = 0; - - open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); - my $firstLine = ; # read the first line - if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { - $fid = $1; - } - close(FIN); - - return $fid; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -my $repeatCnt = $REPEATEVERY; -my $savedFidelity = 0; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # compute new fidelity status - my $fidelity = determineFidelity(); - if ($fidelity != $savedFidelity || $repeatCnt == 0) { - $savedFidelity = $fidelity; #store new fidelity - my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - - if ($repeatCnt == 0) { - $repeatCnt = $REPEATEVERY; - } - } else { - $repeatCnt--; - } -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "fidelity"; +my $NAME = "FidelityProbe"; +my $DELAY = 1000; +my $REPEATEVERY = 5; +my $APACHE_CONF_DIR = "/etc/apache2"; +my $APACHE_CONF_FILE = "apache2.conf"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current server fidelity (1,3,5) to Probe Relay file/socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic server fidelity info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub determineFidelity () { + my $fid = 0; + + open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); + my $firstLine = ; # read the first line + if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { + $fid = $1; + } + close(FIN); + + return $fid; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +my $repeatCnt = $REPEATEVERY; +my $savedFidelity = 0; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # compute new fidelity status + my $fidelity = determineFidelity(); + if ($fidelity != $savedFidelity || $repeatCnt == 0) { + $savedFidelity = $fidelity; #store new fidelity + my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + + if ($repeatCnt == 0) { + $repeatCnt = $REPEATEVERY; + } + } else { + $repeatCnt--; + } +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-client/system/probes/iostat.h b/targets/znews-ss-client/system/probes/iostat.h index 14abd66ec..644e9af0a 100644 --- a/targets/znews-ss-client/system/probes/iostat.h +++ b/targets/znews-ss-client/system/probes/iostat.h @@ -1,116 +1,116 @@ -/* - * iostat: report CPU and I/O statistics - * (C) 1999-2004 by Sebastien Godard - */ - -#ifndef _IOSTAT_H -#define _IOSTAT_H - -#include "common.h" - -#define MAX_NAME_LEN 72 - -#define D_CPU_ONLY 0x001 -#define D_DISK_ONLY 0x002 -#define D_TIMESTAMP 0x004 -#define D_EXTENDED 0x008 -#define D_PART_ALL 0x010 -#define D_KILOBYTES 0x020 -#define F_HAS_SYSFS 0x040 -#define F_OLD_KERNEL 0x080 -#define D_UNFILTERED 0x100 -/* 0x100000:0x800000 -> reserved (cf. common.h) */ - -#define DISPLAY_CPU_ONLY(m) (((m) & D_CPU_ONLY) == D_CPU_ONLY) -#define DISPLAY_DISK_ONLY(m) (((m) & D_DISK_ONLY) == D_DISK_ONLY) -#define DISPLAY_TIMESTAMP(m) (((m) & D_TIMESTAMP) == D_TIMESTAMP) -#define DISPLAY_EXTENDED(m) (((m) & D_EXTENDED) == D_EXTENDED) -#define DISPLAY_PART_ALL(m) (((m) & D_PART_ALL) == D_PART_ALL) -#define DISPLAY_KILOBYTES(m) (((m) & D_KILOBYTES) == D_KILOBYTES) -#define HAS_SYSFS(m) (((m) & F_HAS_SYSFS) == F_HAS_SYSFS) -#define HAS_OLD_KERNEL(m) (((m) & F_OLD_KERNEL) == F_OLD_KERNEL) -#define DISPLAY_UNFILTERED(m) (((m) & D_UNFILTERED) == D_UNFILTERED) - -#define DT_DEVICE 0 -#define DT_PARTITION 1 - - -struct comm_stats { - unsigned long uptime; - unsigned long uptime0; - unsigned long cpu_iowait; - unsigned long cpu_idle; - unsigned int cpu_user; - unsigned int cpu_nice; - unsigned int cpu_system; -}; - -#define COMM_STATS_SIZE (sizeof(struct comm_stats)) - -/* - * Structures for I/O stats. - * The number of structures allocated corresponds to the number of devices - * present in the system, plus a preallocation number to handle those - * that can be registered dynamically. - * The number of devices is found by using /sys filesystem (if mounted), - * or the number of "disk_io:" entries in /proc/stat (2.4 kernels), - * else the default value is 4 (for old kernels, which maintained stats - * for the first four devices in /proc/stat). - * For each io_stats structure allocated corresponds a io_hdr_stats structure. - * A io_stats structure is considered as unused or "free" (containing no stats - * for a particular device) if the 'major' field of the io_hdr_stats - * structure is set to 0. - */ -struct io_stats { - /* # of read operations issued to the device */ - unsigned int rd_ios __attribute__ ((aligned (8))); - /* # of read requests merged */ - unsigned int rd_merges __attribute__ ((packed)); - /* # of sectors read */ - unsigned int rd_sectors __attribute__ ((packed)); - /* Time of read requests in queue */ - unsigned int rd_ticks __attribute__ ((packed)); - /* # of write operations issued to the device */ - unsigned int wr_ios __attribute__ ((packed)); - /* # of write requests merged */ - unsigned int wr_merges __attribute__ ((packed)); - /* # of sectors written */ - unsigned int wr_sectors __attribute__ ((packed)); - /* Time of write requests in queue */ - unsigned int wr_ticks __attribute__ ((packed)); - /* # of I/Os in progress */ - unsigned int ios_pgr __attribute__ ((packed)); - /* # of ticks total (for this device) for I/O */ - unsigned int tot_ticks __attribute__ ((packed)); - /* # of ticks requests spent in queue */ - unsigned int rq_ticks __attribute__ ((packed)); - /* # of I/O done since last reboot */ - unsigned int dk_drive __attribute__ ((packed)); - /* # of blocks read */ - unsigned int dk_drive_rblk __attribute__ ((packed)); - /* # of blocks written */ - unsigned int dk_drive_wblk __attribute__ ((packed)); -}; - -#define IO_STATS_SIZE (sizeof(struct io_stats)) - -struct io_hdr_stats { - unsigned int active __attribute__ ((aligned (8))); - unsigned int major __attribute__ ((packed)); - unsigned int index __attribute__ ((packed)); - char name[MAX_NAME_LEN] __attribute__ ((packed)); -}; - -#define IO_HDR_STATS_SIZE (sizeof(struct io_hdr_stats)) - -/* List of devices entered on the command line */ -struct io_dlist { - /* Indicate whether its partitions are to be displayed or not */ - int disp_part __attribute__ ((aligned (8))); - /* Device name */ - char dev_name[MAX_NAME_LEN] __attribute__ ((packed)); -}; - -#define IO_DLIST_SIZE (sizeof(struct io_dlist)) - -#endif /* _IOSTAT_H */ +/* + * iostat: report CPU and I/O statistics + * (C) 1999-2004 by Sebastien Godard + */ + +#ifndef _IOSTAT_H +#define _IOSTAT_H + +#include "common.h" + +#define MAX_NAME_LEN 72 + +#define D_CPU_ONLY 0x001 +#define D_DISK_ONLY 0x002 +#define D_TIMESTAMP 0x004 +#define D_EXTENDED 0x008 +#define D_PART_ALL 0x010 +#define D_KILOBYTES 0x020 +#define F_HAS_SYSFS 0x040 +#define F_OLD_KERNEL 0x080 +#define D_UNFILTERED 0x100 +/* 0x100000:0x800000 -> reserved (cf. common.h) */ + +#define DISPLAY_CPU_ONLY(m) (((m) & D_CPU_ONLY) == D_CPU_ONLY) +#define DISPLAY_DISK_ONLY(m) (((m) & D_DISK_ONLY) == D_DISK_ONLY) +#define DISPLAY_TIMESTAMP(m) (((m) & D_TIMESTAMP) == D_TIMESTAMP) +#define DISPLAY_EXTENDED(m) (((m) & D_EXTENDED) == D_EXTENDED) +#define DISPLAY_PART_ALL(m) (((m) & D_PART_ALL) == D_PART_ALL) +#define DISPLAY_KILOBYTES(m) (((m) & D_KILOBYTES) == D_KILOBYTES) +#define HAS_SYSFS(m) (((m) & F_HAS_SYSFS) == F_HAS_SYSFS) +#define HAS_OLD_KERNEL(m) (((m) & F_OLD_KERNEL) == F_OLD_KERNEL) +#define DISPLAY_UNFILTERED(m) (((m) & D_UNFILTERED) == D_UNFILTERED) + +#define DT_DEVICE 0 +#define DT_PARTITION 1 + + +struct comm_stats { + unsigned long uptime; + unsigned long uptime0; + unsigned long cpu_iowait; + unsigned long cpu_idle; + unsigned int cpu_user; + unsigned int cpu_nice; + unsigned int cpu_system; +}; + +#define COMM_STATS_SIZE (sizeof(struct comm_stats)) + +/* + * Structures for I/O stats. + * The number of structures allocated corresponds to the number of devices + * present in the system, plus a preallocation number to handle those + * that can be registered dynamically. + * The number of devices is found by using /sys filesystem (if mounted), + * or the number of "disk_io:" entries in /proc/stat (2.4 kernels), + * else the default value is 4 (for old kernels, which maintained stats + * for the first four devices in /proc/stat). + * For each io_stats structure allocated corresponds a io_hdr_stats structure. + * A io_stats structure is considered as unused or "free" (containing no stats + * for a particular device) if the 'major' field of the io_hdr_stats + * structure is set to 0. + */ +struct io_stats { + /* # of read operations issued to the device */ + unsigned int rd_ios __attribute__ ((aligned (8))); + /* # of read requests merged */ + unsigned int rd_merges __attribute__ ((packed)); + /* # of sectors read */ + unsigned int rd_sectors __attribute__ ((packed)); + /* Time of read requests in queue */ + unsigned int rd_ticks __attribute__ ((packed)); + /* # of write operations issued to the device */ + unsigned int wr_ios __attribute__ ((packed)); + /* # of write requests merged */ + unsigned int wr_merges __attribute__ ((packed)); + /* # of sectors written */ + unsigned int wr_sectors __attribute__ ((packed)); + /* Time of write requests in queue */ + unsigned int wr_ticks __attribute__ ((packed)); + /* # of I/Os in progress */ + unsigned int ios_pgr __attribute__ ((packed)); + /* # of ticks total (for this device) for I/O */ + unsigned int tot_ticks __attribute__ ((packed)); + /* # of ticks requests spent in queue */ + unsigned int rq_ticks __attribute__ ((packed)); + /* # of I/O done since last reboot */ + unsigned int dk_drive __attribute__ ((packed)); + /* # of blocks read */ + unsigned int dk_drive_rblk __attribute__ ((packed)); + /* # of blocks written */ + unsigned int dk_drive_wblk __attribute__ ((packed)); +}; + +#define IO_STATS_SIZE (sizeof(struct io_stats)) + +struct io_hdr_stats { + unsigned int active __attribute__ ((aligned (8))); + unsigned int major __attribute__ ((packed)); + unsigned int index __attribute__ ((packed)); + char name[MAX_NAME_LEN] __attribute__ ((packed)); +}; + +#define IO_HDR_STATS_SIZE (sizeof(struct io_hdr_stats)) + +/* List of devices entered on the command line */ +struct io_dlist { + /* Indicate whether its partitions are to be displayed or not */ + int disp_part __attribute__ ((aligned (8))); + /* Device name */ + char dev_name[MAX_NAME_LEN] __attribute__ ((packed)); +}; + +#define IO_DLIST_SIZE (sizeof(struct io_dlist)) + +#endif /* _IOSTAT_H */ diff --git a/targets/znews-ss-client/system/probes/iostats.txt b/targets/znews-ss-client/system/probes/iostats.txt index 612dc5511..ba75611ea 100644 --- a/targets/znews-ss-client/system/probes/iostats.txt +++ b/targets/znews-ss-client/system/probes/iostats.txt @@ -1,151 +1,151 @@ -I/O statistics fields ---------------- - -Based on kernel version 2.6.20. Page generated on 2007-02-07 22:05 EST -Last modified Sep 30, 2003 - -Since 2.4.20 (and some versions before, with patches), and 2.5.45, -more extensive disk statistics have been introduced to help measure disk -activity. Tools such as sar and iostat typically interpret these and do -the work for you, but in case you are interested in creating your own -tools, the fields are explained here. - -In 2.4 now, the information is found as additional fields in -/proc/partitions. In 2.6, the same information is found in two -places: one is in the file /proc/diskstats, and the other is within -the sysfs file system, which must be mounted in order to obtain -the information. Throughout this document we'll assume that sysfs -is mounted on /sys, although of course it may be mounted anywhere. -Both /proc/diskstats and sysfs use the same source for the information -and so should not differ. - -Here are examples of these different formats: - -2.4: - 3 0 39082680 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 3 1 9221278 hda1 35486 0 35496 38030 0 0 0 0 0 38030 38030 - - -2.6 sysfs: - 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 35486 38030 38030 38030 - -2.6 diskstats: - 3 0 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 3 1 hda1 35486 38030 38030 38030 - -On 2.4 you might execute "grep 'hda ' /proc/partitions". On 2.6, you have -a choice of "cat /sys/block/hda/stat" or "grep 'hda ' /proc/diskstats". -The advantage of one over the other is that the sysfs choice works well -if you are watching a known, small set of disks. /proc/diskstats may -be a better choice if you are watching a large number of disks because -you'll avoid the overhead of 50, 100, or 500 or more opens/closes with -each snapshot of your disk statistics. - -In 2.4, the statistics fields are those after the device name. In -the above example, the first field of statistics would be 446216. -By contrast, in 2.6 if you look at /sys/block/hda/stat, you'll -find just the eleven fields, beginning with 446216. If you look at -/proc/diskstats, the eleven fields will be preceded by the major and -minor device numbers, and device name. Each of these formats provide -eleven fields of statistics, each meaning exactly the same things. -All fields except field 9 are cumulative since boot. Field 9 should -go to zero as I/Os complete; all others only increase. Yes, these are -32 bit unsigned numbers, and on a very busy or long-lived system they -may wrap. Applications should be prepared to deal with that; unless -your observations are measured in large numbers of minutes or hours, -they should not wrap twice before you notice them. - -Each set of stats only applies to the indicated device; if you want -system-wide stats you'll have to find all the devices and sum them all up. - -Field 1 -- # of reads issued - This is the total number of reads completed successfully. -Field 2 -- # of reads merged, field 6 -- # of writes merged - Reads and writes which are adjacent to each other may be merged for - efficiency. Thus two 4K reads may become one 8K read before it is - ultimately handed to the disk, and so it will be counted (and queued) - as only one I/O. This field lets you know how often this was done. -Field 3 -- # of sectors read - This is the total number of sectors read successfully. -Field 4 -- # of milliseconds spent reading - This is the total number of milliseconds spent by all reads (as - measured from __make_request() to end_that_request_last()). -Field 5 -- # of writes completed - This is the total number of writes completed successfully. -Field 7 -- # of sectors written - This is the total number of sectors written successfully. -Field 8 -- # of milliseconds spent writing - This is the total number of milliseconds spent by all writes (as - measured from __make_request() to end_that_request_last()). -Field 9 -- # of I/Os currently in progress - The only field that should go to zero. Incremented as requests are - given to appropriate request_queue_t and decremented as they finish. -Field 10 -- # of milliseconds spent doing I/Os - This field is increases so long as field 9 is nonzero. -Field 11 -- weighted # of milliseconds spent doing I/Os - This field is incremented at each I/O start, I/O completion, I/O - merge, or read of these stats by the number of I/Os in progress - (field 9) times the number of milliseconds spent doing I/O since the - last update of this field. This can provide an easy measure of both - I/O completion time and the backlog that may be accumulating. - - -To avoid introducing performance bottlenecks, no locks are held while -modifying these counters. This implies that minor inaccuracies may be -introduced when changes collide, so (for instance) adding up all the -read I/Os issued per partition should equal those made to the disks ... -but due to the lack of locking it may only be very close. - -In 2.6, there are counters for each cpu, which made the lack of locking -almost a non-issue. When the statistics are read, the per-cpu counters -are summed (possibly overflowing the unsigned 32-bit variable they are -summed to) and the result given to the user. There is no convenient -user interface for accessing the per-cpu counters themselves. - -Disks vs Partitions -------------------- - -There were significant changes between 2.4 and 2.6 in the I/O subsystem. -As a result, some statistic information disappeared. The translation from -a disk address relative to a partition to the disk address relative to -the host disk happens much earlier. All merges and timings now happen -at the disk level rather than at both the disk and partition level as -in 2.4. Consequently, you'll see a different statistics output on 2.6 for -partitions from that for disks. There are only *four* fields available -for partitions on 2.6 machines. This is reflected in the examples above. - -Field 1 -- # of reads issued - This is the total number of reads issued to this partition. -Field 2 -- # of sectors read - This is the total number of sectors requested to be read from this - partition. -Field 3 -- # of writes issued - This is the total number of writes issued to this partition. -Field 4 -- # of sectors written - This is the total number of sectors requested to be written to - this partition. - -Note that since the address is translated to a disk-relative one, and no -record of the partition-relative address is kept, the subsequent success -or failure of the read cannot be attributed to the partition. In other -words, the number of reads for partitions is counted slightly before time -of queuing for partitions, and at completion for whole disks. This is -a subtle distinction that is probably uninteresting for most cases. - -Additional notes ----------------- - -In 2.6, sysfs is not mounted by default. If your distribution of -Linux hasn't added it already, here's the line you'll want to add to -your /etc/fstab: - -none /sys sysfs defaults 0 0 - - -In 2.6, all disk statistics were removed from /proc/stat. In 2.4, they -appear in both /proc/partitions and /proc/stat, although the ones in -/proc/stat take a very different format from those in /proc/partitions -(see proc(5), if your system has it.) - --- ricklind[AT]us.ibm[DOT]com +I/O statistics fields +--------------- + +Based on kernel version 2.6.20. Page generated on 2007-02-07 22:05 EST +Last modified Sep 30, 2003 + +Since 2.4.20 (and some versions before, with patches), and 2.5.45, +more extensive disk statistics have been introduced to help measure disk +activity. Tools such as sar and iostat typically interpret these and do +the work for you, but in case you are interested in creating your own +tools, the fields are explained here. + +In 2.4 now, the information is found as additional fields in +/proc/partitions. In 2.6, the same information is found in two +places: one is in the file /proc/diskstats, and the other is within +the sysfs file system, which must be mounted in order to obtain +the information. Throughout this document we'll assume that sysfs +is mounted on /sys, although of course it may be mounted anywhere. +Both /proc/diskstats and sysfs use the same source for the information +and so should not differ. + +Here are examples of these different formats: + +2.4: + 3 0 39082680 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 3 1 9221278 hda1 35486 0 35496 38030 0 0 0 0 0 38030 38030 + + +2.6 sysfs: + 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 35486 38030 38030 38030 + +2.6 diskstats: + 3 0 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 3 1 hda1 35486 38030 38030 38030 + +On 2.4 you might execute "grep 'hda ' /proc/partitions". On 2.6, you have +a choice of "cat /sys/block/hda/stat" or "grep 'hda ' /proc/diskstats". +The advantage of one over the other is that the sysfs choice works well +if you are watching a known, small set of disks. /proc/diskstats may +be a better choice if you are watching a large number of disks because +you'll avoid the overhead of 50, 100, or 500 or more opens/closes with +each snapshot of your disk statistics. + +In 2.4, the statistics fields are those after the device name. In +the above example, the first field of statistics would be 446216. +By contrast, in 2.6 if you look at /sys/block/hda/stat, you'll +find just the eleven fields, beginning with 446216. If you look at +/proc/diskstats, the eleven fields will be preceded by the major and +minor device numbers, and device name. Each of these formats provide +eleven fields of statistics, each meaning exactly the same things. +All fields except field 9 are cumulative since boot. Field 9 should +go to zero as I/Os complete; all others only increase. Yes, these are +32 bit unsigned numbers, and on a very busy or long-lived system they +may wrap. Applications should be prepared to deal with that; unless +your observations are measured in large numbers of minutes or hours, +they should not wrap twice before you notice them. + +Each set of stats only applies to the indicated device; if you want +system-wide stats you'll have to find all the devices and sum them all up. + +Field 1 -- # of reads issued + This is the total number of reads completed successfully. +Field 2 -- # of reads merged, field 6 -- # of writes merged + Reads and writes which are adjacent to each other may be merged for + efficiency. Thus two 4K reads may become one 8K read before it is + ultimately handed to the disk, and so it will be counted (and queued) + as only one I/O. This field lets you know how often this was done. +Field 3 -- # of sectors read + This is the total number of sectors read successfully. +Field 4 -- # of milliseconds spent reading + This is the total number of milliseconds spent by all reads (as + measured from __make_request() to end_that_request_last()). +Field 5 -- # of writes completed + This is the total number of writes completed successfully. +Field 7 -- # of sectors written + This is the total number of sectors written successfully. +Field 8 -- # of milliseconds spent writing + This is the total number of milliseconds spent by all writes (as + measured from __make_request() to end_that_request_last()). +Field 9 -- # of I/Os currently in progress + The only field that should go to zero. Incremented as requests are + given to appropriate request_queue_t and decremented as they finish. +Field 10 -- # of milliseconds spent doing I/Os + This field is increases so long as field 9 is nonzero. +Field 11 -- weighted # of milliseconds spent doing I/Os + This field is incremented at each I/O start, I/O completion, I/O + merge, or read of these stats by the number of I/Os in progress + (field 9) times the number of milliseconds spent doing I/O since the + last update of this field. This can provide an easy measure of both + I/O completion time and the backlog that may be accumulating. + + +To avoid introducing performance bottlenecks, no locks are held while +modifying these counters. This implies that minor inaccuracies may be +introduced when changes collide, so (for instance) adding up all the +read I/Os issued per partition should equal those made to the disks ... +but due to the lack of locking it may only be very close. + +In 2.6, there are counters for each cpu, which made the lack of locking +almost a non-issue. When the statistics are read, the per-cpu counters +are summed (possibly overflowing the unsigned 32-bit variable they are +summed to) and the result given to the user. There is no convenient +user interface for accessing the per-cpu counters themselves. + +Disks vs Partitions +------------------- + +There were significant changes between 2.4 and 2.6 in the I/O subsystem. +As a result, some statistic information disappeared. The translation from +a disk address relative to a partition to the disk address relative to +the host disk happens much earlier. All merges and timings now happen +at the disk level rather than at both the disk and partition level as +in 2.4. Consequently, you'll see a different statistics output on 2.6 for +partitions from that for disks. There are only *four* fields available +for partitions on 2.6 machines. This is reflected in the examples above. + +Field 1 -- # of reads issued + This is the total number of reads issued to this partition. +Field 2 -- # of sectors read + This is the total number of sectors requested to be read from this + partition. +Field 3 -- # of writes issued + This is the total number of writes issued to this partition. +Field 4 -- # of sectors written + This is the total number of sectors requested to be written to + this partition. + +Note that since the address is translated to a disk-relative one, and no +record of the partition-relative address is kept, the subsequent success +or failure of the read cannot be attributed to the partition. In other +words, the number of reads for partitions is counted slightly before time +of queuing for partitions, and at completion for whole disks. This is +a subtle distinction that is probably uninteresting for most cases. + +Additional notes +---------------- + +In 2.6, sysfs is not mounted by default. If your distribution of +Linux hasn't added it already, here's the line you'll want to add to +your /etc/fstab: + +none /sys sysfs defaults 0 0 + + +In 2.6, all disk statistics were removed from /proc/stat. In 2.4, they +appear in both /proc/partitions and /proc/stat, although the ones in +/proc/stat take a very different format from those in /proc/partitions +(see proc(5), if your system has it.) + +-- ricklind[AT]us.ibm[DOT]com diff --git a/targets/znews-ss-client/system/probes/loadProbe.pl b/targets/znews-ss-client/system/probes/loadProbe.pl index 7f2e12dc8..3b648fd9c 100644 --- a/targets/znews-ss-client/system/probes/loadProbe.pl +++ b/targets/znews-ss-client/system/probes/loadProbe.pl @@ -1,101 +1,101 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "load"; -my $NAME = "LoadProbe"; -my $DELAY = 2500; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current CPU usage to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic CPU usage info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub cpuTime () { - my ($user, $nice, $sys, $idle, $iowait); - - local(*FIN); - open(FIN, ") { - chomp; - if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(\s+(\d+))?/o) { - ($user, $nice, $sys, $idle, $iowait) = ($1, $2, $3, $4, $6); - if (!defined($iowait)) { - $iowait = 0; - } - last; - } - } - close(FIN); - return ($user, $nice, $sys, $idle, $iowait); -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# save current cpu ticks -my($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = cpuTime(); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # retrieve new cpu ticks - my ($userN, $niceN, $sysN, $idleN, $iowaitN) = cpuTime(); - # compute delta cpu ticks - my ($user, $nice, $sys, $idle, $iowait) = - ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv, $iowaitN - $iowaitSv); - # store the new saved ticks - ($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = ($userN, $niceN, $sysN, $idleN, $iowaitN); - my $total = $user + $nice + $sys + $idle + $iowait; - my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), - $user/$total, $nice/$total, $sys/$total, $idle/$total, $iowait/$total); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "load"; +my $NAME = "LoadProbe"; +my $DELAY = 2500; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current CPU usage to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic CPU usage info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub cpuTime () { + my ($user, $nice, $sys, $idle, $iowait); + + local(*FIN); + open(FIN, ") { + chomp; + if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(\s+(\d+))?/o) { + ($user, $nice, $sys, $idle, $iowait) = ($1, $2, $3, $4, $6); + if (!defined($iowait)) { + $iowait = 0; + } + last; + } + } + close(FIN); + return ($user, $nice, $sys, $idle, $iowait); +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# save current cpu ticks +my($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = cpuTime(); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # retrieve new cpu ticks + my ($userN, $niceN, $sysN, $idleN, $iowaitN) = cpuTime(); + # compute delta cpu ticks + my ($user, $nice, $sys, $idle, $iowait) = + ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv, $iowaitN - $iowaitSv); + # store the new saved ticks + ($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = ($userN, $niceN, $sysN, $idleN, $iowaitN); + my $total = $user + $nice + $sys + $idle + $iowait; + my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), + $user/$total, $nice/$total, $sys/$total, $idle/$total, $iowait/$total); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-client/system/probes/runApachetop.pl b/targets/znews-ss-client/system/probes/runApachetop.pl index 2d9a80a4d..741ee43f6 100644 --- a/targets/znews-ss-client/system/probes/runApachetop.pl +++ b/targets/znews-ss-client/system/probes/runApachetop.pl @@ -1,16 +1,16 @@ -#!/usr/bin/perl -w - -use strict; - -############################# -my $APACHE_LOG = "/var/log/apache2/access-delegate.log"; -my $APACHETOP_LOG = "../../log/apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - -if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; +#!/usr/bin/perl -w + +use strict; + +############################# +my $APACHE_LOG = "/var/log/apache2/access-delegate.log"; +my $APACHETOP_LOG = "../../log/apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + +if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; diff --git a/targets/znews-ss-client/system/webpages/www1/index.html b/targets/znews-ss-client/system/webpages/www1/index.html index 050159b89..4ec9f5304 100644 --- a/targets/znews-ss-client/system/webpages/www1/index.html +++ b/targets/znews-ss-client/system/webpages/www1/index.html @@ -1,46 +1,46 @@ - - -Somewhere Over the Rainbow - - -

Z.com News - Hello World! (Low-fidelity Settings)

- -We apologize for this text-only content, as we are currently swamped with visitors. Thank you for your patience as we work hard to serve your requests. (This file is a little over 3 KB.) -

-SYDNEY, Australia (Reuters) -- In death as in life, iconic TV naturalist Steve Irwin captivated millions worldwide and clogged the Internet as fans from Guam to Glasgow reacted with disbelief to news "The Crocodile Hunter" was dead. -

-Some Web sites groaned to a halt within hours of the first reports Monday that Irwin had been killed by a stingray's barb through his chest in a freak diving accident off Australia's northeast coast. -

-Web measurement company Hitwise said Irwin's death was the biggest news event read by Australians on the Internet since two Australian miners were trapped by a mine collapse in southern Tasmania state in late April. -

-"We noticed that the Web site www.crocodilehunter.com increased in popularity quite substantially. It became the number one entertainment personality Web site in Australia yesterday and in the United States it also became the third most popular," Hitwise Asia-Pacific marketing director James Borg told Reuters. -

-Australian news Web sites struggled to keep up with demand. -

-The Australian Broadcasting Corp.'s site (www.abc.com.au) had to temporarily shut down, posting a notice Monday that it was experiencing higher than normal traffic. -

-It resumed soon after in a low-bandwidth format to cope with hundreds of thousands of hits. -

-Newspaper Web sites also wobbled but kept up with demand. -

-A spokesman for The Sydney Morning Herald's site, www.smh.com.au, said it had experienced a "huge" 40 percent spike in page impressions compared with the previous week's average weekday number of about 500,000. -

-There was also a 70 percent jump in visitors to its pages, the spokesman said. -

-That pattern was mirrored around the world, with Irwin's death leading major news Web sites such as CNN.com and U.S. and British newspaper Web sites, as well as swamping their most viewed and most emailed categories. -

-Web logs and Internet feedback pages were also awash with postings from shocked readers from around the world, many of them from Americans charmed by Irwin's quirky style and his typically Australian catchphrase of "crikey." -

-Irwin first found fame in the United States before his "Crocodile Hunter" documentaries on U.S.-based television company Discovery Communications' Animal Planet attracted a global audience of 200 million -- 10 times Australia's population. -

-"Crikey!, I miss him so much," Tina Treece from Pittsburgh, Pennsylvania, posted on CNN.com's feedback page CNN Exchange. -

-The site had contributions from readers in Guam, Romania, Thailand, France, Scotland, India, New Zealand, Canada, Brunei, Britain, Malaysia, Denmark and the Netherlands. -

-Many faced the problem of explaining to their children how one of their favorite TV characters had died. -

-"Why did it have to be Steve Irwin?" 11-year-old Daniel told Australian Associated Press. -

-Copyright 2006 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed. - - + + +Somewhere Over the Rainbow + + +

Z.com News - Hello World! (Low-fidelity Settings)

+ +We apologize for this text-only content, as we are currently swamped with visitors. Thank you for your patience as we work hard to serve your requests. (This file is a little over 3 KB.) +

+SYDNEY, Australia (Reuters) -- In death as in life, iconic TV naturalist Steve Irwin captivated millions worldwide and clogged the Internet as fans from Guam to Glasgow reacted with disbelief to news "The Crocodile Hunter" was dead. +

+Some Web sites groaned to a halt within hours of the first reports Monday that Irwin had been killed by a stingray's barb through his chest in a freak diving accident off Australia's northeast coast. +

+Web measurement company Hitwise said Irwin's death was the biggest news event read by Australians on the Internet since two Australian miners were trapped by a mine collapse in southern Tasmania state in late April. +

+"We noticed that the Web site www.crocodilehunter.com increased in popularity quite substantially. It became the number one entertainment personality Web site in Australia yesterday and in the United States it also became the third most popular," Hitwise Asia-Pacific marketing director James Borg told Reuters. +

+Australian news Web sites struggled to keep up with demand. +

+The Australian Broadcasting Corp.'s site (www.abc.com.au) had to temporarily shut down, posting a notice Monday that it was experiencing higher than normal traffic. +

+It resumed soon after in a low-bandwidth format to cope with hundreds of thousands of hits. +

+Newspaper Web sites also wobbled but kept up with demand. +

+A spokesman for The Sydney Morning Herald's site, www.smh.com.au, said it had experienced a "huge" 40 percent spike in page impressions compared with the previous week's average weekday number of about 500,000. +

+There was also a 70 percent jump in visitors to its pages, the spokesman said. +

+That pattern was mirrored around the world, with Irwin's death leading major news Web sites such as CNN.com and U.S. and British newspaper Web sites, as well as swamping their most viewed and most emailed categories. +

+Web logs and Internet feedback pages were also awash with postings from shocked readers from around the world, many of them from Americans charmed by Irwin's quirky style and his typically Australian catchphrase of "crikey." +

+Irwin first found fame in the United States before his "Crocodile Hunter" documentaries on U.S.-based television company Discovery Communications' Animal Planet attracted a global audience of 200 million -- 10 times Australia's population. +

+"Crikey!, I miss him so much," Tina Treece from Pittsburgh, Pennsylvania, posted on CNN.com's feedback page CNN Exchange. +

+The site had contributions from readers in Guam, Romania, Thailand, France, Scotland, India, New Zealand, Canada, Brunei, Britain, Malaysia, Denmark and the Netherlands. +

+Many faced the problem of explaining to their children how one of their favorite TV characters had died. +

+"Why did it have to be Steve Irwin?" 11-year-old Daniel told Australian Associated Press. +

+Copyright 2006 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed. + + diff --git a/targets/znews-ss-client/system/webpages/www3/index.html b/targets/znews-ss-client/system/webpages/www3/index.html index d5801caa4..dee934b7c 100644 --- a/targets/znews-ss-client/system/webpages/www3/index.html +++ b/targets/znews-ss-client/system/webpages/www3/index.html @@ -1,11 +1,11 @@ - - -Somewhere Over the Rainbow - - -

Z.com News - Hello World! (Medium-fidelity Settings)

-This file contains an 800x600 pixel image. The total size of this file is approximately 53K. -
- - + + +Somewhere Over the Rainbow + + +

Z.com News - Hello World! (Medium-fidelity Settings)

+This file contains an 800x600 pixel image. The total size of this file is approximately 53K. +
+ + \ No newline at end of file diff --git a/targets/znews-ss-client/system/webpages/www5/cgi-bin/computePi.pl b/targets/znews-ss-client/system/webpages/www5/cgi-bin/computePi.pl index 6871ac9b4..235516a09 100644 --- a/targets/znews-ss-client/system/webpages/www5/cgi-bin/computePi.pl +++ b/targets/znews-ss-client/system/webpages/www5/cgi-bin/computePi.pl @@ -1,118 +1,118 @@ -#!/usr/bin/perl - -use strict; -use Carp; -use Math::BigFloat; -use Class::Struct qw(struct); -use Data::Dumper; - -# With due homage to Mathsoft's site: -# http://www.mathsoft.com/asolve/constant/pi/pi.html - -# Set the global precision. Faster than passing it everywhichwhere. -my $precision = @ARGV>0?$ARGV[0]:512; - -# Set the iteration count. -my $maxIterations = @ARGV>1?$ARGV[1]:10; - -# Set the verbose debugging flag. -my $debugVerbose = 0; - -# Constants: -my $_1 = Math::BigFloat->new(1); -my $_2 = Math::BigFloat->new(2); -my $_3 = Math::BigFloat->new(3); -my $_4 = Math::BigFloat->new(4); -my $_6 = Math::BigFloat->new(6); -my $_8 = Math::BigFloat->new(8); -my $_239 = Math::BigFloat->new(239); -my $_half = Math::BigFloat->new(0.5); -my $_fifth = Math::BigFloat->new(0.2); -my $_25th = Math::BigFloat->new(0.04); -my $_239th = inv($_239); -my $_57121th = inv($_239*$_239); - - -# Utility methods: -sub div { - my $a = shift; - my $b = shift; - return new Math::BigFloat $a->copy()->fdiv($b,$precision); -} -sub inv { # Inverse (1/x) function. - my $a = shift; - return new Math::BigFloat $_1->copy()->fdiv($a,$precision); -} -sub root2 { - my $self = shift; - return new Math::BigFloat $self->copy()->fsqrt($precision); -} -sub root4 { - my $self = shift; - return root2(root2($self)); -} -sub pow4 { - my $self = shift; - my $square = round($self*$self); - return round($square*$square); -} -sub round { - my $self = shift; - return new Math::BigFloat $self->copy()->fround($precision); -} - -# Method 4: - -# This uses Ramanujan's elliptic integral-based technique to -# compute Pi monstrously quickly. -# -# This algorithm is neat, since it is quartically convergent - -# that means that the error goes as 4^(-iteration_count). -# -# In other words, one more step = four times the # of correct digits. - -sub RamanujanEI { - if (@_) { - my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. - - my $z_4_term = root4($_1 - pow4($z)); - my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); - - my $z_next_plus_1 = $z_next + $_1; - - my $a_next = pow4($z_next_plus_1) * $a - - $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); - $a_next = round($a_next); - return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; - - } else { # Seed the recurrence - my $a = $_6-$_4*root2($_2); - return [ $a, root2($_2)-$_1, $_8, inv($a)]; - } -} - - - -###################################################################### -# -# Main routine: -# -# - -my $iterResult = RamanujanEI(); -for (my $i=1; $i<$maxIterations; $i++) { - $iterResult = RamanujanEI($iterResult); -} -my $piValue = ${$iterResult}[-1]; -my $piStr = "" . $piValue; - -my $CHUNK = 32; -my $i = $CHUNK + 1; -print "Content-type: text/plain\r\n"; -print "Content-length: 570\r\n\r\n"; -print "Pi_512 :=\n"; -print " " . substr($piValue, 0, $i) . "\n"; -for (; $i < length($piValue) ; $i+=$CHUNK) { - print " " . substr($piValue, $i, $CHUNK) . "\n"; -} - +#!/usr/bin/perl + +use strict; +use Carp; +use Math::BigFloat; +use Class::Struct qw(struct); +use Data::Dumper; + +# With due homage to Mathsoft's site: +# http://www.mathsoft.com/asolve/constant/pi/pi.html + +# Set the global precision. Faster than passing it everywhichwhere. +my $precision = @ARGV>0?$ARGV[0]:512; + +# Set the iteration count. +my $maxIterations = @ARGV>1?$ARGV[1]:10; + +# Set the verbose debugging flag. +my $debugVerbose = 0; + +# Constants: +my $_1 = Math::BigFloat->new(1); +my $_2 = Math::BigFloat->new(2); +my $_3 = Math::BigFloat->new(3); +my $_4 = Math::BigFloat->new(4); +my $_6 = Math::BigFloat->new(6); +my $_8 = Math::BigFloat->new(8); +my $_239 = Math::BigFloat->new(239); +my $_half = Math::BigFloat->new(0.5); +my $_fifth = Math::BigFloat->new(0.2); +my $_25th = Math::BigFloat->new(0.04); +my $_239th = inv($_239); +my $_57121th = inv($_239*$_239); + + +# Utility methods: +sub div { + my $a = shift; + my $b = shift; + return new Math::BigFloat $a->copy()->fdiv($b,$precision); +} +sub inv { # Inverse (1/x) function. + my $a = shift; + return new Math::BigFloat $_1->copy()->fdiv($a,$precision); +} +sub root2 { + my $self = shift; + return new Math::BigFloat $self->copy()->fsqrt($precision); +} +sub root4 { + my $self = shift; + return root2(root2($self)); +} +sub pow4 { + my $self = shift; + my $square = round($self*$self); + return round($square*$square); +} +sub round { + my $self = shift; + return new Math::BigFloat $self->copy()->fround($precision); +} + +# Method 4: + +# This uses Ramanujan's elliptic integral-based technique to +# compute Pi monstrously quickly. +# +# This algorithm is neat, since it is quartically convergent - +# that means that the error goes as 4^(-iteration_count). +# +# In other words, one more step = four times the # of correct digits. + +sub RamanujanEI { + if (@_) { + my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. + + my $z_4_term = root4($_1 - pow4($z)); + my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); + + my $z_next_plus_1 = $z_next + $_1; + + my $a_next = pow4($z_next_plus_1) * $a - + $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); + $a_next = round($a_next); + return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; + + } else { # Seed the recurrence + my $a = $_6-$_4*root2($_2); + return [ $a, root2($_2)-$_1, $_8, inv($a)]; + } +} + + + +###################################################################### +# +# Main routine: +# +# + +my $iterResult = RamanujanEI(); +for (my $i=1; $i<$maxIterations; $i++) { + $iterResult = RamanujanEI($iterResult); +} +my $piValue = ${$iterResult}[-1]; +my $piStr = "" . $piValue; + +my $CHUNK = 32; +my $i = $CHUNK + 1; +print "Content-type: text/plain\r\n"; +print "Content-length: 570\r\n\r\n"; +print "Pi_512 :=\n"; +print " " . substr($piValue, 0, $i) . "\n"; +for (; $i < length($piValue) ; $i+=$CHUNK) { + print " " . substr($piValue, $i, $CHUNK) . "\n"; +} + diff --git a/targets/znews-ss-client/system/webpages/www5/cgi-bin/piComputeLib.pl b/targets/znews-ss-client/system/webpages/www5/cgi-bin/piComputeLib.pl index c14fe9400..23ce98e01 100644 --- a/targets/znews-ss-client/system/webpages/www5/cgi-bin/piComputeLib.pl +++ b/targets/znews-ss-client/system/webpages/www5/cgi-bin/piComputeLib.pl @@ -1,233 +1,233 @@ -#!/usr/bin/perl - -#map$x+=(-1)**$_*4/(2*$_+1),0..1e6;die$x - -use strict; -use Carp; -use Math::BigFloat; -use Class::Struct qw(struct); -use Data::Dumper; - -# With due homage to Mathsoft's site: -# http://www.mathsoft.com/asolve/constant/pi/pi.html - -# Set the global precision. Faster than passing it everywhichwhere. -my $precision = @ARGV>0?$ARGV[0]:10; - -# Set the iteration count. -my $maxIterations = @ARGV>1?$ARGV[1]:10; - -# Set the verbose debugging flag. -my $debugVerbose = 0; - -# Constants: -my $_1 = Math::BigFloat->new(1); -my $_2 = Math::BigFloat->new(2); -my $_3 = Math::BigFloat->new(3); -my $_4 = Math::BigFloat->new(4); -my $_6 = Math::BigFloat->new(6); -my $_8 = Math::BigFloat->new(8); -my $_239 = Math::BigFloat->new(239); -my $_half = Math::BigFloat->new(0.5); -my $_fifth = Math::BigFloat->new(0.2); -my $_25th = Math::BigFloat->new(0.04); -my $_239th = inv($_239); -my $_57121th = inv($_239*$_239); - - -# Utility methods: -sub div { - my $a = shift; - my $b = shift; - return new Math::BigFloat $a->copy()->fdiv($b,$precision); -} -sub inv { # Inverse (1/x) function. - my $a = shift; - return new Math::BigFloat $_1->copy()->fdiv($a,$precision); -} -sub root2 { - my $self = shift; - return new Math::BigFloat $self->copy()->fsqrt($precision); -} -sub root4 { - my $self = shift; - return root2(root2($self)); -} -sub pow4 { - my $self = shift; - my $square = round($self*$self); - return round($square*$square); -} -sub round { - my $self = shift; - return new Math::BigFloat $self->copy()->fround($precision); -} - - -# Method 1: - -# This gives Archimedes' approximation, -# 3+10/71 < Pi < 3+1/7 -# ...on the 4th iteration. - -sub BorchardtPfaff { - if (@_) { - my ($a,$b) = @{shift()}; # Retrieve the last iteration. - my $a_next = div( $_2*$a*$b, $a+$b ); - my $b_next = root2($a_next*$b); - return [ round($a_next), round($b_next) ]; - } else { # Seed the recurrence - return [ $_2*root2($_3), $_3 ]; - } -} - -# Method 2: - -# This uses Borwein's AGM method to compute Pi very quickly. -# The 'AGM' is short for the iterated arithmetic-geometric mean; -# which was looked at by Lagrange and Gauss way back in 1799. -# We basically look at the tuple [a,b] which holds the arithmetic -# and geometric means of the previous iteration: -# a[n+1] = (a[n] + b[n])/2 // Arithmetic mean -# b[n+1] = sqrt(a[n] * b[n]) // Geometric mean -# -# This algorithm is neat, since it is quadratically convergent - -# that means that the error goes as 2^(-iteration_count). -# -# In other words, one more step = twice the # of correct digits. - -sub BorweinAGM { - if (@_) { - my ($a,$b,$pi) = @{shift()}; # Retrieve the last iteration. - - my $sqrt_a = root2($a); - my $inv_sqrt_a = inv($sqrt_a); - my $b_plus_1 = $b+$_1; - - my $a_next = $_half * ($sqrt_a+$inv_sqrt_a); - my $b_next = div( $b*$sqrt_a+$inv_sqrt_a , $b_plus_1 ); - my $pi_next = $pi*div( $a_next+$_1 , $b_next+$_1 ); - return [ round($a_next), round($b_next), round($pi_next) ]; - - } else { # Seed the recurrence - my $a0 = root2($_2); - my $pi0 = $_2+root2($_2); - my $b1 = root2($a0); # = root4($_2) - my $a1 = $_half * ($b1 + inv($b1)); - - return [ round($a1), round($b1), round($pi0 * div($a1 + $_1, $b1 + $_1)) ]; - } -} - -# Method 3: - -# The arctangent approximation, as determined by Machin (1706). -# Pi = 4(4 * arctan(1/5) - arctan(1/239)), -# ...where arctan(x) = sum( (-1)^k/(2*k+1)*x^(2*k+1), x=0..infinity). - -sub ArctanPi { - if (@_) { - my ($k, $atan5, $atan239, $denom5, $denom239, $pi) = @{shift()}; # Retrieve the last iteration. - - $k++; - my $parity=$k & 1; - $denom5 = $denom5 * $_25th; - - my $inv_2_k_plus_1='Math::BigFloat'->new(2*$k+1); - - my $term5 = div($denom5, $inv_2_k_plus_1 ); - $denom239 = $denom239 * $_57121th; - - my $term239 = div($denom239, $inv_2_k_plus_1 ); - $atan5 = $parity ? $atan5 - $term5 : $atan5 + $term5; - $atan239 = $parity ? $atan239 - $term239 : $atan239 + $term239; - my $pi = $_4*($_4*$atan5 - $atan239); - - return [ $k, round($atan5), round($atan239), - round($denom5), round($denom239), round($pi) ]; - } else { # Seed the recurrence - my ($k, $atan5, $atan239) = (0, $_fifth, $_239th); - return [ $k, $atan5, $atan239, $atan5, $atan239, $_4*($_4*$atan5 - $atan239)]; - } -} - -# Method 4: - -# This uses Ramanujan's elliptic integral-based technique to -# compute Pi monstrously quickly. -# -# This algorithm is neat, since it is quartically convergent - -# that means that the error goes as 4^(-iteration_count). -# -# In other words, one more step = four times the # of correct digits. - -sub RamanujanEI { - if (@_) { - my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. - - my $z_4_term = root4($_1 - pow4($z)); - my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); - - my $z_next_plus_1 = $z_next + $_1; - - my $a_next = pow4($z_next_plus_1) * $a - - $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); - $a_next = round($a_next); - return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; - - } else { # Seed the recurrence - my $a = $_6-$_4*root2($_2); - return [ $a, root2($_2)-$_1, $_8, inv($a)]; - } -} - - - -###################################################################### -# -# Main routine: -# -# - -my $methods = ["BorchardtPfaff", "ArctanPi", "BorweinAGM", "RamanujanEI" ]; - -my $longestMethodLen=0; -foreach my $method (@{$methods}) { - $longestMethodLen = length($method) if length($method) > $longestMethodLen; -} - -my $pis = [ BorchardtPfaff(), ArctanPi(), BorweinAGM(), RamanujanEI() ]; - -for (my $i=0; $i<$maxIterations; $i++) { - print "Iteration $i:\n"; - if (!$debugVerbose) { - for (my $j=0; $j<@{$methods}; $j++) { - - # The following piece of line noise is equivalent to the - # STL C++, " - - # piValue = pis[j].last(); - - # ", if the declaration for pis is: - - # std::vector > pis; - # - - my $methodName = ${$methods}[$j]; - my $piValue = ${${$pis}[$j]}[-1]; - print ${$methods}[$j] . ": " . - ' ' x ($longestMethodLen - length($methodName)) . - $piValue . "\n"; - } - print "\n"; - } - print(Dumper($pis)) if $debugVerbose; - - last if $i+1 == $maxIterations; - - $pis = [ BorchardtPfaff(${$pis}[0]), - ArctanPi(${$pis}[1]), - BorweinAGM(${$pis}[2]), - RamanujanEI(${$pis}[3]) ]; -} - +#!/usr/bin/perl + +#map$x+=(-1)**$_*4/(2*$_+1),0..1e6;die$x + +use strict; +use Carp; +use Math::BigFloat; +use Class::Struct qw(struct); +use Data::Dumper; + +# With due homage to Mathsoft's site: +# http://www.mathsoft.com/asolve/constant/pi/pi.html + +# Set the global precision. Faster than passing it everywhichwhere. +my $precision = @ARGV>0?$ARGV[0]:10; + +# Set the iteration count. +my $maxIterations = @ARGV>1?$ARGV[1]:10; + +# Set the verbose debugging flag. +my $debugVerbose = 0; + +# Constants: +my $_1 = Math::BigFloat->new(1); +my $_2 = Math::BigFloat->new(2); +my $_3 = Math::BigFloat->new(3); +my $_4 = Math::BigFloat->new(4); +my $_6 = Math::BigFloat->new(6); +my $_8 = Math::BigFloat->new(8); +my $_239 = Math::BigFloat->new(239); +my $_half = Math::BigFloat->new(0.5); +my $_fifth = Math::BigFloat->new(0.2); +my $_25th = Math::BigFloat->new(0.04); +my $_239th = inv($_239); +my $_57121th = inv($_239*$_239); + + +# Utility methods: +sub div { + my $a = shift; + my $b = shift; + return new Math::BigFloat $a->copy()->fdiv($b,$precision); +} +sub inv { # Inverse (1/x) function. + my $a = shift; + return new Math::BigFloat $_1->copy()->fdiv($a,$precision); +} +sub root2 { + my $self = shift; + return new Math::BigFloat $self->copy()->fsqrt($precision); +} +sub root4 { + my $self = shift; + return root2(root2($self)); +} +sub pow4 { + my $self = shift; + my $square = round($self*$self); + return round($square*$square); +} +sub round { + my $self = shift; + return new Math::BigFloat $self->copy()->fround($precision); +} + + +# Method 1: + +# This gives Archimedes' approximation, +# 3+10/71 < Pi < 3+1/7 +# ...on the 4th iteration. + +sub BorchardtPfaff { + if (@_) { + my ($a,$b) = @{shift()}; # Retrieve the last iteration. + my $a_next = div( $_2*$a*$b, $a+$b ); + my $b_next = root2($a_next*$b); + return [ round($a_next), round($b_next) ]; + } else { # Seed the recurrence + return [ $_2*root2($_3), $_3 ]; + } +} + +# Method 2: + +# This uses Borwein's AGM method to compute Pi very quickly. +# The 'AGM' is short for the iterated arithmetic-geometric mean; +# which was looked at by Lagrange and Gauss way back in 1799. +# We basically look at the tuple [a,b] which holds the arithmetic +# and geometric means of the previous iteration: +# a[n+1] = (a[n] + b[n])/2 // Arithmetic mean +# b[n+1] = sqrt(a[n] * b[n]) // Geometric mean +# +# This algorithm is neat, since it is quadratically convergent - +# that means that the error goes as 2^(-iteration_count). +# +# In other words, one more step = twice the # of correct digits. + +sub BorweinAGM { + if (@_) { + my ($a,$b,$pi) = @{shift()}; # Retrieve the last iteration. + + my $sqrt_a = root2($a); + my $inv_sqrt_a = inv($sqrt_a); + my $b_plus_1 = $b+$_1; + + my $a_next = $_half * ($sqrt_a+$inv_sqrt_a); + my $b_next = div( $b*$sqrt_a+$inv_sqrt_a , $b_plus_1 ); + my $pi_next = $pi*div( $a_next+$_1 , $b_next+$_1 ); + return [ round($a_next), round($b_next), round($pi_next) ]; + + } else { # Seed the recurrence + my $a0 = root2($_2); + my $pi0 = $_2+root2($_2); + my $b1 = root2($a0); # = root4($_2) + my $a1 = $_half * ($b1 + inv($b1)); + + return [ round($a1), round($b1), round($pi0 * div($a1 + $_1, $b1 + $_1)) ]; + } +} + +# Method 3: + +# The arctangent approximation, as determined by Machin (1706). +# Pi = 4(4 * arctan(1/5) - arctan(1/239)), +# ...where arctan(x) = sum( (-1)^k/(2*k+1)*x^(2*k+1), x=0..infinity). + +sub ArctanPi { + if (@_) { + my ($k, $atan5, $atan239, $denom5, $denom239, $pi) = @{shift()}; # Retrieve the last iteration. + + $k++; + my $parity=$k & 1; + $denom5 = $denom5 * $_25th; + + my $inv_2_k_plus_1='Math::BigFloat'->new(2*$k+1); + + my $term5 = div($denom5, $inv_2_k_plus_1 ); + $denom239 = $denom239 * $_57121th; + + my $term239 = div($denom239, $inv_2_k_plus_1 ); + $atan5 = $parity ? $atan5 - $term5 : $atan5 + $term5; + $atan239 = $parity ? $atan239 - $term239 : $atan239 + $term239; + my $pi = $_4*($_4*$atan5 - $atan239); + + return [ $k, round($atan5), round($atan239), + round($denom5), round($denom239), round($pi) ]; + } else { # Seed the recurrence + my ($k, $atan5, $atan239) = (0, $_fifth, $_239th); + return [ $k, $atan5, $atan239, $atan5, $atan239, $_4*($_4*$atan5 - $atan239)]; + } +} + +# Method 4: + +# This uses Ramanujan's elliptic integral-based technique to +# compute Pi monstrously quickly. +# +# This algorithm is neat, since it is quartically convergent - +# that means that the error goes as 4^(-iteration_count). +# +# In other words, one more step = four times the # of correct digits. + +sub RamanujanEI { + if (@_) { + my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. + + my $z_4_term = root4($_1 - pow4($z)); + my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); + + my $z_next_plus_1 = $z_next + $_1; + + my $a_next = pow4($z_next_plus_1) * $a - + $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); + $a_next = round($a_next); + return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; + + } else { # Seed the recurrence + my $a = $_6-$_4*root2($_2); + return [ $a, root2($_2)-$_1, $_8, inv($a)]; + } +} + + + +###################################################################### +# +# Main routine: +# +# + +my $methods = ["BorchardtPfaff", "ArctanPi", "BorweinAGM", "RamanujanEI" ]; + +my $longestMethodLen=0; +foreach my $method (@{$methods}) { + $longestMethodLen = length($method) if length($method) > $longestMethodLen; +} + +my $pis = [ BorchardtPfaff(), ArctanPi(), BorweinAGM(), RamanujanEI() ]; + +for (my $i=0; $i<$maxIterations; $i++) { + print "Iteration $i:\n"; + if (!$debugVerbose) { + for (my $j=0; $j<@{$methods}; $j++) { + + # The following piece of line noise is equivalent to the + # STL C++, " + + # piValue = pis[j].last(); + + # ", if the declaration for pis is: + + # std::vector > pis; + # + + my $methodName = ${$methods}[$j]; + my $piValue = ${${$pis}[$j]}[-1]; + print ${$methods}[$j] . ": " . + ' ' x ($longestMethodLen - length($methodName)) . + $piValue . "\n"; + } + print "\n"; + } + print(Dumper($pis)) if $debugVerbose; + + last if $i+1 == $maxIterations; + + $pis = [ BorchardtPfaff(${$pis}[0]), + ArctanPi(${$pis}[1]), + BorweinAGM(${$pis}[2]), + RamanujanEI(${$pis}[3]) ]; +} + diff --git a/targets/znews-ss-client/system/webpages/www5/index.php b/targets/znews-ss-client/system/webpages/www5/index.php index 6c66bd469..b3b52ea5e 100644 --- a/targets/znews-ss-client/system/webpages/www5/index.php +++ b/targets/znews-ss-client/system/webpages/www5/index.php @@ -1,84 +1,84 @@ - 1 && time()%$content == 0) { - echo << - -Please come back... - - -I (the server) am swamped right now!!
-Please kindly come back in a couple of minutes.
-Sorry for the inconvenience, and thanks for understanding! - - -REJECT; - exit(); -} - -/* -$mysql_url = ''; -$mysql_user = ''; -$mysql_password = ''; -$mysql_db = ''; - -$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) - or die('Could not connect: ' . mysql_error()); - -$mydb = mysql_select_db($mysql_db, $link); -if(!$mydb) { - die('Could not select Test database: ' . mysql_error()); -} - -// Performing SQL query -$query = "SELECT COUNT(*) FROM cur"; -$result = mysql_query($query, $link) - or die('Query COUNT failed: ' . mysql_error()); -$row = mysql_fetch_row($result); -if ($row != false) { - $numItems = $row[0]; -} - -$idx = rand(1, $numItems); -$query = "SELECT cur_text FROM cur LIMIT $idx,1"; -$result = mysql_query($query, $link) - or die('Query item $idx failed: ' . mysql_error()); -$row = mysql_fetch_row($result); -if($row != false) { - $text = $row[0]; -} -*/ -$idx = 0; -$text = ""; - -echo << - -Somewhere Over the Rainbow - - - -

Z.com News - Hello World! (High-fidelity Settings)

-This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. - - - - -END - -?> + 1 && time()%$content == 0) { + echo << + +Please come back... + + +I (the server) am swamped right now!!
+Please kindly come back in a couple of minutes.
+Sorry for the inconvenience, and thanks for understanding! + + +REJECT; + exit(); +} + +/* +$mysql_url = ''; +$mysql_user = ''; +$mysql_password = ''; +$mysql_db = ''; + +$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) + or die('Could not connect: ' . mysql_error()); + +$mydb = mysql_select_db($mysql_db, $link); +if(!$mydb) { + die('Could not select Test database: ' . mysql_error()); +} + +// Performing SQL query +$query = "SELECT COUNT(*) FROM cur"; +$result = mysql_query($query, $link) + or die('Query COUNT failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if ($row != false) { + $numItems = $row[0]; +} + +$idx = rand(1, $numItems); +$query = "SELECT cur_text FROM cur LIMIT $idx,1"; +$result = mysql_query($query, $link) + or die('Query item $idx failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if($row != false) { + $text = $row[0]; +} +*/ +$idx = 0; +$text = ""; + +echo << + +Somewhere Over the Rainbow + + + +

Z.com News - Hello World! (High-fidelity Settings)

+This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. + + + + +END + +?> diff --git a/targets/znews-ss-prediction/log/topic/effectorBus.log b/targets/znews-ss-prediction/log/topic/effectorBus.log index a70dc671f..51df60945 100644 --- a/targets/znews-ss-prediction/log/topic/effectorBus.log +++ b/targets/znews-ss-prediction/log/topic/effectorBus.log @@ -1 +1 @@ -{location=10.0.2.15, name=blackhole, msg-created=1347630591011, action=EXECUTE, channel=topic/effectorBus, msg-sent=1347630591011, argument_size=1, argument_0=client=10.0.2.2} +{location=10.0.2.15, name=blackhole, msg-created=1347630591011, action=EXECUTE, channel=topic/effectorBus, msg-sent=1347630591011, argument_size=1, argument_0=client=10.0.2.2} diff --git a/targets/znews-ss-prediction/log/topic/gaugeBus.log b/targets/znews-ss-prediction/log/topic/gaugeBus.log index 92bf5ae39..90ece3525 100644 --- a/targets/znews-ss-prediction/log/topic/gaugeBus.log +++ b/targets/znews-ss-prediction/log/topic/gaugeBus.log @@ -1,191 +1,191 @@ -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiagnosisGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness::x, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=DG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=DiagnosisGaugeT} -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.End2EndRespTimeGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=end2endRespTime(delegate.oracle)::c0.experRespTime, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=EERTG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=ResponseTimeGaugeT} -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.EchoGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness(c1)::c0.maliciousness, setupParam_size=3, mapping_1=maliciousness(c2)::c1.maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357101, action=CREATE, gaugeName=EG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630357101, gaugeType=MaliciousnessGaugeT} -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.2, mapping_0=load::s0.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357102, action=CREATE, gaugeName=LoG0, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357102, gaugeType=LoadGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357187, action=REPORT_CREATED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630357187, gaugeType=DiagnosisGaugeT} -{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357189, action=REPORT_CREATED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630357189, gaugeType=ResponseTimeGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357191, action=REPORT_CREATED, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630357191, gaugeType=MaliciousnessGaugeT} -{uid=LoadGaugeT0914094557193@10.0.2.2, beaconPer=20000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357193, action=REPORT_CREATED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630357193, gaugeType=LoadGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630377197, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630377197} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630387192, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387192} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630387194, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387194} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630387196, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387196} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630397201, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630397201} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630417198, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417198} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630417200, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417200} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630417202, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417202} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630417205, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417205} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630437209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630437209} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630447204, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447204} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630447206, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447206} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630447209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447209} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=DiagnosisGaugeT} -{uid=LoadGaugeT0914094557193@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=LoadGaugeT} -{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454372, action=REPORT_CONFIGURED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630454372, gaugeType=ResponseTimeGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.ApacheTopGauge, mapping_6=reqServiceRate::s0.reqServiceRate, setupParam_2=beaconPeriod:long=20000, mapping_5=pageHit::s0.lastPageHit, setupParam_1=targetIP=10.0.2.15, mapping_4=numReqsSuccess::conn0.numReqsSuccess, mapping_0=byteServiceRate::s0.byteServiceRate, mapping_3=numReqsServerError::conn0.numReqsServerError, mapping_2=numReqsRedirect::conn0.numReqsRedirect, setupParam_size=3, mapping_1=numReqsClientError::conn0.numReqsClientError, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454668, action=CREATE, gaugeName=ATG1, mapping_size=7, channel=topic/gaugeBus, msg-sent=1347630454668, gaugeType=ApacheTopGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiskIOGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=readRate::s0.diskReadRate, mapping_2=writeRate::s0.diskWriteRate, setupParam_size=3, mapping_1=transferRate::s0.diskXferRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454669, action=CREATE, gaugeName=DioG1, mapping_size=3, channel=topic/gaugeBus, msg-sent=1347630454669, gaugeType=DiskIOGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.FidelityGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.15, mapping_0=fidelity::s0.fidelity, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=FiG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=FidelityGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latency(10.0.2.2)::conn0.latency, setupParam_size=3, mapping_1=latency(phoenix)::conn1.latency, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=LatG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=LatencyGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latencyRate(10.0.2.2)::conn0.latencyRate, setupParam_size=3, mapping_1=latencyRate(phoenix)::conn1.latencyRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454671, action=CREATE, gaugeName=LatRoCG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454671, gaugeType=LatencyRateGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=load::s1.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454672, action=CREATE, gaugeName=LoG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454672, gaugeType=LoadGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630457213, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630457213} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630459410, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630459410, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460095, action=CONFIGURE, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460095, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460154, action=REPORT_CONFIGURED, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460154, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464412, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630464412, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464467, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464467, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464471, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469414, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630469414, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469510, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469510, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469511, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469511, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474415, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630474415, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474420, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.10000000000000002, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474420, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474421, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474421, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630477215, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477215} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630477217, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477217} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630477223, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477223} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479417, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630479418, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479492, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479492, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479493, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630479518, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630479518} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484419, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630484419, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484508, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484508, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484509, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484509, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489421, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630489421, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494423, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630494423, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494437, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494437, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494438, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494438, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630497221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630497221} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499425, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630499425, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499449, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499449, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499450, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499450, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504427, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630504427, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504459, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504460, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504460, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630507221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507221} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630507229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507229} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509429, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630509429, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509470, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509471, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630509530, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630509530} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514430, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630514431, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514481, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514482, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630517225, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630517225} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519433, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630519433, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524435, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630524435, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524504, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524505, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524505, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529437, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630529437, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534438, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630534438, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630537227, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537227} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630537229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537229} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630537235, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537235} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539441, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630539441, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630539542, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630539542} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544443, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630544443, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544547, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544548, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544548, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549446, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630549446, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554448, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630554449, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554470, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554471, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630557233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630557233} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559451, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630559451, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564453, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630564453, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630567233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567233} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630567241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567241} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569456, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630569456, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630569557, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630569557} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574458, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630574458, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574516, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574516, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574517, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574517, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630577237, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630577237} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579460, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630579460, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584463, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630584463, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589465, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630589465, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630594467, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630594467, value_size=2, gaugeType=DiagnosisGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630597239, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597239} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630597241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597241} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630597247, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597247} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599469, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630599469, value_size=2, gaugeType=DiagnosisGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630599570, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630599570} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604470, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630604470, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609473, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630609473, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614475, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630614475, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614481, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614482, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630617245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630617245} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619477, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630619477, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619493, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619494, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619494, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624478, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630624478, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630627245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627245} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630627253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627253} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629481, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630629481, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629511, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629511, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629512, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629512, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630629581, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630629581} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634483, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630634483, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634520, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634520, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634521, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634521, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630637249, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630637249} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639485, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630639485, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639530, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639530, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639531, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639531, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644487, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630644487, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649490, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630649490, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649547, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649548, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654492, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630654492, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630657251, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657251} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630657253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657253} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630657259, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657259} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659495, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630659495, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659564, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659565, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659565, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630659596, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630659596} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665048, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630665048, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670050, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630670050, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiagnosisGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness::x, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=DG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=DiagnosisGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.End2EndRespTimeGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=end2endRespTime(delegate.oracle)::c0.experRespTime, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=EERTG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=ResponseTimeGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.EchoGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness(c1)::c0.maliciousness, setupParam_size=3, mapping_1=maliciousness(c2)::c1.maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357101, action=CREATE, gaugeName=EG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630357101, gaugeType=MaliciousnessGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.2, mapping_0=load::s0.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357102, action=CREATE, gaugeName=LoG0, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357102, gaugeType=LoadGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357187, action=REPORT_CREATED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630357187, gaugeType=DiagnosisGaugeT} +{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357189, action=REPORT_CREATED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630357189, gaugeType=ResponseTimeGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357191, action=REPORT_CREATED, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630357191, gaugeType=MaliciousnessGaugeT} +{uid=LoadGaugeT0914094557193@10.0.2.2, beaconPer=20000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357193, action=REPORT_CREATED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630357193, gaugeType=LoadGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630377197, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630377197} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630387192, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387192} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630387194, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387194} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630387196, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387196} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630397201, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630397201} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630417198, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417198} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630417200, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417200} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630417202, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417202} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630417205, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417205} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630437209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630437209} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630447204, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447204} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630447206, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447206} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630447209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447209} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=DiagnosisGaugeT} +{uid=LoadGaugeT0914094557193@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=LoadGaugeT} +{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454372, action=REPORT_CONFIGURED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630454372, gaugeType=ResponseTimeGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.ApacheTopGauge, mapping_6=reqServiceRate::s0.reqServiceRate, setupParam_2=beaconPeriod:long=20000, mapping_5=pageHit::s0.lastPageHit, setupParam_1=targetIP=10.0.2.15, mapping_4=numReqsSuccess::conn0.numReqsSuccess, mapping_0=byteServiceRate::s0.byteServiceRate, mapping_3=numReqsServerError::conn0.numReqsServerError, mapping_2=numReqsRedirect::conn0.numReqsRedirect, setupParam_size=3, mapping_1=numReqsClientError::conn0.numReqsClientError, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454668, action=CREATE, gaugeName=ATG1, mapping_size=7, channel=topic/gaugeBus, msg-sent=1347630454668, gaugeType=ApacheTopGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiskIOGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=readRate::s0.diskReadRate, mapping_2=writeRate::s0.diskWriteRate, setupParam_size=3, mapping_1=transferRate::s0.diskXferRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454669, action=CREATE, gaugeName=DioG1, mapping_size=3, channel=topic/gaugeBus, msg-sent=1347630454669, gaugeType=DiskIOGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.FidelityGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.15, mapping_0=fidelity::s0.fidelity, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=FiG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=FidelityGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latency(10.0.2.2)::conn0.latency, setupParam_size=3, mapping_1=latency(phoenix)::conn1.latency, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=LatG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=LatencyGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latencyRate(10.0.2.2)::conn0.latencyRate, setupParam_size=3, mapping_1=latencyRate(phoenix)::conn1.latencyRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454671, action=CREATE, gaugeName=LatRoCG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454671, gaugeType=LatencyRateGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=load::s1.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454672, action=CREATE, gaugeName=LoG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454672, gaugeType=LoadGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630457213, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630457213} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630459410, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630459410, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460095, action=CONFIGURE, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460095, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460154, action=REPORT_CONFIGURED, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460154, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464412, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630464412, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464467, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464467, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464471, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469414, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630469414, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469510, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469510, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469511, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469511, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474415, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630474415, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474420, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.10000000000000002, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474420, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474421, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474421, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630477215, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477215} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630477217, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477217} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630477223, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477223} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479417, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630479418, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479492, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479492, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479493, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630479518, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630479518} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484419, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630484419, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484508, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484508, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484509, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484509, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489421, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630489421, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494423, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630494423, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494437, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494437, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494438, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494438, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630497221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630497221} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499425, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630499425, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499449, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499449, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499450, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499450, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504427, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630504427, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504459, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504460, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504460, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630507221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507221} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630507229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507229} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509429, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630509429, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509470, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509471, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630509530, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630509530} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514430, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630514431, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514481, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514482, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630517225, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630517225} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519433, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630519433, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524435, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630524435, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524504, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524505, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524505, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529437, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630529437, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534438, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630534438, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630537227, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537227} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630537229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537229} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630537235, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537235} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539441, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630539441, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630539542, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630539542} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544443, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630544443, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544547, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544548, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544548, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549446, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630549446, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554448, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630554449, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554470, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554471, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630557233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630557233} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559451, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630559451, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564453, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630564453, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630567233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567233} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630567241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567241} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569456, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630569456, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630569557, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630569557} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574458, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630574458, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574516, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574516, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574517, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574517, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630577237, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630577237} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579460, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630579460, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584463, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630584463, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589465, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630589465, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630594467, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630594467, value_size=2, gaugeType=DiagnosisGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630597239, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597239} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630597241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597241} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630597247, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597247} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599469, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630599469, value_size=2, gaugeType=DiagnosisGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630599570, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630599570} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604470, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630604470, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609473, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630609473, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614475, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630614475, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614481, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614482, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630617245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630617245} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619477, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630619477, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619493, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619494, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619494, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624478, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630624478, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630627245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627245} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630627253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627253} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629481, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630629481, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629511, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629511, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629512, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629512, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630629581, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630629581} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634483, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630634483, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634520, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634520, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634521, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634521, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630637249, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630637249} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639485, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630639485, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639530, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639530, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639531, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639531, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644487, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630644487, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649490, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630649490, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649547, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649548, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654492, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630654492, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630657251, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657251} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630657253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657253} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630657259, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657259} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659495, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630659495, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659564, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659565, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659565, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630659596, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630659596} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665048, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630665048, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670050, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630670050, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} diff --git a/targets/znews-ss-prediction/log/topic/rainbowHealth.log b/targets/znews-ss-prediction/log/topic/rainbowHealth.log index 33931f7a8..23bde129f 100644 --- a/targets/znews-ss-prediction/log/topic/rainbowHealth.log +++ b/targets/znews-ss-prediction/log/topic/rainbowHealth.log @@ -1,102 +1,102 @@ -{msg-created=1347630325763, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325773, txt=EventServiceManager initialized!} -{msg-created=1347630325789, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325789, txt=T[topic/rainbowHealth] +listener Oracle@10.0.2.2} -{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/rainbowHealth] +listener SystemDelegate@10.0.2.2} -{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/effectorBus] +listener SystemDelegate@10.0.2.2} -{msg-created=1347630351995, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351995, txt=T[topic/gaugeBus] +listener GaugeCoordinator@10.0.2.2} -{msg-created=1347630351996, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351996, txt=T[topic/rainbowHealth] +listener ModelManager@10.0.2.2} -{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/rainbowHealth] +listener del1} -{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/effectorBus] +listener del1} -{msg-created=1347630352014, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352014, txt=T[topic/gaugeBus] +listener ApacheTopGaugeT@10.0.2.2} -{msg-created=1347630352018, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352018, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT@10.0.2.2} -{msg-created=1347630352020, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352020, txt=T[topic/gaugeBus] +listener DiskIOGaugeT@10.0.2.2} -{msg-created=1347630352021, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352021, txt=T[topic/gaugeBus] +listener FidelityGaugeT@10.0.2.2} -{msg-created=1347630352022, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352022, txt=T[topic/gaugeBus] +listener LatencyGaugeT@10.0.2.2} -{msg-created=1347630352024, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352024, txt=T[topic/gaugeBus] +listener LatencyRateGaugeT@10.0.2.2} -{msg-created=1347630352025, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352025, txt=T[topic/gaugeBus] +listener LoadGaugeT@10.0.2.2} -{msg-created=1347630352026, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352026, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT@10.0.2.2} -{msg-created=1347630352031, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352031, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT@10.0.2.2} -{beaconPer=5000, id=del1, location=10.0.2.2, cloudT=DELEGATE, msg-created=1347630357039, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630357039} -{id=del1, location=10.0.2.2, msg-created=1347630357099, action=START, channel=topic/rainbowHealth, msg-sent=1347630357099} -{msg-created=1347630357187, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357187, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT0914094557185@10.0.2.2} -{msg-created=1347630357188, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357188, txt=G[DiagnosisGaugeT0914094557185@10.0.2.2] G - Diagnosis started.} -{msg-created=1347630357189, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357189, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} -{msg-created=1347630357190, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=T[topic/probeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} -{msg-created=1347630357190, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=G[ResponseTimeGaugeT0914094557188@10.0.2.2] G - End-End Resp Time started.} -{msg-created=1347630357191, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357191, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} -{msg-created=1347630357192, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} -{msg-created=1347630357192, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=G[MaliciousnessGaugeT0914094557191@10.0.2.2] G - Maliciousness started.} -{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/gaugeBus] +listener LoadGaugeT0914094557193@10.0.2.2} -{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/probeBus] +listener LoadGaugeT0914094557193@10.0.2.2} -{msg-created=1347630357193, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357194, txt=G[LoadGaugeT0914094557193@10.0.2.2] G - CPU Load started.} -{id=del1, msg-created=1347630362096, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630362096} -{id=del1, msg-created=1347630367196, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630367196} -{id=del1, msg-created=1347630372296, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630372296} -{id=del1, msg-created=1347630377297, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630377297} -{id=del1, msg-created=1347630382298, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630382298} -{id=del1, msg-created=1347630387299, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630387299} -{id=del1, msg-created=1347630392300, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630392300} -{id=del1, msg-created=1347630397301, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630397301} -{id=del1, msg-created=1347630402302, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630402302} -{id=del1, msg-created=1347630407303, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630407303} -{id=del1, msg-created=1347630412304, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630412304} -{id=del1, msg-created=1347630417305, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630417305} -{id=del1, msg-created=1347630422306, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630422306} -{id=del1, msg-created=1347630427307, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630427307} -{id=del1, msg-created=1347630432308, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630432308} -{id=del1, msg-created=1347630437309, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630437309} -{id=del1, msg-created=1347630442310, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630442310} -{id=del1, msg-created=1347630447311, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630447311} -{id=del1, msg-created=1347630452312, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630452312} -{location=10.0.2.2, msg-created=1347630454176, action=START_PROBES, channel=topic/rainbowHealth, msg-sent=1347630454176} -{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/rainbowHealth] +listener ProbeBusRelay@10.0.2.2} -{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/probeBus] +listener ProbeBusRelay@10.0.2.2} -{beaconPer=0, id=ProbeBusRelay@10.0.2.2, location=10.0.2.2, cloudT=PB_RELAY, msg-created=1347630454321, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630454321} -{msg-created=1347630454322, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454322, txt=[PBR] Rainbow Runtime - Probe Bus Relay started.} -{msg-created=1347630454370, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454370, txt=[PBR] IProbe ClientProxyProbe0@10.0.2.2:clientproxy added!} -{beaconPer=0, id=ClientProxyProbe0@10.0.2.2, probeK=JAVA, alias=clientproxy, location=10.0.2.2, cloudT=PROBE, msg-created=1347630454370, action=REPORT_CREATED, svcName=ClientProxyProbe0, channel=topic/rainbowHealth, msg-sent=1347630454370} -{id=del1, location=10.0.2.15, msg-created=1347630454667, action=START, channel=topic/rainbowHealth, msg-sent=1347630454667} -{id=del1, msg-created=1347630457373, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630457373} -{id=del1, location=10.0.2.15, msg-created=1347630459775, action=START, channel=topic/rainbowHealth, msg-sent=1347630459775} -{id=del1, msg-created=1347630462374, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630462374} -{id=del1, msg-created=1347630467375, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630467375} -{id=del1, msg-created=1347630472376, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630472376} -{id=del1, msg-created=1347630477377, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630477377} -{id=del1, msg-created=1347630482378, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630482378} -{id=del1, msg-created=1347630487379, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630487379} -{id=del1, msg-created=1347630492380, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630492380} -{id=del1, msg-created=1347630497381, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630497381} -{id=del1, msg-created=1347630502382, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630502382} -{id=del1, msg-created=1347630507383, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630507383} -{id=del1, msg-created=1347630512384, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630512384} -{id=del1, msg-created=1347630517385, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630517385} -{id=del1, msg-created=1347630522386, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630522386} -{id=del1, msg-created=1347630527387, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630527387} -{id=del1, msg-created=1347630532388, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630532388} -{id=del1, msg-created=1347630537389, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630537389} -{id=del1, msg-created=1347630542390, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630542390} -{id=del1, msg-created=1347630547391, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630547391} -{id=del1, msg-created=1347630552392, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630552392} -{id=del1, msg-created=1347630557393, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630557393} -{id=del1, msg-created=1347630562394, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630562394} -{id=del1, msg-created=1347630567395, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630567395} -{id=del1, msg-created=1347630572396, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630572396} -{id=del1, msg-created=1347630577397, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630577397} -{id=del1, msg-created=1347630582398, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630582398} -{id=del1, msg-created=1347630587399, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630587399} -{id=del1, msg-created=1347630592400, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630592400} -{id=del1, msg-created=1347630597401, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630597401} -{id=del1, msg-created=1347630602402, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630602402} -{id=del1, msg-created=1347630607403, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630607403} -{id=del1, msg-created=1347630612404, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630612404} -{id=del1, msg-created=1347630617405, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630617405} -{id=del1, msg-created=1347630622406, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630622406} -{id=del1, msg-created=1347630627407, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630627407} -{id=del1, msg-created=1347630632408, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630632408} -{id=del1, msg-created=1347630637409, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630637409} -{id=del1, msg-created=1347630642410, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630642410} -{id=del1, msg-created=1347630647411, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630647411} -{id=del1, msg-created=1347630652412, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630652412} -{id=del1, msg-created=1347630657413, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630657413} -{id=del1, msg-created=1347630662414, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630662414} -{id=del1, msg-created=1347630667415, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630667415} -{id=del1, msg-created=1347630672416, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630672416} +{msg-created=1347630325763, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325773, txt=EventServiceManager initialized!} +{msg-created=1347630325789, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325789, txt=T[topic/rainbowHealth] +listener Oracle@10.0.2.2} +{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/rainbowHealth] +listener SystemDelegate@10.0.2.2} +{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/effectorBus] +listener SystemDelegate@10.0.2.2} +{msg-created=1347630351995, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351995, txt=T[topic/gaugeBus] +listener GaugeCoordinator@10.0.2.2} +{msg-created=1347630351996, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351996, txt=T[topic/rainbowHealth] +listener ModelManager@10.0.2.2} +{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/rainbowHealth] +listener del1} +{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/effectorBus] +listener del1} +{msg-created=1347630352014, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352014, txt=T[topic/gaugeBus] +listener ApacheTopGaugeT@10.0.2.2} +{msg-created=1347630352018, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352018, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT@10.0.2.2} +{msg-created=1347630352020, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352020, txt=T[topic/gaugeBus] +listener DiskIOGaugeT@10.0.2.2} +{msg-created=1347630352021, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352021, txt=T[topic/gaugeBus] +listener FidelityGaugeT@10.0.2.2} +{msg-created=1347630352022, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352022, txt=T[topic/gaugeBus] +listener LatencyGaugeT@10.0.2.2} +{msg-created=1347630352024, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352024, txt=T[topic/gaugeBus] +listener LatencyRateGaugeT@10.0.2.2} +{msg-created=1347630352025, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352025, txt=T[topic/gaugeBus] +listener LoadGaugeT@10.0.2.2} +{msg-created=1347630352026, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352026, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT@10.0.2.2} +{msg-created=1347630352031, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352031, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT@10.0.2.2} +{beaconPer=5000, id=del1, location=10.0.2.2, cloudT=DELEGATE, msg-created=1347630357039, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630357039} +{id=del1, location=10.0.2.2, msg-created=1347630357099, action=START, channel=topic/rainbowHealth, msg-sent=1347630357099} +{msg-created=1347630357187, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357187, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT0914094557185@10.0.2.2} +{msg-created=1347630357188, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357188, txt=G[DiagnosisGaugeT0914094557185@10.0.2.2] G - Diagnosis started.} +{msg-created=1347630357189, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357189, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} +{msg-created=1347630357190, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=T[topic/probeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} +{msg-created=1347630357190, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=G[ResponseTimeGaugeT0914094557188@10.0.2.2] G - End-End Resp Time started.} +{msg-created=1347630357191, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357191, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} +{msg-created=1347630357192, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} +{msg-created=1347630357192, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=G[MaliciousnessGaugeT0914094557191@10.0.2.2] G - Maliciousness started.} +{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/gaugeBus] +listener LoadGaugeT0914094557193@10.0.2.2} +{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/probeBus] +listener LoadGaugeT0914094557193@10.0.2.2} +{msg-created=1347630357193, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357194, txt=G[LoadGaugeT0914094557193@10.0.2.2] G - CPU Load started.} +{id=del1, msg-created=1347630362096, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630362096} +{id=del1, msg-created=1347630367196, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630367196} +{id=del1, msg-created=1347630372296, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630372296} +{id=del1, msg-created=1347630377297, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630377297} +{id=del1, msg-created=1347630382298, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630382298} +{id=del1, msg-created=1347630387299, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630387299} +{id=del1, msg-created=1347630392300, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630392300} +{id=del1, msg-created=1347630397301, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630397301} +{id=del1, msg-created=1347630402302, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630402302} +{id=del1, msg-created=1347630407303, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630407303} +{id=del1, msg-created=1347630412304, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630412304} +{id=del1, msg-created=1347630417305, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630417305} +{id=del1, msg-created=1347630422306, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630422306} +{id=del1, msg-created=1347630427307, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630427307} +{id=del1, msg-created=1347630432308, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630432308} +{id=del1, msg-created=1347630437309, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630437309} +{id=del1, msg-created=1347630442310, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630442310} +{id=del1, msg-created=1347630447311, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630447311} +{id=del1, msg-created=1347630452312, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630452312} +{location=10.0.2.2, msg-created=1347630454176, action=START_PROBES, channel=topic/rainbowHealth, msg-sent=1347630454176} +{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/rainbowHealth] +listener ProbeBusRelay@10.0.2.2} +{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/probeBus] +listener ProbeBusRelay@10.0.2.2} +{beaconPer=0, id=ProbeBusRelay@10.0.2.2, location=10.0.2.2, cloudT=PB_RELAY, msg-created=1347630454321, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630454321} +{msg-created=1347630454322, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454322, txt=[PBR] Rainbow Runtime - Probe Bus Relay started.} +{msg-created=1347630454370, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454370, txt=[PBR] IProbe ClientProxyProbe0@10.0.2.2:clientproxy added!} +{beaconPer=0, id=ClientProxyProbe0@10.0.2.2, probeK=JAVA, alias=clientproxy, location=10.0.2.2, cloudT=PROBE, msg-created=1347630454370, action=REPORT_CREATED, svcName=ClientProxyProbe0, channel=topic/rainbowHealth, msg-sent=1347630454370} +{id=del1, location=10.0.2.15, msg-created=1347630454667, action=START, channel=topic/rainbowHealth, msg-sent=1347630454667} +{id=del1, msg-created=1347630457373, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630457373} +{id=del1, location=10.0.2.15, msg-created=1347630459775, action=START, channel=topic/rainbowHealth, msg-sent=1347630459775} +{id=del1, msg-created=1347630462374, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630462374} +{id=del1, msg-created=1347630467375, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630467375} +{id=del1, msg-created=1347630472376, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630472376} +{id=del1, msg-created=1347630477377, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630477377} +{id=del1, msg-created=1347630482378, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630482378} +{id=del1, msg-created=1347630487379, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630487379} +{id=del1, msg-created=1347630492380, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630492380} +{id=del1, msg-created=1347630497381, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630497381} +{id=del1, msg-created=1347630502382, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630502382} +{id=del1, msg-created=1347630507383, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630507383} +{id=del1, msg-created=1347630512384, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630512384} +{id=del1, msg-created=1347630517385, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630517385} +{id=del1, msg-created=1347630522386, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630522386} +{id=del1, msg-created=1347630527387, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630527387} +{id=del1, msg-created=1347630532388, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630532388} +{id=del1, msg-created=1347630537389, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630537389} +{id=del1, msg-created=1347630542390, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630542390} +{id=del1, msg-created=1347630547391, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630547391} +{id=del1, msg-created=1347630552392, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630552392} +{id=del1, msg-created=1347630557393, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630557393} +{id=del1, msg-created=1347630562394, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630562394} +{id=del1, msg-created=1347630567395, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630567395} +{id=del1, msg-created=1347630572396, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630572396} +{id=del1, msg-created=1347630577397, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630577397} +{id=del1, msg-created=1347630582398, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630582398} +{id=del1, msg-created=1347630587399, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630587399} +{id=del1, msg-created=1347630592400, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630592400} +{id=del1, msg-created=1347630597401, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630597401} +{id=del1, msg-created=1347630602402, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630602402} +{id=del1, msg-created=1347630607403, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630607403} +{id=del1, msg-created=1347630612404, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630612404} +{id=del1, msg-created=1347630617405, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630617405} +{id=del1, msg-created=1347630622406, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630622406} +{id=del1, msg-created=1347630627407, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630627407} +{id=del1, msg-created=1347630632408, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630632408} +{id=del1, msg-created=1347630637409, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630637409} +{id=del1, msg-created=1347630642410, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630642410} +{id=del1, msg-created=1347630647411, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630647411} +{id=del1, msg-created=1347630652412, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630652412} +{id=del1, msg-created=1347630657413, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630657413} +{id=del1, msg-created=1347630662414, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630662414} +{id=del1, msg-created=1347630667415, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630667415} +{id=del1, msg-created=1347630672416, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630672416} diff --git a/targets/znews-ss-prediction/model/DoSFam.acme b/targets/znews-ss-prediction/model/DoSFam.acme index 517612eea..2e54d6974 100644 --- a/targets/znews-ss-prediction/model/DoSFam.acme +++ b/targets/znews-ss-prediction/model/DoSFam.acme @@ -1,46 +1,46 @@ -Family DoSFam = { - - Element Type PotentiallyMaliciousT = { - - Property deploymentLocation : string; - - Property maliciousness : float << default : float = 0.0; >> ; - - } - - Element Type MaliciousT extends PotentiallyMaliciousT with { - rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; - } - - Element Type SuspiciousT extends PotentiallyMaliciousT with { - rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD && maliciousness <= MALICIOUS_THRESHOLD; - } - - Element Type NormalT extends PotentiallyMaliciousT with { - rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; - - Element Type BlackholerT = { - - Property blackholed : Set {string} << default : Set {string} = {}; >> ; - - } - Port Type BlackholedPortT = { - - Property isBlackholed : boolean = true; - - } - - Port Type CaptchaPortT = { - Property captchaEnabled : boolean << default : boolean = false;>>; - } - - Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; - Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; - rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | - exists bh : BlackholerT in self.COMPONENTS | - contains(c.deploymentLocation, bh.blackholed); - rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.components | - forall ip : string in lb.blackholed | - forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | - c.maliciousness > self.MALICIOUS_THRESHOLD; +Family DoSFam = { + + Element Type PotentiallyMaliciousT = { + + Property deploymentLocation : string; + + Property maliciousness : float << default : float = 0.0; >> ; + + } + + Element Type MaliciousT extends PotentiallyMaliciousT with { + rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; + } + + Element Type SuspiciousT extends PotentiallyMaliciousT with { + rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD && maliciousness <= MALICIOUS_THRESHOLD; + } + + Element Type NormalT extends PotentiallyMaliciousT with { + rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; + + Element Type BlackholerT = { + + Property blackholed : Set {string} << default : Set {string} = {}; >> ; + + } + Port Type BlackholedPortT = { + + Property isBlackholed : boolean = true; + + } + + Port Type CaptchaPortT = { + Property captchaEnabled : boolean << default : boolean = false;>>; + } + + Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; + Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; + rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | + exists bh : BlackholerT in self.COMPONENTS | + contains(c.deploymentLocation, bh.blackholed); + rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.components | + forall ip : string in lb.blackholed | + forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | + c.maliciousness > self.MALICIOUS_THRESHOLD; } \ No newline at end of file diff --git a/targets/znews-ss-prediction/model/TargetEnv.acme b/targets/znews-ss-prediction/model/TargetEnv.acme index 4331c55b7..2ec6be259 100644 --- a/targets/znews-ss-prediction/model/TargetEnv.acme +++ b/targets/znews-ss-prediction/model/TargetEnv.acme @@ -1,4 +1,4 @@ -System TargetEnv = { - -} - +System TargetEnv = { + +} + diff --git a/targets/znews-ss-prediction/model/TargetEnvType.acme b/targets/znews-ss-prediction/model/TargetEnvType.acme index a91a99173..91e499a0e 100644 --- a/targets/znews-ss-prediction/model/TargetEnvType.acme +++ b/targets/znews-ss-prediction/model/TargetEnvType.acme @@ -1,67 +1,67 @@ -Family EnvType = { - - Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; - - Role Type ArchRoleT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type PartPortT = { - - } - Component Type ArchElementT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type NetworkRoleT = { - - } - Connector Type MappingT = { - - } - Role Type PartRoleT = { - - } - Connector Type EdgeT = { - - Property bandwidthAvg : ResourceStatePropT; - - Property capacity : ResourceStatePropT; - - } - Component Type NodeT = { - - Property cpuOverall : ResourceStatePropT; - - Property memoryMain : ResourceStatePropT; - - Property storageLocal : ResourceStatePropT; - - Property socketPool : ResourceStatePropT; - - Property batteryOverall : ResourceStatePropT; - - } - Port Type NetworkPortT = { - - } - Connector Type ArchConnT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type ArchPortT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type ContainerRoleT = { - - } - Port Type ContainmentPortT = { - - } -} - +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type PartPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type NetworkRoleT = { + + } + Connector Type MappingT = { + + } + Role Type PartRoleT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Port Type NetworkPortT = { + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type ContainerRoleT = { + + } + Port Type ContainmentPortT = { + + } +} + diff --git a/targets/znews-ss-prediction/model/TargetEnvType.mtd b/targets/znews-ss-prediction/model/TargetEnvType.mtd index 6817ebfa8..9d8d87f85 100644 --- a/targets/znews-ss-prediction/model/TargetEnvType.mtd +++ b/targets/znews-ss-prediction/model/TargetEnvType.mtd @@ -1,475 +1,475 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews-ss-prediction/model/ZNewsSys.acme b/targets/znews-ss-prediction/model/ZNewsSys.acme index 91fe005e2..a6ac63fff 100644 --- a/targets/znews-ss-prediction/model/ZNewsSys.acme +++ b/targets/znews-ss-prediction/model/ZNewsSys.acme @@ -1,612 +1,612 @@ -Family EnvType = { - - Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; - Port Type PartPortT = { - - } - Port Type NetworkPortT = { - - } - Port Type ArchPortT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } - Port Type ContainmentPortT = { - - } - Component Type ArchElementT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } - Component Type NodeT = { - - Property cpuOverall : ResourceStatePropT; - - Property memoryMain : ResourceStatePropT; - - Property storageLocal : ResourceStatePropT; - - Property socketPool : ResourceStatePropT; - - Property batteryOverall : ResourceStatePropT; - - } - Role Type ArchRoleT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } - Role Type NetworkRoleT = { - - } - Role Type PartRoleT = { - - } - Role Type ContainerRoleT = { - - } - Connector Type MappingT = { - - } - Connector Type EdgeT = { - - Property bandwidthAvg : ResourceStatePropT; - - Property capacity : ResourceStatePropT; - - } - Connector Type ArchConnT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } -} - -Family ZNewsFam extends EnvType with { - - Port Type HttpPortT extends ArchPortT with { - - } - Port Type ProxyForwardPortT extends ArchPortT with { - - } - Port Type HttpReqPortT extends ArchPortT with { - - } - Port Type SqlReqPort extends ArchPortT with { - - } - Port Type SqlRecPort extends ArchPortT with { - - } - Component Type ProxyT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - } - Component Type ServerT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - Property reqServiceRate : float << default : float = 0.0; >> ; - - Property byteServiceRate : float << default : float = 0.0; >> ; - - Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; - - Property cost : float << default : float = 1.0; >> ; - - Property lastPageHit : Record [uri : string; cnt : int; kbytes : float; ]; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - Component Type ClientT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property experRespTime : float << default : float = 0.0; >> ; - - Property reqRate : float << default : float = 0.0; >> ; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - Component Type DBT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "locahost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - } - Role Type ReceiverRoleT extends ArchRoleT with { - - } - Role Type RequestorRoleT extends ArchRoleT with { - - } - Connector Type ProxyConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - Connector Type SQLConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - Connector Type HttpConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - Property bandwidth : float << default : float = 0.0; >> ; - - Property latency : float << default : float = 0.0; >> ; - - Property numReqsSuccess : int << default : int = 0; >> ; - - Property numReqsRedirect : int << default : int = 0; >> ; - - Property numReqsClientError : int << default : int = 0; >> ; - - Property numReqsServerError : int << default : int = 0; >> ; - - Property latencyRate : float; - - } - - Property MIN_RESPTIME : float; - - Property MAX_RESPTIME : float << default : float = 2; >> ; - - Property TOLERABLE_PERCENT_UNHAPPY : float; - - Property UNHAPPY_GRADIENT_1 : float; - - Property UNHAPPY_GRADIENT_2 : float; - - Property UNHAPPY_GRADIENT_3 : float; - - Property FRACTION_GRADIENT_1 : float; - - Property FRACTION_GRADIENT_2 : float; - - Property FRACTION_GRADIENT_3 : float; - - Property MIN_UTIL : float; - - Property MAX_UTIL : float << default : float = 1; >> ; - - Property MAX_FIDELITY_LEVEL : int; - - Property THRESHOLD_FIDELITY : int; - - Property THRESHOLD_COST : float; -} - -Family DoSFam = { - - Element Type PotentiallyMaliciousT = { - - Property deploymentLocation : string; - - Property maliciousness : float << default : float = 0.0; >> ; - - } - Element Type MaliciousT extends PotentiallyMaliciousT with { - rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; - - } - Element Type SuspiciousT extends PotentiallyMaliciousT with { - rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD AND maliciousness <= MALICIOUS_THRESHOLD; - - } - Element Type NormalT extends PotentiallyMaliciousT with { - rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; - - } - Element Type BlackholerT = { - - Property blackholed : Set {string} << default : Set {string} = {}; >> ; - - } - Element Type CaptchaRedirectT = { - - Property captchaEnabled : boolean << default : boolean = false; >> ; - - } - Element Type ThrottlerT = { - - Property throttled : Set {string} << default : Set {string} = {}; >> ; - - } - Element Type CaptchaHandlerT = { - - Property captcha : int << default : int = 0; >> ; - - } - Element Type AuthenticationHandlerT = { - - Property authenticate : int << default : int = 0; >> ; - - } - Port Type BlackholedPortT = { - - Property isBlackholed : boolean = true; - - } - - Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; - - Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; - rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | - exists bh : BlackholerT in self.COMPONENTS | - contains(c.deploymentLocation, bh.blackholed); - rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | - forall ip : string in lb.blackholed | - forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | - c.maliciousness > self.MALICIOUS_THRESHOLD; -} - -Family ZNewsDosFam extends ZNewsFam, DoSFam with { - - Component Type ZNewsClientT extends ClientT, PotentiallyMaliciousT, CaptchaHandlerT, AuthenticationHandlerT with { - - } - Component Type ZNewsLBT extends ProxyT, CaptchaRedirectT, BlackholerT, ThrottlerT with { - - } -} - -System ZNewsSys : ZNewsDosFam = new ZNewsDosFam extended with { - - Component Server0 : ArchElementT, ServerT = new ArchElementT, ServerT extended with { - Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { - - Property isArchEnabled = true; - - } - Port sql0 : SqlReqPort = new SqlReqPort extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.web0}"; - Property httpPort : string = "${customize.system.target.web0.httpPort}"; - - Property load = 0.0; - - Property reqServiceRate = 0.0; - - Property byteServiceRate = 0.0; - - Property fidelity = 5; - - Property cost = 1.0; - - Property isArchEnabled = true; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - - Component Server1 : ServerT = new ServerT extended with { - Port p : HttpPortT = new HttpPortT extended with { - - } - Port p0 : SqlReqPort = new SqlReqPort extended with { - - } - Property deploymentLocation = "${customize.system.target.web1}"; - Property httpPort : string = "${customize.system.target.web1.httpPort}"; - - Property load = 0.0; - - Property reqServiceRate = 0.0; - - Property byteServiceRate = 0.0; - - Property fidelity = 5; - - Property cost = 1.0; - - Property isArchEnabled = true; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - - Component ServerB0 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { - - Property isArchEnabled = false; - - } - Port sql0 : SqlReqPort = new SqlReqPort extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.web2}"; - Property httpPort : string = "${customize.system.target.web2.httpPort}"; - - Property load = 0.0; - - Property reqServiceRate = 0.0; - - Property byteServiceRate = 0.0; - - Property fidelity = 5; - - Property cost = 1.0; - - Property isArchEnabled = false; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - Component LB0 : ZNewsLBT = new ZNewsLBT extended with { - Port http0 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - Port http1 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - Property captchaEnabled = false; - - } - Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - Property isArchEnabled = true; - - } - Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - Property isArchEnabled = false; - - } - Port p : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - - Property deploymentLocation = "${customize.system.target.lb}"; - - Property load = 0.0; - - Property isArchEnabled = true; - - Property blackholed = {}; - - Property captchaEnabled = false; - - Property throttled = {}; - - } - Component DB0 : DBT = new DBT extended with { - Port rec0 : SqlRecPort = new SqlRecPort extended with { - - Property isArchEnabled = true; - - } - Port rec1 : SqlRecPort = new SqlRecPort extended with { - - Property isArchEnabled = true; - - } - Port p : SqlRecPort = new SqlRecPort extended with { - - } - - Property deploymentLocation = "${customize.system.target.db}"; - - Property load = 0.0; - - Property isArchEnabled = true; - - } - Component Client0 : ZNewsClientT = new ZNewsClientT extended with { - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.client1}"; - - Property experRespTime = 0; - - Property reqRate = 0.0; - - Property isArchEnabled = true; - - Property maliciousness = 0.0; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - Component Client1 : ZNewsClientT = new ZNewsClientT extended with { - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.client2}"; - - Property experRespTime = 0.0; - - Property reqRate = 0.0; - - Property isArchEnabled = true; - - Property maliciousness = 0.0; - - Property captcha = 0; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - - Connector httpConn_0_0 : HttpConnT = new HttpConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property bandwidth = 0.0; - - Property latency = 0.0; - - Property numReqsSuccess = 0; - - Property numReqsRedirect = 0; - - Property numReqsClientError = 0; - - Property numReqsServerError = 0; - - Property isArchEnabled = true; - - } - Connector httpConn_1_0 : HttpConnT = new HttpConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property bandwidth = 0.0; - - Property latency = 0.0; - - Property numReqsSuccess = 0; - - Property numReqsRedirect = 0; - - Property numReqsClientError = 0; - - Property numReqsServerError = 0; - - Property isArchEnabled = true; - - } - Connector proxyConn_0_0 : ProxyConnT = new ProxyConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = true; - - } - Connector proxyConn_1_0 : ProxyConnT = new ProxyConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = false; - - } - Connector dbConn_0_0 : SQLConnT = new SQLConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = true; - - } - Connector dbConn_1_0 : SQLConnT = new SQLConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = true; - - } - Connector ProxyConnT0 : ProxyConnT = new ProxyConnT extended with { - - } - Connector SQLConnT0 : SQLConnT = new SQLConnT extended with { - - } - Attachment Client1.p0 to httpConn_0_0.req; - Attachment LB0.http0 to httpConn_0_0.rec; - Attachment Client0.p0 to httpConn_1_0.req; - Attachment LB0.http1 to httpConn_1_0.rec; - Attachment Server0.http0 to proxyConn_0_0.rec; - Attachment LB0.fwd0 to proxyConn_0_0.req; - Attachment ServerB0.http0 to proxyConn_1_0.rec; - Attachment LB0.fwd1 to proxyConn_1_0.req; - Attachment Server0.sql0 to dbConn_0_0.rec; - Attachment DB0.rec0 to dbConn_0_0.req; - Attachment ServerB0.sql0 to dbConn_1_0.rec; - Attachment DB0.rec1 to dbConn_1_0.req; - Attachment LB0.p to ProxyConnT0.req; - Attachment Server1.p to ProxyConnT0.rec; - Attachment Server1.p0 to SQLConnT0.req; - Attachment DB0.p to SQLConnT0.rec; - - Property MAX_RESPTIME = 2000.0; - - Property MAX_UTIL = 1; - - Property MALICIOUS_THRESHOLD = 0.8; - rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | - exists bh : BlackholerT in self.COMPONENTS | - contains(c.deploymentLocation, bh.blackholed); - rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | - forall ip : string in lb.blackholed | - forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | - c.maliciousness > self.MALICIOUS_THRESHOLD; -} - +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + Port Type PartPortT = { + + } + Port Type NetworkPortT = { + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Port Type ContainmentPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Role Type NetworkRoleT = { + + } + Role Type PartRoleT = { + + } + Role Type ContainerRoleT = { + + } + Connector Type MappingT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } +} + +Family ZNewsFam extends EnvType with { + + Port Type HttpPortT extends ArchPortT with { + + } + Port Type ProxyForwardPortT extends ArchPortT with { + + } + Port Type HttpReqPortT extends ArchPortT with { + + } + Port Type SqlReqPort extends ArchPortT with { + + } + Port Type SqlRecPort extends ArchPortT with { + + } + Component Type ProxyT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Component Type ServerT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + Property reqServiceRate : float << default : float = 0.0; >> ; + + Property byteServiceRate : float << default : float = 0.0; >> ; + + Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; + + Property cost : float << default : float = 1.0; >> ; + + Property lastPageHit : Record [uri : string; cnt : int; kbytes : float; ]; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + Component Type ClientT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property experRespTime : float << default : float = 0.0; >> ; + + Property reqRate : float << default : float = 0.0; >> ; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + Component Type DBT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "locahost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Role Type ReceiverRoleT extends ArchRoleT with { + + } + Role Type RequestorRoleT extends ArchRoleT with { + + } + Connector Type ProxyConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Connector Type SQLConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Connector Type HttpConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + Property bandwidth : float << default : float = 0.0; >> ; + + Property latency : float << default : float = 0.0; >> ; + + Property numReqsSuccess : int << default : int = 0; >> ; + + Property numReqsRedirect : int << default : int = 0; >> ; + + Property numReqsClientError : int << default : int = 0; >> ; + + Property numReqsServerError : int << default : int = 0; >> ; + + Property latencyRate : float; + + } + + Property MIN_RESPTIME : float; + + Property MAX_RESPTIME : float << default : float = 2; >> ; + + Property TOLERABLE_PERCENT_UNHAPPY : float; + + Property UNHAPPY_GRADIENT_1 : float; + + Property UNHAPPY_GRADIENT_2 : float; + + Property UNHAPPY_GRADIENT_3 : float; + + Property FRACTION_GRADIENT_1 : float; + + Property FRACTION_GRADIENT_2 : float; + + Property FRACTION_GRADIENT_3 : float; + + Property MIN_UTIL : float; + + Property MAX_UTIL : float << default : float = 1; >> ; + + Property MAX_FIDELITY_LEVEL : int; + + Property THRESHOLD_FIDELITY : int; + + Property THRESHOLD_COST : float; +} + +Family DoSFam = { + + Element Type PotentiallyMaliciousT = { + + Property deploymentLocation : string; + + Property maliciousness : float << default : float = 0.0; >> ; + + } + Element Type MaliciousT extends PotentiallyMaliciousT with { + rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; + + } + Element Type SuspiciousT extends PotentiallyMaliciousT with { + rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD AND maliciousness <= MALICIOUS_THRESHOLD; + + } + Element Type NormalT extends PotentiallyMaliciousT with { + rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; + + } + Element Type BlackholerT = { + + Property blackholed : Set {string} << default : Set {string} = {}; >> ; + + } + Element Type CaptchaRedirectT = { + + Property captchaEnabled : boolean << default : boolean = false; >> ; + + } + Element Type ThrottlerT = { + + Property throttled : Set {string} << default : Set {string} = {}; >> ; + + } + Element Type CaptchaHandlerT = { + + Property captcha : int << default : int = 0; >> ; + + } + Element Type AuthenticationHandlerT = { + + Property authenticate : int << default : int = 0; >> ; + + } + Port Type BlackholedPortT = { + + Property isBlackholed : boolean = true; + + } + + Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; + + Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; + rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | + exists bh : BlackholerT in self.COMPONENTS | + contains(c.deploymentLocation, bh.blackholed); + rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | + forall ip : string in lb.blackholed | + forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | + c.maliciousness > self.MALICIOUS_THRESHOLD; +} + +Family ZNewsDosFam extends ZNewsFam, DoSFam with { + + Component Type ZNewsClientT extends ClientT, PotentiallyMaliciousT, CaptchaHandlerT, AuthenticationHandlerT with { + + } + Component Type ZNewsLBT extends ProxyT, CaptchaRedirectT, BlackholerT, ThrottlerT with { + + } +} + +System ZNewsSys : ZNewsDosFam = new ZNewsDosFam extended with { + + Component Server0 : ArchElementT, ServerT = new ArchElementT, ServerT extended with { + Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { + + Property isArchEnabled = true; + + } + Port sql0 : SqlReqPort = new SqlReqPort extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.web0}"; + Property httpPort : string = "${customize.system.target.web0.httpPort}"; + + Property load = 0.0; + + Property reqServiceRate = 0.0; + + Property byteServiceRate = 0.0; + + Property fidelity = 5; + + Property cost = 1.0; + + Property isArchEnabled = true; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + + Component Server1 : ServerT = new ServerT extended with { + Port p : HttpPortT = new HttpPortT extended with { + + } + Port p0 : SqlReqPort = new SqlReqPort extended with { + + } + Property deploymentLocation = "${customize.system.target.web1}"; + Property httpPort : string = "${customize.system.target.web1.httpPort}"; + + Property load = 0.0; + + Property reqServiceRate = 0.0; + + Property byteServiceRate = 0.0; + + Property fidelity = 5; + + Property cost = 1.0; + + Property isArchEnabled = true; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + + Component ServerB0 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { + + Property isArchEnabled = false; + + } + Port sql0 : SqlReqPort = new SqlReqPort extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.web2}"; + Property httpPort : string = "${customize.system.target.web2.httpPort}"; + + Property load = 0.0; + + Property reqServiceRate = 0.0; + + Property byteServiceRate = 0.0; + + Property fidelity = 5; + + Property cost = 1.0; + + Property isArchEnabled = false; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + Component LB0 : ZNewsLBT = new ZNewsLBT extended with { + Port http0 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + Port http1 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + Property captchaEnabled = false; + + } + Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + Property isArchEnabled = true; + + } + Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + Property isArchEnabled = false; + + } + Port p : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + + Property deploymentLocation = "${customize.system.target.lb}"; + + Property load = 0.0; + + Property isArchEnabled = true; + + Property blackholed = {}; + + Property captchaEnabled = false; + + Property throttled = {}; + + } + Component DB0 : DBT = new DBT extended with { + Port rec0 : SqlRecPort = new SqlRecPort extended with { + + Property isArchEnabled = true; + + } + Port rec1 : SqlRecPort = new SqlRecPort extended with { + + Property isArchEnabled = true; + + } + Port p : SqlRecPort = new SqlRecPort extended with { + + } + + Property deploymentLocation = "${customize.system.target.db}"; + + Property load = 0.0; + + Property isArchEnabled = true; + + } + Component Client0 : ZNewsClientT = new ZNewsClientT extended with { + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.client1}"; + + Property experRespTime = 0; + + Property reqRate = 0.0; + + Property isArchEnabled = true; + + Property maliciousness = 0.0; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + Component Client1 : ZNewsClientT = new ZNewsClientT extended with { + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.client2}"; + + Property experRespTime = 0.0; + + Property reqRate = 0.0; + + Property isArchEnabled = true; + + Property maliciousness = 0.0; + + Property captcha = 0; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + + Connector httpConn_0_0 : HttpConnT = new HttpConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property bandwidth = 0.0; + + Property latency = 0.0; + + Property numReqsSuccess = 0; + + Property numReqsRedirect = 0; + + Property numReqsClientError = 0; + + Property numReqsServerError = 0; + + Property isArchEnabled = true; + + } + Connector httpConn_1_0 : HttpConnT = new HttpConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property bandwidth = 0.0; + + Property latency = 0.0; + + Property numReqsSuccess = 0; + + Property numReqsRedirect = 0; + + Property numReqsClientError = 0; + + Property numReqsServerError = 0; + + Property isArchEnabled = true; + + } + Connector proxyConn_0_0 : ProxyConnT = new ProxyConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = true; + + } + Connector proxyConn_1_0 : ProxyConnT = new ProxyConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = false; + + } + Connector dbConn_0_0 : SQLConnT = new SQLConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = true; + + } + Connector dbConn_1_0 : SQLConnT = new SQLConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = true; + + } + Connector ProxyConnT0 : ProxyConnT = new ProxyConnT extended with { + + } + Connector SQLConnT0 : SQLConnT = new SQLConnT extended with { + + } + Attachment Client1.p0 to httpConn_0_0.req; + Attachment LB0.http0 to httpConn_0_0.rec; + Attachment Client0.p0 to httpConn_1_0.req; + Attachment LB0.http1 to httpConn_1_0.rec; + Attachment Server0.http0 to proxyConn_0_0.rec; + Attachment LB0.fwd0 to proxyConn_0_0.req; + Attachment ServerB0.http0 to proxyConn_1_0.rec; + Attachment LB0.fwd1 to proxyConn_1_0.req; + Attachment Server0.sql0 to dbConn_0_0.rec; + Attachment DB0.rec0 to dbConn_0_0.req; + Attachment ServerB0.sql0 to dbConn_1_0.rec; + Attachment DB0.rec1 to dbConn_1_0.req; + Attachment LB0.p to ProxyConnT0.req; + Attachment Server1.p to ProxyConnT0.rec; + Attachment Server1.p0 to SQLConnT0.req; + Attachment DB0.p to SQLConnT0.rec; + + Property MAX_RESPTIME = 2000.0; + + Property MAX_UTIL = 1; + + Property MALICIOUS_THRESHOLD = 0.8; + rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | + exists bh : BlackholerT in self.COMPONENTS | + contains(c.deploymentLocation, bh.blackholed); + rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | + forall ip : string in lb.blackholed | + forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | + c.maliciousness > self.MALICIOUS_THRESHOLD; +} + diff --git a/targets/znews-ss-prediction/model/ZNewsSys.mtd b/targets/znews-ss-prediction/model/ZNewsSys.mtd index 9975f54af..e847ff51b 100644 --- a/targets/znews-ss-prediction/model/ZNewsSys.mtd +++ b/targets/znews-ss-prediction/model/ZNewsSys.mtd @@ -1,396 +1,396 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews-ss-prediction/model/gauges.yml b/targets/znews-ss-prediction/model/gauges.yml index d10a9038e..6e3a3d811 100644 --- a/targets/znews-ss-prediction/model/gauges.yml +++ b/targets/znews-ss-prediction/model/gauges.yml @@ -1,134 +1,134 @@ -# -# Gauge Type and Gauge Instance Specifications -# - time periods generally in milliseconds -# -# History: -# - [SWC 2007.01.18] Created file, populated ZNews gauge descriptions. -# - [SWC 2007.04.09] Changed LatencyGaugeT to use RtLatencyMultiHostGauge. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# - [SWC 2007.04.11] Added ResponseTimeGaugeT -# - [BRS 2013.11.13] Changed to new format -# -gauge-types: - - - BlackHoleGaugeT: - commands: - blockedIPs: "BlackholerT.setBlackholed({String})" - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.BlackholeGauge" - configParams: - targetProbeType: - type: String - default: ~ - - ThrottleGaugeT: - commands: - throttledIPs: "ThrottlerT.setThrottled({String})" - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.ThrottleGauge" - configParams: - targetProbeType: - type: String - default: ~ - - MaliciousnessGaugeT: - commands: - maliciousness : PotentiallyMaliciousT.setMaliciousness (float) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.EchoGauge" - configParams: - targetGaugeName: - type: String - default: ~ - targetGaugeType: - type: String - default: ~ - targetGaugeValue: - type: String - default: ~ - comment: "EchoGaugeT echos a value reported by another gauge" - - DummyDiagnosisGaugeT: - commands: - maliciousness: PotentiallyMaliciousT.setMaliciousness (float) - captcha: CaptchaHandlerT.setCaptchaResponse (int) - authenticate: CaptchaHandlerT.setAuthenticationResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.DummyDiagnosisGauge" - configParams: - targetProbeList: - type: String - default: ~ - - CaptchaGaugeT: - commands: - enablement : ProxyT.setCaptchaEnabled (boolean) - clientMgmt : CaptchaHandlerT.setCaptchaResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 5000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.CaptchaGauge" - configParams: - targetProbeType: - type: String - default: ~ - - AuthenticationEnablementGaugeT: - commands: - clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 5000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge" - configParams: - targetProbeType: - type: String - default: ~ +# +# Gauge Type and Gauge Instance Specifications +# - time periods generally in milliseconds +# +# History: +# - [SWC 2007.01.18] Created file, populated ZNews gauge descriptions. +# - [SWC 2007.04.09] Changed LatencyGaugeT to use RtLatencyMultiHostGauge. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# - [SWC 2007.04.11] Added ResponseTimeGaugeT +# - [BRS 2013.11.13] Changed to new format +# +gauge-types: + + + BlackHoleGaugeT: + commands: + blockedIPs: "BlackholerT.setBlackholed({String})" + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.BlackholeGauge" + configParams: + targetProbeType: + type: String + default: ~ + + ThrottleGaugeT: + commands: + throttledIPs: "ThrottlerT.setThrottled({String})" + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.ThrottleGauge" + configParams: + targetProbeType: + type: String + default: ~ + + MaliciousnessGaugeT: + commands: + maliciousness : PotentiallyMaliciousT.setMaliciousness (float) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.EchoGauge" + configParams: + targetGaugeName: + type: String + default: ~ + targetGaugeType: + type: String + default: ~ + targetGaugeValue: + type: String + default: ~ + comment: "EchoGaugeT echos a value reported by another gauge" + + DummyDiagnosisGaugeT: + commands: + maliciousness: PotentiallyMaliciousT.setMaliciousness (float) + captcha: CaptchaHandlerT.setCaptchaResponse (int) + authenticate: CaptchaHandlerT.setAuthenticationResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.DummyDiagnosisGauge" + configParams: + targetProbeList: + type: String + default: ~ + + CaptchaGaugeT: + commands: + enablement : ProxyT.setCaptchaEnabled (boolean) + clientMgmt : CaptchaHandlerT.setCaptchaResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 5000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.CaptchaGauge" + configParams: + targetProbeType: + type: String + default: ~ + + AuthenticationEnablementGaugeT: + commands: + clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 5000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge" + configParams: + targetProbeType: + type: String + default: ~ DiagnosisGaugeT: commands: @@ -143,450 +143,450 @@ gauge-types: javaClass: type: String default: "org.sa.rainbow.translator.znn.gauges.DiagnosisGauge" - configParams: - clients: - type: String + configParams: + clients: + type: String default: "c1=10.5.6.254" reportingPeriod: type: long default: 10000 comment: "Diagnosis gauge for DoS analysis" - - ResponseTimeGaugeT: - commands: - end2endRespTime : ClientT.setResponseTime (float) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.End2EndRespTimeGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "ResponseTimeGaugeT measures and reports the end-to-end response time from a client or its proxy." - - - ServerEnablementGaugeT: - commands: - removeServer: ServerT.deleteServer - addServer: "ProxyT.connectNewServer (String, String, String)" - enableServer: ServerT.enableServer (boolean) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 10000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.ServerEnablementGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - mode: - type: String - default: "enable" - comment: "ServerEnablementGaugeT reports creation/deletion or enablement/disablement of servers. mode can be either enable|new" - - - ApacheTopGaugeT: - commands: - reqServiceRate : ServerT.setReqServiceRate(float) - byteServiceRate : ServerT.setByteServiceRate(float) - numReqsSuccess : HttpConnT.setNumSuccessfulRequests(int) - numReqsRedirect : HttpConnT.setNumRedirectedRequests(int) - numReqsClientError : HttpConnT.setNumRequestsClientError(int) - numReqsServerError : HttpConnT.setNumRequestsServerError(int) - pageHit : ServerT.setLastPageHit(String) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.ApacheTopGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "ApacheTopGaugeT measures and reports properties of an Apache server, via a UNIX top like utility" - - DiskIOGaugeT: - commands: - transferRate : ServerT.setDiskTransferRate(double) - readRate : ServerT.setDiskReadRate(double) - writeRate : ServerT.setDiskWriteRate(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.DiskIOGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "DiskIOGaugeT measures and reports disk IO stat of the target host, read/write reported in KBps" - - LoadGaugeT: - commands: - load : ServerT.setLoad(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.CpuLoadGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "LoadGaugeT measures and reports CPU load of the target host" - - FidelityGaugeT: - commands: - fidelity : ServerT.setFidelity(int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.FidelityGauge" - configParams: - samplingFrequency: - type: long - default: 2500 - targetProbeType: - type: String - default: ~ - comment: "FidelityGaugeT measures and reports the fidelity level of served content" - - LatencyGaugeT: - commands: - latency : HttpConnT.setLatency(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge" - configParams: - samplingFrequency: - type: long - default: 1500 - targetProbeType: - type: String - default: ~ - comment: "LatencyGaugeT measures and reports latency on a connection" - - LatencyRateGaugeT: - commands: - latencyRate : HttpConnT.setLatencyRate(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge" - configParams: - samplingFrequency: - type: long - default: 1500 - targetProbeType: - type: String - default: ~ - comment: "LatencyRateGaugeT measures and reports the latency rate of change on a connection" - - - -gauge-instances: - - BHG1: - type: BlackHoleGaugeT - model: "ZNewsSys:Acme" - commands: - "blockedIPs": LB0.setBlackholed ($) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - reportingPeriod: 10000 - targetProbeType: blackhole - - TG1: - type: ThrottleGaugeT - model: "ZNewsSys:Acme" - commands: - "throttledIPs": LB0.setThrottled ($) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - reportingPeriod: 10000 - targetProbeType: throttle - - MG1: - type: DummyDiagnosisGaugeT - model: "ZNewsSys:Acme" - commands: - "maliciousness(x)": x.setMaliciousness ($) - "captcha(x)": x.setCaptchaResponse ($) - "authenticate(x)": x.setAuthenticationResponse ($) - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - reportingPeriod: 10000 - targetProbeList: "dummymaliciousness@*,authenticationprobe" - - - CG1: - type: CaptchaGaugeT - model: "ZNewsSys:Acme" - commands: - "enabled": LB0.setCaptchaEnabled($) - "clientMgmt(${customize.system.target.client1})": Client0.setCaptchaResponse (0) - "clientMgmt(${customize.system.target.client2})": Client1.setCaptchaResponse (0) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - samplingFrequency: 1000 - targetProbeType: captchaprobe - - AEG1: - type: AuthenticationEnablementGaugeT - model: "ZNewsSys:Acme" - commands: - "clientMgmt(${customize.system.target.client1})": Client0.setAuthenticationResponse (0) - "clientMgmt(${customize.system.target.client2})": Client1.setAuthenticationResponse (0) - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - samplingFrequency: 1000 - targetProbeType: authenticationprobe + + ResponseTimeGaugeT: + commands: + end2endRespTime : ClientT.setResponseTime (float) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.End2EndRespTimeGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "ResponseTimeGaugeT measures and reports the end-to-end response time from a client or its proxy." + + + ServerEnablementGaugeT: + commands: + removeServer: ServerT.deleteServer + addServer: "ProxyT.connectNewServer (String, String, String)" + enableServer: ServerT.enableServer (boolean) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 10000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.ServerEnablementGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + mode: + type: String + default: "enable" + comment: "ServerEnablementGaugeT reports creation/deletion or enablement/disablement of servers. mode can be either enable|new" + + + ApacheTopGaugeT: + commands: + reqServiceRate : ServerT.setReqServiceRate(float) + byteServiceRate : ServerT.setByteServiceRate(float) + numReqsSuccess : HttpConnT.setNumSuccessfulRequests(int) + numReqsRedirect : HttpConnT.setNumRedirectedRequests(int) + numReqsClientError : HttpConnT.setNumRequestsClientError(int) + numReqsServerError : HttpConnT.setNumRequestsServerError(int) + pageHit : ServerT.setLastPageHit(String) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.ApacheTopGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "ApacheTopGaugeT measures and reports properties of an Apache server, via a UNIX top like utility" + + DiskIOGaugeT: + commands: + transferRate : ServerT.setDiskTransferRate(double) + readRate : ServerT.setDiskReadRate(double) + writeRate : ServerT.setDiskWriteRate(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.DiskIOGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "DiskIOGaugeT measures and reports disk IO stat of the target host, read/write reported in KBps" + + LoadGaugeT: + commands: + load : ServerT.setLoad(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.CpuLoadGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "LoadGaugeT measures and reports CPU load of the target host" + + FidelityGaugeT: + commands: + fidelity : ServerT.setFidelity(int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.FidelityGauge" + configParams: + samplingFrequency: + type: long + default: 2500 + targetProbeType: + type: String + default: ~ + comment: "FidelityGaugeT measures and reports the fidelity level of served content" + + LatencyGaugeT: + commands: + latency : HttpConnT.setLatency(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge" + configParams: + samplingFrequency: + type: long + default: 1500 + targetProbeType: + type: String + default: ~ + comment: "LatencyGaugeT measures and reports latency on a connection" + + LatencyRateGaugeT: + commands: + latencyRate : HttpConnT.setLatencyRate(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge" + configParams: + samplingFrequency: + type: long + default: 1500 + targetProbeType: + type: String + default: ~ + comment: "LatencyRateGaugeT measures and reports the latency rate of change on a connection" + + + +gauge-instances: + + BHG1: + type: BlackHoleGaugeT + model: "ZNewsSys:Acme" + commands: + "blockedIPs": LB0.setBlackholed ($) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + reportingPeriod: 10000 + targetProbeType: blackhole + + TG1: + type: ThrottleGaugeT + model: "ZNewsSys:Acme" + commands: + "throttledIPs": LB0.setThrottled ($) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + reportingPeriod: 10000 + targetProbeType: throttle + + MG1: + type: DummyDiagnosisGaugeT + model: "ZNewsSys:Acme" + commands: + "maliciousness(x)": x.setMaliciousness ($) + "captcha(x)": x.setCaptchaResponse ($) + "authenticate(x)": x.setAuthenticationResponse ($) + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + reportingPeriod: 10000 + targetProbeList: "dummymaliciousness@*,authenticationprobe" + + + CG1: + type: CaptchaGaugeT + model: "ZNewsSys:Acme" + commands: + "enabled": LB0.setCaptchaEnabled($) + "clientMgmt(${customize.system.target.client1})": Client0.setCaptchaResponse (0) + "clientMgmt(${customize.system.target.client2})": Client1.setCaptchaResponse (0) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + samplingFrequency: 1000 + targetProbeType: captchaprobe + + AEG1: + type: AuthenticationEnablementGaugeT + model: "ZNewsSys:Acme" + commands: + "clientMgmt(${customize.system.target.client1})": Client0.setAuthenticationResponse (0) + "clientMgmt(${customize.system.target.client2})": Client1.setAuthenticationResponse (0) + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + samplingFrequency: 1000 + targetProbeType: authenticationprobe - EERTG1: - type: ResponseTimeGaugeT - model: "ZNewsSys:Acme" - commands: - "end2endRespTime(${customize.system.target.master})" : Client0.setResponseTime($) - "end2endRespTime(${customize.system.target.bad})" : Client1.setResponseTime($) - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - samplingFrequency: 1000 - targetProbeType : clientproxy@* - comment: "EERTG1 is associated with the client component of the System, ZNewsSys, defined as an Acme model" - - - SEG1: - type: ServerEnablementGaugeT - model: "ZNewsSys:Acme" - commands: - "removeServer(x)": x.deleteServer - "connectServer(x)": "LB0.connectNewServer (Server0, $, $)" - "enableServer(x)": "LB0.enableServer (x, $)" - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - targetProbeType: "enablementprobe@${customize.system.target.lb}" - samplingFrequency: 1000 - mode: new - comment: "This needs to be located on the master because it needs access to the model" - - - -unused-gauge-instances: - - MG1: - type: MaliciousnessGaugeT - model: "ZNewsSys:Acme" - mappings: - "maliciousness(c2)": Client1.maliciousness - "maliciousness(c1)": Client0.maliciousness - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - targetGaugeName: DG1 - targetGaugeType: DiagnosisGaugeT - targetGaugeValue: maliciousness - - DG1: - type: DiagnosisGaugeT - model: "ZNewsSys:Acme" - mappings: - "maliciousness": x - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - reportingPeriod: 10000 - - ATG1: - type: ApacheTopGaugeT - model: "ZNewsSys:Acme" - mappings: - reqServiceRate : s0.reqServiceRate - byteServiceRate : s0.byteServiceRate - numReqsSuccess : conn0.numReqsSuccess - numReqsRedirect : conn0.numReqsRedirect - numReqsClientError : conn0.numReqsClientError - numReqsServerError : conn0.numReqsServerError - pageHit : s0.lastPageHit - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: ~ - # Leave details unspecified (null) to use default value defined at the type-level - targetProbeType : apachetop - comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" - - DioG1: - type: DiskIOGaugeT - model: "ZNewsSys:Acme" - mappings: - transferRate : s0.diskXferRate - readRate : s0.diskReadRate - writeRate : s0.diskWriteRate - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1000 - targetProbeType : diskio - comment: "DioG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LoG0: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s0.load - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG0 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LoG1: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s1.load - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG1 is associated with the component s1 of the System, ZNewsSys, defined as an Acme model" - - FiG1: - type: FidelityGaugeT - model: "ZNewsSys:Acme" - mappings: - fidelity : s0.fidelity - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 2500 - targetProbeType : fidelity - comment: "FiG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LatG1: - type: LatencyGaugeT - model: "ZNewsSys:Acme" - mappings: - "latency(${rainbow.master.location.host})" : conn0.latency - "latency(@{ZNewsSys.s1.deploymentLocation})" : conn1.latency - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1500 - targetProbeType : pingrtt - comment: "LatG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" - - LatRoCG1: - type: LatencyRateGaugeT - model: "ZNewsSys:Acme" - mappings: - "latencyRate(${rainbow.master.location.host})" : conn0.latencyRate - "latencyRate(@{ZNewsSys.s1.deploymentLocation})" : conn1.latencyRate - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1500 - targetProbeType : pingrtt - comment: "LatRoCG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" - - ATG0: - type: ApacheTopGaugeT - model: "ZNewsSys:Acme" - mappings: - reqServiceRate : s0.reqServiceRate - byteServiceRate : s0.byteServiceRate - numReqsSuccess : conn0.numReqsSuccess - numReqsRedirect : conn0.numReqsRedirect - numReqsClientError : conn0.numReqsClientError - numReqsServerError : conn0.numReqsServerError - pageHit : s0.lastPageHit - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - samplingFrequency: ~ - # Leave details unspecified (null) to use default value defined at the type-level - targetProbeType : apachetop - comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" - - LoG3: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s3.load - setupValues: - targetIP: "${customize.system.target.3}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG3 is associated with the component s3 of the System, ZNewsSys, defined as an Acme model" - + EERTG1: + type: ResponseTimeGaugeT + model: "ZNewsSys:Acme" + commands: + "end2endRespTime(${customize.system.target.master})" : Client0.setResponseTime($) + "end2endRespTime(${customize.system.target.bad})" : Client1.setResponseTime($) + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + samplingFrequency: 1000 + targetProbeType : clientproxy@* + comment: "EERTG1 is associated with the client component of the System, ZNewsSys, defined as an Acme model" + + + SEG1: + type: ServerEnablementGaugeT + model: "ZNewsSys:Acme" + commands: + "removeServer(x)": x.deleteServer + "connectServer(x)": "LB0.connectNewServer (Server0, $, $)" + "enableServer(x)": "LB0.enableServer (x, $)" + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + targetProbeType: "enablementprobe@${customize.system.target.lb}" + samplingFrequency: 1000 + mode: new + comment: "This needs to be located on the master because it needs access to the model" + + + +unused-gauge-instances: + + MG1: + type: MaliciousnessGaugeT + model: "ZNewsSys:Acme" + mappings: + "maliciousness(c2)": Client1.maliciousness + "maliciousness(c1)": Client0.maliciousness + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + targetGaugeName: DG1 + targetGaugeType: DiagnosisGaugeT + targetGaugeValue: maliciousness + + DG1: + type: DiagnosisGaugeT + model: "ZNewsSys:Acme" + mappings: + "maliciousness": x + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + reportingPeriod: 10000 + + ATG1: + type: ApacheTopGaugeT + model: "ZNewsSys:Acme" + mappings: + reqServiceRate : s0.reqServiceRate + byteServiceRate : s0.byteServiceRate + numReqsSuccess : conn0.numReqsSuccess + numReqsRedirect : conn0.numReqsRedirect + numReqsClientError : conn0.numReqsClientError + numReqsServerError : conn0.numReqsServerError + pageHit : s0.lastPageHit + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: ~ + # Leave details unspecified (null) to use default value defined at the type-level + targetProbeType : apachetop + comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" + + DioG1: + type: DiskIOGaugeT + model: "ZNewsSys:Acme" + mappings: + transferRate : s0.diskXferRate + readRate : s0.diskReadRate + writeRate : s0.diskWriteRate + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1000 + targetProbeType : diskio + comment: "DioG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LoG0: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s0.load + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG0 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LoG1: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s1.load + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG1 is associated with the component s1 of the System, ZNewsSys, defined as an Acme model" + + FiG1: + type: FidelityGaugeT + model: "ZNewsSys:Acme" + mappings: + fidelity : s0.fidelity + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 2500 + targetProbeType : fidelity + comment: "FiG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LatG1: + type: LatencyGaugeT + model: "ZNewsSys:Acme" + mappings: + "latency(${rainbow.master.location.host})" : conn0.latency + "latency(@{ZNewsSys.s1.deploymentLocation})" : conn1.latency + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1500 + targetProbeType : pingrtt + comment: "LatG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" + + LatRoCG1: + type: LatencyRateGaugeT + model: "ZNewsSys:Acme" + mappings: + "latencyRate(${rainbow.master.location.host})" : conn0.latencyRate + "latencyRate(@{ZNewsSys.s1.deploymentLocation})" : conn1.latencyRate + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1500 + targetProbeType : pingrtt + comment: "LatRoCG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" + + ATG0: + type: ApacheTopGaugeT + model: "ZNewsSys:Acme" + mappings: + reqServiceRate : s0.reqServiceRate + byteServiceRate : s0.byteServiceRate + numReqsSuccess : conn0.numReqsSuccess + numReqsRedirect : conn0.numReqsRedirect + numReqsClientError : conn0.numReqsClientError + numReqsServerError : conn0.numReqsServerError + pageHit : s0.lastPageHit + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + samplingFrequency: ~ + # Leave details unspecified (null) to use default value defined at the type-level + targetProbeType : apachetop + comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" + + LoG3: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s3.load + setupValues: + targetIP: "${customize.system.target.3}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG3 is associated with the component s3 of the System, ZNewsSys, defined as an Acme model" + diff --git a/targets/znews-ss-prediction/model/op.map b/targets/znews-ss-prediction/model/op.map index 867bb0232..5cf840f9c 100644 --- a/targets/znews-ss-prediction/model/op.map +++ b/targets/znews-ss-prediction/model/op.map @@ -1,8 +1,8 @@ -setFidelity: changeState -blackhole: changeState -unblackhole: changeState -enableCaptcha: changeState -disableCaptcha: changeState -activateServer: start -deactivateServer: stop - +setFidelity: changeState +blackhole: changeState +unblackhole: changeState +enableCaptcha: changeState +disableCaptcha: changeState +activateServer: start +deactivateServer: stop + diff --git a/targets/znews-ss-prediction/rainbow-10.5.6.1.properties b/targets/znews-ss-prediction/rainbow-10.5.6.1.properties index cfc220922..f3b58f741 100644 --- a/targets/znews-ss-prediction/rainbow-10.5.6.1.properties +++ b/targets/znews-ss-prediction/rainbow-10.5.6.1.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.1 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.1 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-prediction/rainbow-10.5.6.3.properties b/targets/znews-ss-prediction/rainbow-10.5.6.3.properties index cd2a3a569..1ae1db5fe 100644 --- a/targets/znews-ss-prediction/rainbow-10.5.6.3.properties +++ b/targets/znews-ss-prediction/rainbow-10.5.6.3.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.3 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.3 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-prediction/rainbow-10.5.6.4.properties b/targets/znews-ss-prediction/rainbow-10.5.6.4.properties index dc87c9608..e2ffde51c 100644 --- a/targets/znews-ss-prediction/rainbow-10.5.6.4.properties +++ b/targets/znews-ss-prediction/rainbow-10.5.6.4.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.4 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.4 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-prediction/rainbow-10.5.6.5.properties b/targets/znews-ss-prediction/rainbow-10.5.6.5.properties index f92704d09..e5cf62d61 100644 --- a/targets/znews-ss-prediction/rainbow-10.5.6.5.properties +++ b/targets/znews-ss-prediction/rainbow-10.5.6.5.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.5 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.5 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-prediction/rainbow-10.5.6.6.properties b/targets/znews-ss-prediction/rainbow-10.5.6.6.properties index 9ea44d2bd..7b9c3b575 100644 --- a/targets/znews-ss-prediction/rainbow-10.5.6.6.properties +++ b/targets/znews-ss-prediction/rainbow-10.5.6.6.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.6 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.6 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss-prediction/rainbow-fir.properties b/targets/znews-ss-prediction/rainbow-fir.properties index d3a02027c..6b602596d 100644 --- a/targets/znews-ss-prediction/rainbow-fir.properties +++ b/targets/znews-ss-prediction/rainbow-fir.properties @@ -1,37 +1,37 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = fir -#rainbow.master.location.host = jarrah -#rainbow.master.location.host = waterfall.able.cs.cmu.edu -#rainbow.master.location.host = fir.wv.cs.cmu.edu -#- Location information of the deployed delegate -rainbow.deployment.location = ${rainbow.master.location.host} -#rainbow.deployment.location = fir.wv.cs.cmu.edu -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = cygwin - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = waterfall.able.cs.cmu.edu -#customize.system.target.2 = phoenix -#customize.system.target.3 = fir -#customize.system.target.3 = fir.wv.cs.cmu.edu -#customize.system.target.size = 4 -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = fir +#rainbow.master.location.host = jarrah +#rainbow.master.location.host = waterfall.able.cs.cmu.edu +#rainbow.master.location.host = fir.wv.cs.cmu.edu +#- Location information of the deployed delegate +rainbow.deployment.location = ${rainbow.master.location.host} +#rainbow.deployment.location = fir.wv.cs.cmu.edu +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = cygwin + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = waterfall.able.cs.cmu.edu +#customize.system.target.2 = phoenix +#customize.system.target.3 = fir +#customize.system.target.3 = fir.wv.cs.cmu.edu +#customize.system.target.size = 4 +customize.system.target.size = 2 diff --git a/targets/znews-ss-prediction/rainbow-maple.properties b/targets/znews-ss-prediction/rainbow-maple.properties index 13d831aba..3decb02c7 100644 --- a/targets/znews-ss-prediction/rainbow-maple.properties +++ b/targets/znews-ss-prediction/rainbow-maple.properties @@ -1,29 +1,29 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = maple -#- Location information of the deployed delegate -rainbow.deployment.location = maple -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = waterfall.able.cs.cmu.edu -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = maple +#- Location information of the deployed delegate +rainbow.deployment.location = maple +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = waterfall.able.cs.cmu.edu +customize.system.target.size = 2 diff --git a/targets/znews-ss-prediction/rainbow-oracle.properties b/targets/znews-ss-prediction/rainbow-oracle.properties index 86a4ae4f1..e6ca2a9b3 100644 --- a/targets/znews-ss-prediction/rainbow-oracle.properties +++ b/targets/znews-ss-prediction/rainbow-oracle.properties @@ -1,32 +1,32 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = jarrah -#- Location information of the deployed delegate -rainbow.deployment.location = oracle -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = oracle -#customize.system.target.2 = phoenix -#customize.system.target.3 = waterfall.able.cs.cmu.edu -#customize.system.target.size = 4 -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = jarrah +#- Location information of the deployed delegate +rainbow.deployment.location = oracle +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = oracle +#customize.system.target.2 = phoenix +#customize.system.target.3 = waterfall.able.cs.cmu.edu +#customize.system.target.size = 4 +customize.system.target.size = 2 diff --git a/targets/znews-ss-prediction/rainbow-waterfall.able.cs.cmu.edu.properties b/targets/znews-ss-prediction/rainbow-waterfall.able.cs.cmu.edu.properties index 6dce5bcda..321152bf1 100644 --- a/targets/znews-ss-prediction/rainbow-waterfall.able.cs.cmu.edu.properties +++ b/targets/znews-ss-prediction/rainbow-waterfall.able.cs.cmu.edu.properties @@ -1,29 +1,29 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = maple -#- Location information of this deployed delegate -rainbow.deployment.location = waterfall.able.cs.cmu.edu -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = waterfall.able.cs.cmu.edu -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = maple +#- Location information of this deployed delegate +rainbow.deployment.location = waterfall.able.cs.cmu.edu +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = waterfall.able.cs.cmu.edu +customize.system.target.size = 2 diff --git a/targets/znews-ss-prediction/rainbow.properties b/targets/znews-ss-prediction/rainbow.properties index 09890a5d1..efb6a05cd 100644 --- a/targets/znews-ss-prediction/rainbow.properties +++ b/targets/znews-ss-prediction/rainbow.properties @@ -1,137 +1,137 @@ -################################################################################ -# Purpose: Common configuration file for the Rainbow infrastructure. -# Properties are loaded by class org.sa.rainbow.Rainbow . -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -### -# Default values for location specific properties, meaning that, if the -# rainbow-.properties file does not specify a value, the default value -# set here is used. - -### Utility mechanism configuration -#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL -logging.level = DEBUG -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log -# (default) -#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" -#logging.max.size = 1024 -#logging.max.backups = 5 - -### Rainbow component customization -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = 127.0.0.1 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.2.2 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.event.service = eseb -eBus Relay - -rainbow.delegate.beaconperiod = 10000 -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory - -#Rainbow models -rainbow.model.number=4 -rainbow.model.path_0 = model/ZNewsSys.acme -rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory -rainbow.model.name_0 = ZNewsSys -rainbow.model.saveOnClose_0=true -rainbow.model.saveLocation_0=model/ZNewSys-post.acme - -rainbow.model.path_1 = stitch/utilities.yml -rainbow.model.load.class_1=org.sa.rainbow.model.utility.UtilityCommandFactory -rainbow.model.name_1=ZNewsSys - -rainbow.model.load.class_2=org.sa.rainbow.model.utility.UtilityHistoryCommandFactory -rainbow.model.name_2=ZNewsSys -rainbow.model.saveOnClose_2=true -rainbow.model.saveLocation_2=model/uh.csv - -rainbow.model.load.class_3= org.sa.rainbow.predictor.model.PredictorModelCommandFactory -rainbow.model.name_3=ZNewsSys - -#Rainbow analyses -rainbow.analyses.size = 2 -rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator - -rainbow.analyses_1 = org.sa.rainbow.evaluator.utility.UtilityEvaluator - -rainbow.analysis_2 = org.sa.rainbow.predictor.analysis.PredictionAnalyzer; -rainbow.analysis.model_2 = ZNewsSys:Predictor - -#Rainbow adaptation & stitch components -rainbow.adaptation.manager.size = 1 -rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager -rainbow.adaptation.manager.model_0=ZNewsSys:Acme - -rainbow.adaptation.executor.size = 1 -rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.Executor -rainbow.adaptation.executor.model_0=ZNewsSys:Acme - -rainbow.effector.manager.size = 1 -rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager - - -customize.model.evaluate.period = 2000 -## Translator customization -#- Gauge spec -customize.gauges.path = model/gauges.yml -#- Probe spec -customize.probes.path = system/probes.yml -#- Operator spec as mapping to effector -customize.archop.map.path = model/op.map -#- Effector spec -customize.effectors.path = system/effectors.yml -## Adaptation Manager -#- Directory of Stitch adaptation script -customize.scripts.path = stitch -#- Utilities description file, Strategy evaluation config, and minimum score threshold -customize.utility.path = stitch/utilities.yml -customize.utility.trackStrategy = uSF -customize.utility.score.minimum.threshold = 0.33 -customize.utility.scenario = scenario 1 -#- Whether to enable prediction, ONLY enable if system has predictor probes! -#customize.prediction.enable = false - -## System configuration information -# -#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: -#customize.system.sim.path = znewspred/znews-transbw.sim -#- if real target system: -#customize.system.target.0 = ${rainbow.master.location.host} -#customize.system.target.1 = 10.0.2.15 -#customize.system.target.1 = waterfall.able.cs.cmu.edu -#customize.system.target.0 = localhost -#customize.system.target.2 = oracle -#customize.system.target.size = 3 -#customize.system.target.size = 2 -customize.system.target.master = ${rainbow.deployment.location} -customize.system.target.lb = 10.5.6.1 -customize.system.target.lb.httpPort = 1081 -customize.system.target.web0 = 10.5.6.3 -customize.system.target.web0.httpPort = 1080 -customize.system.target.web1 = 10.5.6.4 -customize.system.target.web1.httpPort = 1080 -customize.system.target.db = 10.5.6.2 -customize.system.target.web2 = 10.5.6.5 -customize.system.target.web2.httpPort=1080 -customize.system.target.web2.disabled=true -customize.system.target.client1=10.0.0.2 -customize.system.target.client2=10.5.6.6 -customize.system.target.bad=10.5.6.6 -#customize.system.target.0 = ${rainbow.deployment.location} -#customize.system.target.1 = 10.5.6.1 -#customize.system.target.size = 2 +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +logging.level = DEBUG +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = 127.0.0.1 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.2.2 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.event.service = eseb +eBus Relay + +rainbow.delegate.beaconperiod = 10000 +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory + +#Rainbow models +rainbow.model.number=4 +rainbow.model.path_0 = model/ZNewsSys.acme +rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory +rainbow.model.name_0 = ZNewsSys +rainbow.model.saveOnClose_0=true +rainbow.model.saveLocation_0=model/ZNewSys-post.acme + +rainbow.model.path_1 = stitch/utilities.yml +rainbow.model.load.class_1=org.sa.rainbow.model.utility.UtilityCommandFactory +rainbow.model.name_1=ZNewsSys + +rainbow.model.load.class_2=org.sa.rainbow.model.utility.UtilityHistoryCommandFactory +rainbow.model.name_2=ZNewsSys +rainbow.model.saveOnClose_2=true +rainbow.model.saveLocation_2=model/uh.csv + +rainbow.model.load.class_3= org.sa.rainbow.predictor.model.PredictorModelCommandFactory +rainbow.model.name_3=ZNewsSys + +#Rainbow analyses +rainbow.analyses.size = 2 +rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator + +rainbow.analyses_1 = org.sa.rainbow.evaluator.utility.UtilityEvaluator + +rainbow.analysis_2 = org.sa.rainbow.predictor.analysis.PredictionAnalyzer; +rainbow.analysis.model_2 = ZNewsSys:Predictor + +#Rainbow adaptation & stitch components +rainbow.adaptation.manager.size = 1 +rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager +rainbow.adaptation.manager.model_0=ZNewsSys:Acme + +rainbow.adaptation.executor.size = 1 +rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.Executor +rainbow.adaptation.executor.model_0=ZNewsSys:Acme + +rainbow.effector.manager.size = 1 +rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager + + +customize.model.evaluate.period = 2000 +## Translator customization +#- Gauge spec +customize.gauges.path = model/gauges.yml +#- Probe spec +customize.probes.path = system/probes.yml +#- Operator spec as mapping to effector +customize.archop.map.path = model/op.map +#- Effector spec +customize.effectors.path = system/effectors.yml +## Adaptation Manager +#- Directory of Stitch adaptation script +customize.scripts.path = stitch +#- Utilities description file, Strategy evaluation config, and minimum score threshold +customize.utility.path = stitch/utilities.yml +customize.utility.trackStrategy = uSF +customize.utility.score.minimum.threshold = 0.33 +customize.utility.scenario = scenario 1 +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# +#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: +#customize.system.sim.path = znewspred/znews-transbw.sim +#- if real target system: +#customize.system.target.0 = ${rainbow.master.location.host} +#customize.system.target.1 = 10.0.2.15 +#customize.system.target.1 = waterfall.able.cs.cmu.edu +#customize.system.target.0 = localhost +#customize.system.target.2 = oracle +#customize.system.target.size = 3 +#customize.system.target.size = 2 +customize.system.target.master = ${rainbow.deployment.location} +customize.system.target.lb = 10.5.6.1 +customize.system.target.lb.httpPort = 1081 +customize.system.target.web0 = 10.5.6.3 +customize.system.target.web0.httpPort = 1080 +customize.system.target.web1 = 10.5.6.4 +customize.system.target.web1.httpPort = 1080 +customize.system.target.db = 10.5.6.2 +customize.system.target.web2 = 10.5.6.5 +customize.system.target.web2.httpPort=1080 +customize.system.target.web2.disabled=true +customize.system.target.client1=10.0.0.2 +customize.system.target.client2=10.5.6.6 +customize.system.target.bad=10.5.6.6 +#customize.system.target.0 = ${rainbow.deployment.location} +#customize.system.target.1 = 10.5.6.1 +#customize.system.target.size = 2 diff --git a/targets/znews-ss-prediction/rainbow.properties-all-in-one-machine b/targets/znews-ss-prediction/rainbow.properties-all-in-one-machine index f05013820..349283e56 100644 --- a/targets/znews-ss-prediction/rainbow.properties-all-in-one-machine +++ b/targets/znews-ss-prediction/rainbow.properties-all-in-one-machine @@ -1,112 +1,112 @@ -################################################################################ -# Purpose: Common configuration file for the Rainbow infrastructure. -# Properties are loaded by class org.sa.rainbow.Rainbow . -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -### -# Default values for location specific properties, meaning that, if the -# rainbow-.properties file does not specify a value, the default value -# set here is used. - -### Utility mechanism configuration -#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL -logging.level = DEBUG -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log -# (default) -#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" -#logging.max.size = 1024 -#logging.max.backups = 5 - -### Rainbow component customization -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = 127.0.0.1 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.2.2 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.event.service = eseb -eBus Relay - -rainbow.delegate.beaconperiod = 10000 -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory - -#Rainbow models -rainbow.model.number=1 -rainbow.model.path_0 = model/ZNewsSys.acme -rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory -rainbow.model.name_0 = ZNewsSys - -#Rainbow analyses -rainbow.analyses.size = 1 -rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator - -#Rainbow adaptation & stitch components -rainbow.adaptation.manager.size = 1 -rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager -rainbow.adaptation.manager.model_0=ZNewsSys:Acme - -rainbow.adaptation.executor.size = 1 -rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.Executor -rainbow.adaptation.executor.model_0=ZNewsSys:Acme - -rainbow.effector.manager.size = 1 -rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager - - -customize.model.evaluate.period = 2000 -## Translator customization -#- Gauge spec -customize.gauges.path = model/gauges.yml -#- Probe spec -customize.probes.path = system/probes.yml -#- Operator spec as mapping to effector -customize.archop.map.path = model/op.map -#- Effector spec -customize.effectors.path = system/effectors.yml -## Adaptation Manager -#- Directory of Stitch adaptation script -customize.scripts.path = stitch -#- Utilities description file, Strategy evaluation config, and minimum score threshold -customize.utility.path = stitch/utilities.yml -customize.utility.trackStrategy = uSF -customize.utility.score.minimum.threshold = 0.33 -customize.utility.scenario = scenario 2 -#- Whether to enable prediction, ONLY enable if system has predictor probes! -#customize.prediction.enable = false - -## System configuration information -# -#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: -#customize.system.sim.path = znewspred/znews-transbw.sim -#- if real target system: -#customize.system.target.0 = ${rainbow.master.location.host} -#customize.system.target.1 = 10.0.2.15 -#customize.system.target.1 = waterfall.able.cs.cmu.edu -#customize.system.target.0 = localhost -#customize.system.target.2 = oracle -#customize.system.target.size = 3 -#customize.system.target.size = 2 -customize.system.target.master = ${rainbow.deployment.location} -customize.system.target.lb = 10.5.6.1 -customize.system.target.lb.httpPort = 1081 -customize.system.target.web0 = 10.5.6.1 -customize.system.target.web0.httpPort = 1080 -customize.system.target.web1 = 10.5.6.1 -customize.system.target.web1.httpPort = 1082 -customize.system.target.db = 10.5.6.1 -#customize.system.target.0 = ${rainbow.deployment.location} -#customize.system.target.1 = 10.5.6.1 -#customize.system.target.size = 2 +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +logging.level = DEBUG +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = 127.0.0.1 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.2.2 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.event.service = eseb +eBus Relay + +rainbow.delegate.beaconperiod = 10000 +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory + +#Rainbow models +rainbow.model.number=1 +rainbow.model.path_0 = model/ZNewsSys.acme +rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory +rainbow.model.name_0 = ZNewsSys + +#Rainbow analyses +rainbow.analyses.size = 1 +rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator + +#Rainbow adaptation & stitch components +rainbow.adaptation.manager.size = 1 +rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager +rainbow.adaptation.manager.model_0=ZNewsSys:Acme + +rainbow.adaptation.executor.size = 1 +rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.Executor +rainbow.adaptation.executor.model_0=ZNewsSys:Acme + +rainbow.effector.manager.size = 1 +rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager + + +customize.model.evaluate.period = 2000 +## Translator customization +#- Gauge spec +customize.gauges.path = model/gauges.yml +#- Probe spec +customize.probes.path = system/probes.yml +#- Operator spec as mapping to effector +customize.archop.map.path = model/op.map +#- Effector spec +customize.effectors.path = system/effectors.yml +## Adaptation Manager +#- Directory of Stitch adaptation script +customize.scripts.path = stitch +#- Utilities description file, Strategy evaluation config, and minimum score threshold +customize.utility.path = stitch/utilities.yml +customize.utility.trackStrategy = uSF +customize.utility.score.minimum.threshold = 0.33 +customize.utility.scenario = scenario 2 +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# +#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: +#customize.system.sim.path = znewspred/znews-transbw.sim +#- if real target system: +#customize.system.target.0 = ${rainbow.master.location.host} +#customize.system.target.1 = 10.0.2.15 +#customize.system.target.1 = waterfall.able.cs.cmu.edu +#customize.system.target.0 = localhost +#customize.system.target.2 = oracle +#customize.system.target.size = 3 +#customize.system.target.size = 2 +customize.system.target.master = ${rainbow.deployment.location} +customize.system.target.lb = 10.5.6.1 +customize.system.target.lb.httpPort = 1081 +customize.system.target.web0 = 10.5.6.1 +customize.system.target.web0.httpPort = 1080 +customize.system.target.web1 = 10.5.6.1 +customize.system.target.web1.httpPort = 1082 +customize.system.target.db = 10.5.6.1 +#customize.system.target.0 = ${rainbow.deployment.location} +#customize.system.target.1 = 10.5.6.1 +#customize.system.target.size = 2 diff --git a/targets/znews-ss-prediction/stitch/README.txt b/targets/znews-ss-prediction/stitch/README.txt index fe0c94a76..1a5abb8c4 100644 --- a/targets/znews-ss-prediction/stitch/README.txt +++ b/targets/znews-ss-prediction/stitch/README.txt @@ -1,2 +1,2 @@ -Extension: Stitch scripts must have the extension ".s"; otherwise, the -Adaptation Manager will not know to load it. +Extension: Stitch scripts must have the extension ".s"; otherwise, the +Adaptation Manager will not know to load it. diff --git a/targets/znews-ss-prediction/stitch/dosStrategies.s b/targets/znews-ss-prediction/stitch/dosStrategies.s index 8afeca081..a9cc18473 100644 --- a/targets/znews-ss-prediction/stitch/dosStrategies.s +++ b/targets/znews-ss-prediction/stitch/dosStrategies.s @@ -1,104 +1,104 @@ -/* - * Adaptation script for security attacks - */ - -module dos.strategies; -import op "org.sa.rainbow.stitch.lib.*"; -import op "org.sa.rainbow.model.acme.znn.ZNN"; -import lib "dosTactics.s"; -import lib "newssiteTactics.s"; - -//define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); - -define boolean haveMaliciousAndSuspicious = exists c : D.ZNewsClientT in M.components | (c.maliciousness >= M.SUSPICIOUS_THRESHOLD); - -define boolean unhandledMalicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness >= M.MALICIOUS_THRESHOLD) && !((exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.blackholed)) || c.captcha == -1 || c.authenticate == -1)); - -// There are people who are suspicious but haven't been throttled -define boolean unhandledSuspicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness < M.MALICIOUS_THRESHOLD && c.maliciousness > M.SUSPICIOUS_THRESHOLD) && !((exists b : D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.throttled)) || c.captcha == -1 || c.authenticate == -1)); - -// There are clients blackholed that are not malicious -define boolean cUnfairlyPenalizedClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD))); - -// There are clients throttled that are not suspicous -define boolean cUnfairlyThrottledClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSPICOUS_THRESHOLD && c.maliciousness <= M.SUSPICIOUS_THRESHOLD))); - -// We haven't captchaed -define boolean cNotChallenging = exists c : D.ZNewsLBT in M.components | (c.captchaEnabled == false); - -// Non-malicious clients are suffering high response times -define boolean cHiRespTime = exists c : T.ClientT/*,D.ZNewsClientT*/ in M.components | (c.experRespTime > M.MAX_RESPTIME); - -// There is atleast one reserve server available -define boolean serversAvailable = ZNN.availableServices(M,T.ServerT) > 0; - -/* Stop the attack by placing attackers into a blackhole. This strategy is triggered - * by the presence of an attacker and an impact on response time - */ -strategy EliminateStrategy -[ cHiRespTime && (unhandledMalicious || unhandledSuspicious) ] { - t0: (unhandledMalicious || unhandledSuspicious) -> blackholeAttacker() @[5000 /*ms*/] { - t1: (!unhandledMalicious) -> done; - t1a: (unhandledSuspicious) -> throttleSuspicious () @[5000] { - t2a: (default) -> TNULL; // in this case, we have no more steps to take - t2b: (success) -> done; - } - } - t3: (default) -> TNULL; -} - -strategy RestoreStrategy -[cUnfairlyPenalizedClients || cUnfairlyThrottledClients] { - t0: (cUnfairlyPenalizedClients) -> unblackholeAttacker () @[2000 /*ms*/] { - t1 : (!cUnfairlyPenalizedClients) -> done; - t1a: (default) -> TNULL; - } - t2 : (cUnfairlyThrottledClients) -> unthrottle () @[2000] { - t2a: (!cUnfairlyThrottledClients) -> done; - t2b: (default) -> TNULL; - } -} - -strategy Challenge [cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { - t0: (cNotChallenging) -> addCaptcha () @[5000] { - t1: (success) -> done; - t1a: (default) -> TNULL; - } - t2: (!cNotChallenging) -> forceReauthentication () @[5000] { - t3: (success) -> done; - t3a: (default) -> TNULL; - - } -} - - - -strategy DisableChallenges [!haveMaliciousAndSuspicious && !cNotChallenging] { - t0: (!cNotChallenging) -> removeCaptcha () @[1000] { - t1: (cNotChallenging) -> done; - } -} - - -strategy SimpleReduceResponseTime -[cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { - t0: (/*hiLoad*/ cHiRespTime) -> enlistServers(1) @[1000 /*ms*/] { - t1: (!cHiRespTime) -> done; - t2: (cHiRespTime) -> lowerFidelity(2, 100) @[3000 /*ms*/] { - t2a: (!cHiRespTime) -> done; - t2b: (default) -> TNULL; // in this case, we have no more steps to take - } - } -} - -/* This strategy allocates more capacity to counter the impact of a DoS attack. - */ -//strategy IncreaseCapacityStrategy -//[ styleApplies && cHiRespTime && serversAvailable] { -// t0: (/* under attack */ cHiRespTime) -> enlistServer(1) @[1000 /*ms*/] { -// t1: (!cHiRespTime) -> done; -// t1a: (default) -> TNULL; // in this case, we have no more steps to take -// } -//} - - +/* + * Adaptation script for security attacks + */ + +module dos.strategies; +import op "org.sa.rainbow.stitch.lib.*"; +import op "org.sa.rainbow.model.acme.znn.ZNN"; +import lib "dosTactics.s"; +import lib "newssiteTactics.s"; + +//define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); + +define boolean haveMaliciousAndSuspicious = exists c : D.ZNewsClientT in M.components | (c.maliciousness >= M.SUSPICIOUS_THRESHOLD); + +define boolean unhandledMalicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness >= M.MALICIOUS_THRESHOLD) && !((exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.blackholed)) || c.captcha == -1 || c.authenticate == -1)); + +// There are people who are suspicious but haven't been throttled +define boolean unhandledSuspicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness < M.MALICIOUS_THRESHOLD && c.maliciousness > M.SUSPICIOUS_THRESHOLD) && !((exists b : D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.throttled)) || c.captcha == -1 || c.authenticate == -1)); + +// There are clients blackholed that are not malicious +define boolean cUnfairlyPenalizedClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD))); + +// There are clients throttled that are not suspicous +define boolean cUnfairlyThrottledClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSPICOUS_THRESHOLD && c.maliciousness <= M.SUSPICIOUS_THRESHOLD))); + +// We haven't captchaed +define boolean cNotChallenging = exists c : D.ZNewsLBT in M.components | (c.captchaEnabled == false); + +// Non-malicious clients are suffering high response times +define boolean cHiRespTime = exists c : T.ClientT/*,D.ZNewsClientT*/ in M.components | (c.experRespTime > M.MAX_RESPTIME); + +// There is atleast one reserve server available +define boolean serversAvailable = ZNN.availableServices(M,T.ServerT) > 0; + +/* Stop the attack by placing attackers into a blackhole. This strategy is triggered + * by the presence of an attacker and an impact on response time + */ +strategy EliminateStrategy +[ cHiRespTime && (unhandledMalicious || unhandledSuspicious) ] { + t0: (unhandledMalicious || unhandledSuspicious) -> blackholeAttacker() @[5000 /*ms*/] { + t1: (!unhandledMalicious) -> done; + t1a: (unhandledSuspicious) -> throttleSuspicious () @[5000] { + t2a: (default) -> TNULL; // in this case, we have no more steps to take + t2b: (success) -> done; + } + } + t3: (default) -> TNULL; +} + +strategy RestoreStrategy +[cUnfairlyPenalizedClients || cUnfairlyThrottledClients] { + t0: (cUnfairlyPenalizedClients) -> unblackholeAttacker () @[2000 /*ms*/] { + t1 : (!cUnfairlyPenalizedClients) -> done; + t1a: (default) -> TNULL; + } + t2 : (cUnfairlyThrottledClients) -> unthrottle () @[2000] { + t2a: (!cUnfairlyThrottledClients) -> done; + t2b: (default) -> TNULL; + } +} + +strategy Challenge [cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { + t0: (cNotChallenging) -> addCaptcha () @[5000] { + t1: (success) -> done; + t1a: (default) -> TNULL; + } + t2: (!cNotChallenging) -> forceReauthentication () @[5000] { + t3: (success) -> done; + t3a: (default) -> TNULL; + + } +} + + + +strategy DisableChallenges [!haveMaliciousAndSuspicious && !cNotChallenging] { + t0: (!cNotChallenging) -> removeCaptcha () @[1000] { + t1: (cNotChallenging) -> done; + } +} + + +strategy SimpleReduceResponseTime +[cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { + t0: (/*hiLoad*/ cHiRespTime) -> enlistServers(1) @[1000 /*ms*/] { + t1: (!cHiRespTime) -> done; + t2: (cHiRespTime) -> lowerFidelity(2, 100) @[3000 /*ms*/] { + t2a: (!cHiRespTime) -> done; + t2b: (default) -> TNULL; // in this case, we have no more steps to take + } + } +} + +/* This strategy allocates more capacity to counter the impact of a DoS attack. + */ +//strategy IncreaseCapacityStrategy +//[ styleApplies && cHiRespTime && serversAvailable] { +// t0: (/* under attack */ cHiRespTime) -> enlistServer(1) @[1000 /*ms*/] { +// t1: (!cHiRespTime) -> done; +// t1a: (default) -> TNULL; // in this case, we have no more steps to take +// } +//} + + diff --git a/targets/znews-ss-prediction/stitch/dosTactics.s b/targets/znews-ss-prediction/stitch/dosTactics.s index b2db07c05..c1303bcd3 100644 --- a/targets/znews-ss-prediction/stitch/dosTactics.s +++ b/targets/znews-ss-prediction/stitch/dosTactics.s @@ -1,160 +1,160 @@ -module dos.strategies; - -import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T, ZNewsDosFam as D} ; -import op "org.sa.rainbow.stitch.lib.*"; - -//-------------------------------------------------------------------------------------------------- -// ! exists c : ClientT in self.components | (c.isMalicious and !c.is_blackholed) -// -// Failing this would cause the strategy to fire -// In the long run, isMalicious could be a float that captures the probability -// that a client is malicious -- in this case, we would have a threshold value -// -// Countermeasure #3: Black Hole the attacker(s) -// Blackholing means replying with ICMP giving reason for Black hole the attacking -// client by redirecting connections from a client -// for some period of time (i.e. black hole the traffic). -// -tactic blackholeAttacker () { - condition { - exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.blackholed))); - - // currently just checking if the client is identified as malicious. - // exists c:D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD; - } - action { - // Find the attacker. Currently, this is done by checking if client is identified as an attacker - // the blackHole() routine re-routes all traffic from a client away from the backed servers - // thereby preventing attackers from consuming ZNN resources. - // - set evilClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD}; - set blackholedClients = M.LB0.blackholed; - for (T.ClientT target : evilClients) { - blackholedClients = Set.add (blackholedClients, target.deploymentLocation); - } - M.setBlackholed (M.LB0, blackholedClients); - } - effect { - // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? - // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true - // if the client is blackholed and false otherwise - forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.blackholed))); - //forall c:T.ClientT in M.components | (c.maliciousness > M.MALICIOUS_THRESHOLD) -> !c.isBlackholed)); - } -} - -tactic unblackholeAttacker () { - condition { - exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.blackholed) && c.maliciousness <= M.MALICIOUS_THRESHOLD); - } - action { - set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.MALICIOUS_THRESHOLD}; - set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.blackholed) > 0}; - for (D.ZNewsLBT l : lbs) { - set blackholedClients = l.blackholed; - for (D.ZNewsClientT c : reformedClients) { - // Curiously, if the unblackhole is only in the op.map and - // not in the the EffectOp class, then the parameters need - // to be paired with their parameter name - // Thus, (...,"client", c.deploymentLocation) here - // compared to blackhole above, which is actually - // a method provided in the EffectOp class - blackholedClients = Set.remove (blackholedClients, c.deploymentLocation); - } - M.setBlackholed (l, blackholedClients); - } - } - effect { - forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD)); - } -} - -tactic throttleSuspicious () { - condition { - exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.throttled))); - } - action { - // Find the attacker. Currently, this is done by checking if client is identified as an attacker - // the blackHole() routine re-routes all traffic from a client away from the backed servers - // thereby preventing attackers from consuming ZNN resources. - // - set suspciousClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.SUSCPICIOUS_THRESHOLD}; - set throttledClients = M.LB0.throttled; - for (T.ClientT target : suspciousClients) { - throttledClients = Set.add (throttledClients, target.deploymentLocation); - } - M.setThrottled (M.LB0, throttledClients); - } - effect { - // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? - // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true - // if the client is blackholed and false otherwise - forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.throttled))); - } -} - -tactic unthrottle () { - condition { - exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.throttled) && c.maliciousness <= M.SUSCPICIOUS_THRESHOLD); - } - action { - set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.SUSCPICIOUS_THRESHOLD}; - set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.throttled) > 0}; - for (D.ZNewsLBT l : lbs) { - set throttledClients = l.throttled; - for (D.ZNewsClientT c : reformedClients) { - throttledClients = Set.remove (throttledClients, c.deploymentLocation); - } - M.setThrottled (l, throttledClients); - } - } - effect { - forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSCPICIOUS_THRESHOLD)); - } -} - -tactic forceReauthentication () { - condition { - true; - } - action { - for (ProxyT lb : M.components) { - M.forceReauthentication (lb); - } - } - effect { - true; - } -} - -tactic addCaptcha () { - condition { - exists lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; - } - action { - set lbs = {select l : D.ZNewsLBT in M.components | !l.captchaEnabled}; - for (D.ZNewsLBT l : lbs) { - M.setCaptchaEnabled (l, true); - } - } - effect { - forall lb:D.ZNewsLBT in M.components | lb.captchaEnabled; - } -} - -tactic removeCaptcha () { - condition { - exists lb:D.ZNewsLBT in M.components | lb.captchaEnabled; - } - action { - set lbs = {select l : D.ZNewsLBT in M.components | l.captchaEnabled}; - for (D.ZNewsLBT l : lbs) { - M.setCaptchaEnabled (l, false); - } - } - effect { - forall lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; - } -} - - +module dos.strategies; + +import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T, ZNewsDosFam as D} ; +import op "org.sa.rainbow.stitch.lib.*"; + +//-------------------------------------------------------------------------------------------------- +// ! exists c : ClientT in self.components | (c.isMalicious and !c.is_blackholed) +// +// Failing this would cause the strategy to fire +// In the long run, isMalicious could be a float that captures the probability +// that a client is malicious -- in this case, we would have a threshold value +// +// Countermeasure #3: Black Hole the attacker(s) +// Blackholing means replying with ICMP giving reason for Black hole the attacking +// client by redirecting connections from a client +// for some period of time (i.e. black hole the traffic). +// +tactic blackholeAttacker () { + condition { + exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.blackholed))); + + // currently just checking if the client is identified as malicious. + // exists c:D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD; + } + action { + // Find the attacker. Currently, this is done by checking if client is identified as an attacker + // the blackHole() routine re-routes all traffic from a client away from the backed servers + // thereby preventing attackers from consuming ZNN resources. + // + set evilClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD}; + set blackholedClients = M.LB0.blackholed; + for (T.ClientT target : evilClients) { + blackholedClients = Set.add (blackholedClients, target.deploymentLocation); + } + M.setBlackholed (M.LB0, blackholedClients); + } + effect { + // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? + // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true + // if the client is blackholed and false otherwise + forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.blackholed))); + //forall c:T.ClientT in M.components | (c.maliciousness > M.MALICIOUS_THRESHOLD) -> !c.isBlackholed)); + } +} + +tactic unblackholeAttacker () { + condition { + exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.blackholed) && c.maliciousness <= M.MALICIOUS_THRESHOLD); + } + action { + set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.MALICIOUS_THRESHOLD}; + set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.blackholed) > 0}; + for (D.ZNewsLBT l : lbs) { + set blackholedClients = l.blackholed; + for (D.ZNewsClientT c : reformedClients) { + // Curiously, if the unblackhole is only in the op.map and + // not in the the EffectOp class, then the parameters need + // to be paired with their parameter name + // Thus, (...,"client", c.deploymentLocation) here + // compared to blackhole above, which is actually + // a method provided in the EffectOp class + blackholedClients = Set.remove (blackholedClients, c.deploymentLocation); + } + M.setBlackholed (l, blackholedClients); + } + } + effect { + forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD)); + } +} + +tactic throttleSuspicious () { + condition { + exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.throttled))); + } + action { + // Find the attacker. Currently, this is done by checking if client is identified as an attacker + // the blackHole() routine re-routes all traffic from a client away from the backed servers + // thereby preventing attackers from consuming ZNN resources. + // + set suspciousClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.SUSCPICIOUS_THRESHOLD}; + set throttledClients = M.LB0.throttled; + for (T.ClientT target : suspciousClients) { + throttledClients = Set.add (throttledClients, target.deploymentLocation); + } + M.setThrottled (M.LB0, throttledClients); + } + effect { + // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? + // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true + // if the client is blackholed and false otherwise + forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.throttled))); + } +} + +tactic unthrottle () { + condition { + exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.throttled) && c.maliciousness <= M.SUSCPICIOUS_THRESHOLD); + } + action { + set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.SUSCPICIOUS_THRESHOLD}; + set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.throttled) > 0}; + for (D.ZNewsLBT l : lbs) { + set throttledClients = l.throttled; + for (D.ZNewsClientT c : reformedClients) { + throttledClients = Set.remove (throttledClients, c.deploymentLocation); + } + M.setThrottled (l, throttledClients); + } + } + effect { + forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSCPICIOUS_THRESHOLD)); + } +} + +tactic forceReauthentication () { + condition { + true; + } + action { + for (ProxyT lb : M.components) { + M.forceReauthentication (lb); + } + } + effect { + true; + } +} + +tactic addCaptcha () { + condition { + exists lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; + } + action { + set lbs = {select l : D.ZNewsLBT in M.components | !l.captchaEnabled}; + for (D.ZNewsLBT l : lbs) { + M.setCaptchaEnabled (l, true); + } + } + effect { + forall lb:D.ZNewsLBT in M.components | lb.captchaEnabled; + } +} + +tactic removeCaptcha () { + condition { + exists lb:D.ZNewsLBT in M.components | lb.captchaEnabled; + } + action { + set lbs = {select l : D.ZNewsLBT in M.components | l.captchaEnabled}; + for (D.ZNewsLBT l : lbs) { + M.setCaptchaEnabled (l, false); + } + } + effect { + forall lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; + } +} + + diff --git a/targets/znews-ss-prediction/stitch/newssiteTactics.s b/targets/znews-ss-prediction/stitch/newssiteTactics.s index 891770c68..41d6ad58a 100644 --- a/targets/znews-ss-prediction/stitch/newssiteTactics.s +++ b/targets/znews-ss-prediction/stitch/newssiteTactics.s @@ -1,118 +1,118 @@ -module newssite.tactics; - -import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T}; -import op "org.sa.rainbow.stitch.lib.*"; -import op "org.sa.rainbow.model.acme.znn.ZNN"; - - -/** - * Enlist n free servers into service pool. - * Utility: [v] R; [^] C; [<>] F - */ -tactic enlistServers (int n) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // there should be enough available server resources - ZNN.availableServices(M, T.ServerT) >= n; - } - action { - set servers = Set.randomSubset(ZNN.findServices(M, T.ServerT), n); - for (T.ServerT freeSvr : servers) { - M.enableServer (freeSvr, true); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Deactivate n servers from service pool into free pool. - * Utility: [^] R; [v] C; [<>] F - */ -tactic dischargeServers (int n) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there should be enough servers to discharge - Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; - } - action { - set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; - set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); - for (T.ServerT s : subLowUtilSvrs) { - M.enableServer (s, false); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Lowers fidelity by integral steps for percent of requests. - * Utility: [v] R; [v] C; [v] F - */ -tactic lowerFidelity (int step, float fracReq) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // exists server with fidelity to lower - exists s : T.ServerT in M.components | s.fidelity > step; - } - action { - // retrieve set of servers who still have enough fidelity grade to lower - set servers = { select s : T.ServerT in M.components | s.fidelity > step }; - for (T.ServerT s : servers) { - M.setFidelity(s, s.fidelity - step); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Raises fidelity by integral steps for percent of requests. - * Utility: [^] R; [^] C; [^] F - */ -tactic raiseFidelity (int step, float fracReq) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there exists some client with below low-threshold response time - exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - } - action { - // first find the lowest fidelity set - set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; -/* smarter way of doing things... - int lowestFidelity = M.MAX_FIDELITY_LEVEL; - for (T.ServerT s : servers) { - if (s.fidelity < lowestFidelity) { - lowestFidelity = s.fidelity; - } - } - // find only servers with this lowest fidelity setting, and raise fidelity - servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; -*/ - for (T.ServerT s : servers) { - M.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/* - T5) delayClients(set clients) - utility: [^] R; [v] C; [v] F - T6) blockClients(set clients) - utility: [^] R; [v] C; [v] F -*/ +module newssite.tactics; + +import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T}; +import op "org.sa.rainbow.stitch.lib.*"; +import op "org.sa.rainbow.model.acme.znn.ZNN"; + + +/** + * Enlist n free servers into service pool. + * Utility: [v] R; [^] C; [<>] F + */ +tactic enlistServers (int n) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // there should be enough available server resources + ZNN.availableServices(M, T.ServerT) >= n; + } + action { + set servers = Set.randomSubset(ZNN.findServices(M, T.ServerT), n); + for (T.ServerT freeSvr : servers) { + M.enableServer (freeSvr, true); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Deactivate n servers from service pool into free pool. + * Utility: [^] R; [v] C; [<>] F + */ +tactic dischargeServers (int n) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there should be enough servers to discharge + Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; + } + action { + set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; + set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); + for (T.ServerT s : subLowUtilSvrs) { + M.enableServer (s, false); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Lowers fidelity by integral steps for percent of requests. + * Utility: [v] R; [v] C; [v] F + */ +tactic lowerFidelity (int step, float fracReq) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // exists server with fidelity to lower + exists s : T.ServerT in M.components | s.fidelity > step; + } + action { + // retrieve set of servers who still have enough fidelity grade to lower + set servers = { select s : T.ServerT in M.components | s.fidelity > step }; + for (T.ServerT s : servers) { + M.setFidelity(s, s.fidelity - step); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Raises fidelity by integral steps for percent of requests. + * Utility: [^] R; [^] C; [^] F + */ +tactic raiseFidelity (int step, float fracReq) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there exists some client with below low-threshold response time + exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + } + action { + // first find the lowest fidelity set + set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; +/* smarter way of doing things... + int lowestFidelity = M.MAX_FIDELITY_LEVEL; + for (T.ServerT s : servers) { + if (s.fidelity < lowestFidelity) { + lowestFidelity = s.fidelity; + } + } + // find only servers with this lowest fidelity setting, and raise fidelity + servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; +*/ + for (T.ServerT s : servers) { + M.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/* + T5) delayClients(set clients) + utility: [^] R; [v] C; [v] F + T6) blockClients(set clients) + utility: [^] R; [v] C; [v] F +*/ diff --git a/targets/znews-ss-prediction/stitch/old/newssiteStrategies.s b/targets/znews-ss-prediction/stitch/old/newssiteStrategies.s index 3eef21719..55f3bf8a9 100644 --- a/targets/znews-ss-prediction/stitch/old/newssiteStrategies.s +++ b/targets/znews-ss-prediction/stitch/old/newssiteStrategies.s @@ -1,117 +1,117 @@ -/* - * Adaptation script for the News Site example. - */ - -module newssite.strategies; - -import lib "newssiteTactics.s"; - -define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); -define boolean cViolation = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - -define set servers = {select s : T.ServerT in M.components | true}; -define set unhappyClients = {select c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME}; -define int numClients = Set.size({select c : T.ClientT in M.components | true}); -define int numUnhappy = Set.size(unhappyClients); -define float numUnhappyFloat = 1.0*numUnhappy; - -define boolean hiLoad = exists s : T.ServerT in M.components | s.load > M.MAX_UTIL; -define boolean hiRespTime = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; -define boolean lowRespTime = exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - -define float totalCost = Model.sumOverProperty("cost", servers); -define boolean hiCost = totalCost >= M.THRESHOLD_COST; - -define float avgFidelity = Model.sumOverProperty("fidelity", servers) / Set.size(servers); -define boolean lowFi = avgFidelity < M.THRESHOLD_FIDELITY; - -/* This Strategy is simple in that, while it encounters any anomaly in - * experienced response time, it firsts enlists one new server, then lowers - * fidelity one step, and quits - */ -strategy SimpleReduceResponseTime -[ styleApplies && cViolation ] { - t0: (/*hiLoad*/ cViolation) -> enlistServers(1) @[1000 /*ms*/] { - t1: (!cViolation) -> done; - t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[3000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> TNULL; // in this case, we have no more steps to take - } - } -} - -/* This Strategy is smarter in that it looks for a percentage of clients with - * anomalous experienced response time, in which case it enlists a few servers - * in sequence, then lowers fidelity a few steps, then starts delaying Clients - */ -strategy SmarterReduceResponseTime -[ styleApplies && cViolation ] { - define boolean unhappy = numUnhappyFloat/numClients > M.TOLERABLE_PERCENT_UNHAPPY; - - t0: (unhappy) -> enlistServers(1) @[500 /*ms*/] { - t1: (!cViolation) -> done; - t2: (unhappy) -> enlistServers(1) @[2000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (unhappy) -> lowerFidelity(2, 100) @[2000 /*ms*/] { - t2b1: (!cViolation) -> done; - t2b2: (unhappy) -> do[1] t2; - t2b3: (default) -> TNULL; // in this case, we have no more steps to take - } - } - } -} - -/* This Strategy (experimental!) has the sophistication of reducing fidelity - * for a percentage of requests depending on percentage of unhappy clients - */ -strategy SophisticatedReduceResponseTime -[ styleApplies && cViolation && M.SUPPORT_FRACTION_GRADIENT ] { - define boolean unhappy1 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_1; // e.g., 10% - define boolean unhappy2 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_2; // e.g., 25% - define boolean unhappy3 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_3; // e.g., 50% - - t1: (hiLoad) -> enlistServers(2) @[500 /*ms*/] { - t1a: (!cViolation) -> done; - t1b: (default) -> TNULL; - } - t2: (unhappy1) -> lowerFidelity(1, M.FRACTION_GRADIENT_1) @[500 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> do[1] t1; - } - t3: (unhappy2) -> lowerFidelity(2, M.FRACTION_GRADIENT_2) @[500 /*ms*/] { - t3a: (!cViolation) -> done; - t3b: (default) -> do[1] t1; - } - t4: (unhappy3) -> lowerFidelity(4, M.FRACTION_GRADIENT_3) @[500 /*ms*/] { - t4a: (!cViolation) -> done; - t4b: (unhappy3) -> enlistServers(2) @[1000 /*ms*/] { - t4b1: (!cViolation) -> done; - t4b2: (default) -> do[1] t1; - } - t4c: (default) -> do[1] t1; - } -} - -/* This Strategy is triggered by the total server costs rising above acceptable - * threshold; this Strategy reduces the number of active servers - */ -strategy ReduceOverallCost -[ styleApplies && hiCost ] { - t0: (hiCost) -> dischargeServers(1) @[2000 /*ms*/] { - t1: (!hiCost) -> done; - t2: (lowRespTime && hiCost) -> do[2] t0; - t3: (default) -> TNULL; - } -} - -/* This Strategy is triggered by overall fidelity being below acceptable - * threshold; this Strategy raises the fidelity of the servers - */ -strategy ImproveOverallFidelity -[ styleApplies && lowFi ] { - t0: (lowFi) -> raiseFidelity(2, 100) @[800 /*ms*/] { - t1: (!lowFi) -> done; - t2: (lowRespTime && lowFi) -> do[1] t0; - t3: (default) -> TNULL; - } -} +/* + * Adaptation script for the News Site example. + */ + +module newssite.strategies; + +import lib "newssiteTactics.s"; + +define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); +define boolean cViolation = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + +define set servers = {select s : T.ServerT in M.components | true}; +define set unhappyClients = {select c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME}; +define int numClients = Set.size({select c : T.ClientT in M.components | true}); +define int numUnhappy = Set.size(unhappyClients); +define float numUnhappyFloat = 1.0*numUnhappy; + +define boolean hiLoad = exists s : T.ServerT in M.components | s.load > M.MAX_UTIL; +define boolean hiRespTime = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; +define boolean lowRespTime = exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + +define float totalCost = Model.sumOverProperty("cost", servers); +define boolean hiCost = totalCost >= M.THRESHOLD_COST; + +define float avgFidelity = Model.sumOverProperty("fidelity", servers) / Set.size(servers); +define boolean lowFi = avgFidelity < M.THRESHOLD_FIDELITY; + +/* This Strategy is simple in that, while it encounters any anomaly in + * experienced response time, it firsts enlists one new server, then lowers + * fidelity one step, and quits + */ +strategy SimpleReduceResponseTime +[ styleApplies && cViolation ] { + t0: (/*hiLoad*/ cViolation) -> enlistServers(1) @[1000 /*ms*/] { + t1: (!cViolation) -> done; + t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[3000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> TNULL; // in this case, we have no more steps to take + } + } +} + +/* This Strategy is smarter in that it looks for a percentage of clients with + * anomalous experienced response time, in which case it enlists a few servers + * in sequence, then lowers fidelity a few steps, then starts delaying Clients + */ +strategy SmarterReduceResponseTime +[ styleApplies && cViolation ] { + define boolean unhappy = numUnhappyFloat/numClients > M.TOLERABLE_PERCENT_UNHAPPY; + + t0: (unhappy) -> enlistServers(1) @[500 /*ms*/] { + t1: (!cViolation) -> done; + t2: (unhappy) -> enlistServers(1) @[2000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (unhappy) -> lowerFidelity(2, 100) @[2000 /*ms*/] { + t2b1: (!cViolation) -> done; + t2b2: (unhappy) -> do[1] t2; + t2b3: (default) -> TNULL; // in this case, we have no more steps to take + } + } + } +} + +/* This Strategy (experimental!) has the sophistication of reducing fidelity + * for a percentage of requests depending on percentage of unhappy clients + */ +strategy SophisticatedReduceResponseTime +[ styleApplies && cViolation && M.SUPPORT_FRACTION_GRADIENT ] { + define boolean unhappy1 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_1; // e.g., 10% + define boolean unhappy2 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_2; // e.g., 25% + define boolean unhappy3 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_3; // e.g., 50% + + t1: (hiLoad) -> enlistServers(2) @[500 /*ms*/] { + t1a: (!cViolation) -> done; + t1b: (default) -> TNULL; + } + t2: (unhappy1) -> lowerFidelity(1, M.FRACTION_GRADIENT_1) @[500 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> do[1] t1; + } + t3: (unhappy2) -> lowerFidelity(2, M.FRACTION_GRADIENT_2) @[500 /*ms*/] { + t3a: (!cViolation) -> done; + t3b: (default) -> do[1] t1; + } + t4: (unhappy3) -> lowerFidelity(4, M.FRACTION_GRADIENT_3) @[500 /*ms*/] { + t4a: (!cViolation) -> done; + t4b: (unhappy3) -> enlistServers(2) @[1000 /*ms*/] { + t4b1: (!cViolation) -> done; + t4b2: (default) -> do[1] t1; + } + t4c: (default) -> do[1] t1; + } +} + +/* This Strategy is triggered by the total server costs rising above acceptable + * threshold; this Strategy reduces the number of active servers + */ +strategy ReduceOverallCost +[ styleApplies && hiCost ] { + t0: (hiCost) -> dischargeServers(1) @[2000 /*ms*/] { + t1: (!hiCost) -> done; + t2: (lowRespTime && hiCost) -> do[2] t0; + t3: (default) -> TNULL; + } +} + +/* This Strategy is triggered by overall fidelity being below acceptable + * threshold; this Strategy raises the fidelity of the servers + */ +strategy ImproveOverallFidelity +[ styleApplies && lowFi ] { + t0: (lowFi) -> raiseFidelity(2, 100) @[800 /*ms*/] { + t1: (!lowFi) -> done; + t2: (lowRespTime && lowFi) -> do[1] t0; + t3: (default) -> TNULL; + } +} diff --git a/targets/znews-ss-prediction/stitch/old/newssiteTactics.s b/targets/znews-ss-prediction/stitch/old/newssiteTactics.s index a0efdb740..0684601ef 100644 --- a/targets/znews-ss-prediction/stitch/old/newssiteTactics.s +++ b/targets/znews-ss-prediction/stitch/old/newssiteTactics.s @@ -1,118 +1,118 @@ -module newssite.tactics; - -import model "ZNewsSys.acme" { ZNewsSys as M, ZNewsFam as T }; -import op "znews1.operator.EffectOp" { EffectOp as S }; -import op "org.sa.rainbow.stitch.lib.*"; - - -/** - * Enlist n free servers into service pool. - * Utility: [v] R; [^] C; [<>] F - */ -tactic enlistServers (int n) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // there should be enough available server resources - Model.availableServices(T.ServerT) >= n; - } - action { - set servers = Set.randomSubset(Model.findServices(T.ServerT), n); - for (T.ServerT freeSvr : servers) { - S.activateServer(freeSvr); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Deactivate n servers from service pool into free pool. - * Utility: [^] R; [v] C; [<>] F - */ -tactic dischargeServers (int n) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there should be enough servers to discharge - Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; - } - action { - set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; - set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); - for (T.ServerT s : subLowUtilSvrs) { - S.deactivateServer(s); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Lowers fidelity by integral steps for percent of requests. - * Utility: [v] R; [v] C; [v] F - */ -tactic lowerFidelity (int step, float fracReq) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // exists server with fidelity to lower - exists s : T.ServerT in M.components | s.fidelity > step; - } - action { - // retrieve set of servers who still have enough fidelity grade to lower - set servers = { select s : T.ServerT in M.components | s.fidelity > step }; - for (T.ServerT s : servers) { - S.setFidelity(s, s.fidelity - step); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Raises fidelity by integral steps for percent of requests. - * Utility: [^] R; [^] C; [^] F - */ -tactic raiseFidelity (int step, float fracReq) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there exists some client with below low-threshold response time - exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - } - action { - // first find the lowest fidelity set - set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; -/* smarter way of doing things... - int lowestFidelity = M.MAX_FIDELITY_LEVEL; - for (T.ServerT s : servers) { - if (s.fidelity < lowestFidelity) { - lowestFidelity = s.fidelity; - } - } - // find only servers with this lowest fidelity setting, and raise fidelity - servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; -*/ - for (T.ServerT s : servers) { - S.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/* - T5) delayClients(set clients) - utility: [^] R; [v] C; [v] F - T6) blockClients(set clients) - utility: [^] R; [v] C; [v] F -*/ +module newssite.tactics; + +import model "ZNewsSys.acme" { ZNewsSys as M, ZNewsFam as T }; +import op "znews1.operator.EffectOp" { EffectOp as S }; +import op "org.sa.rainbow.stitch.lib.*"; + + +/** + * Enlist n free servers into service pool. + * Utility: [v] R; [^] C; [<>] F + */ +tactic enlistServers (int n) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // there should be enough available server resources + Model.availableServices(T.ServerT) >= n; + } + action { + set servers = Set.randomSubset(Model.findServices(T.ServerT), n); + for (T.ServerT freeSvr : servers) { + S.activateServer(freeSvr); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Deactivate n servers from service pool into free pool. + * Utility: [^] R; [v] C; [<>] F + */ +tactic dischargeServers (int n) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there should be enough servers to discharge + Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; + } + action { + set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; + set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); + for (T.ServerT s : subLowUtilSvrs) { + S.deactivateServer(s); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Lowers fidelity by integral steps for percent of requests. + * Utility: [v] R; [v] C; [v] F + */ +tactic lowerFidelity (int step, float fracReq) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // exists server with fidelity to lower + exists s : T.ServerT in M.components | s.fidelity > step; + } + action { + // retrieve set of servers who still have enough fidelity grade to lower + set servers = { select s : T.ServerT in M.components | s.fidelity > step }; + for (T.ServerT s : servers) { + S.setFidelity(s, s.fidelity - step); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Raises fidelity by integral steps for percent of requests. + * Utility: [^] R; [^] C; [^] F + */ +tactic raiseFidelity (int step, float fracReq) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there exists some client with below low-threshold response time + exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + } + action { + // first find the lowest fidelity set + set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; +/* smarter way of doing things... + int lowestFidelity = M.MAX_FIDELITY_LEVEL; + for (T.ServerT s : servers) { + if (s.fidelity < lowestFidelity) { + lowestFidelity = s.fidelity; + } + } + // find only servers with this lowest fidelity setting, and raise fidelity + servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; +*/ + for (T.ServerT s : servers) { + S.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/* + T5) delayClients(set clients) + utility: [^] R; [v] C; [v] F + T6) blockClients(set clients) + utility: [^] R; [v] C; [v] F +*/ diff --git a/targets/znews-ss-prediction/stitch/utilities.yml b/targets/znews-ss-prediction/stitch/utilities.yml index 057e48819..b1afa7129 100644 --- a/targets/znews-ss-prediction/stitch/utilities.yml +++ b/targets/znews-ss-prediction/stitch/utilities.yml @@ -1,151 +1,151 @@ -# Created October 22nd, 2013 (Javier Camara) -# -# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y -# is the utility in the range [0,1] -# -# History: -# - [JC 2013.10.22] Created file, defined utilities for Dos Attack Demo. -# - [JC 2013.11.1] Added user annoyance to the utility profile. -model: - name: ZNewsSys - type: Acme -utilities: - uR: - label: "Average Response Time" - mapping: "[EAvg]ClientT.experRespTime" - description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" - utility: - 0: 1.00 - 100: 1.00 - 200: 0.99 - 500: 0.90 - 1000: 0.75 - 1500: 0.50 - 2000: 0.25 - 4000: 0.00 - uC: - label: "Average Server Cost" - mapping: "[EXPR]size(/self/components:ServerT[isArchEnabled])" - description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers. Adapted to a 3-server configuration." - utility: - 0: 1.00 - 1: 0.90 - 2: 0.30 - 3: 0.10 - uM: - label: "Malicious Clients" - mapping: "[EXPR](2*size(/self/components:PotentiallyMaliciousT[maliciousness > self.MALICIOUS_THRESHOLD]))/(size(/self/components:PotentiallyMaliciousT)+1)*100" - description: "Percentage of malicious clients." - utility: - 0: 1.00 - 5: 1.00 - 20: 0.80 - 50: 0.40 - 70: 0.00 - uA: - label: "Average User Annoyance" - mapping: "[EAvg]ClientT.annoyance" - description: "Client experienced annoyance level, should be defined as an int property 'ClientT.annoyance' in the architecture, with a range 0-100" - utility: - 0: 1.00 - 100: 0.00 - -# Weighted utility preferences, each set should sum to 1. -# Three scenarios: -# 1.) Priority is given to eliminating malicious clients. -# 2.) Priority is given to optimizing good client experience (both serving them in a timely manner, and minimizing annoyance). -# 3.) Priority is given to keeping cost down. -# Note: Original Weight of uR is now split 50/50% among uR and uA in every scenario. -weights: - scenario 1: - uR: 0.15 - uM: 0.6 - uC: 0.1 - uA: 0.15 - scenario 2: - uR: 0.3 - uM: 0.3 - uC: 0.1 - uA: 0.3 - scenario 3: - uR: 0.2 - uM: 0.2 - uC: 0.4 - uA: 0.2 - -# Tactic quality attribute vectors -# -vectors: -# Utility: [^] R; [<>] M; [v] C; [<>]A -# assume each server will drop response time by 1000 ms and increase cost by 1 unit - enlistServers: - uR: -1000 - uM: 0 - uC: +1.00 - uA: 0 - -# Utility: [^] R; [<>] M; [^] C; [v]A -# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit, increases annoyance of users 5% for low-quality service - lowerFidelity: - uR: -500 - uM: 0 - uC: -0.10 - uA: +5 - -# Utility: [^] R; [^] M; [v] C; [v]A -# assume that adding the captcha reduces response time by 250 ms, reduces level of malicious users by 90%, increases cost 1/2 unit, and increases user annoyance by 50% - addCaptcha: - uR: -250 - uM: -90 - uC: +0.50 - uA: +50 - -# Utility: [^] R; [^] M; [<>] C; [v]A -# assume that forcing users to reauthenticate reduces response time by 250 ms, reduces level of malicious users by 70%, and increases user annoyance by 50% - forceReauthentication: - uR: -250 - uM: -70 - uC: 0.00 - uA: +50 - -# Utility: [^] R; [^] M; [<>] C; [v]A -# assume that blackholing potential attackers reduces response time by 1000 ms, reduces level of malicious users by 100%, and increases user annoyance by 100% - blackholeAttacker: - uR: -1000 - uM: -100 - uC: 0.00 - uA: +50 - -# Utility: [^] R; [<>] M; [<>] C; [v]A -# assume that throttling suspicious clients reduces response time by 500 ms, and increases user annoyance by 50% - throttleSuspicious: - uR: -500 -# uM may need to change if we decide to substitute % of malicious clients by % of malicious user throughput - uM: 0 - uC: 0.00 - uA: +25 - -# Utility: [^] R; [<>] M; [^] C; [^]A -# assume that removing the captcha reduces cost 1/2 unit, and reduces user annoyance by 50% - removeCaptcha: - uR: -500 - uM: 0 - uC: -0.50 - uA: -50 - -# Utility: [<>] R; [<>] M; [<>] C; [^]A -# assume that removing the captcha reduces user annoyance by 100% - unblackholeAttacker: - uR: 0 - uM: 0 - uC: 0.00 - uA: -100 - -# Utility: [<>] R; [<>] M; [<>] C; [^]A -# assume that unthrottling suspicious clients reduces user annoyance by 50% - unthrottle: - uR: 0 - uM: 0 - uC: 0.00 - uA: -50 - +# Created October 22nd, 2013 (Javier Camara) +# +# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y +# is the utility in the range [0,1] +# +# History: +# - [JC 2013.10.22] Created file, defined utilities for Dos Attack Demo. +# - [JC 2013.11.1] Added user annoyance to the utility profile. +model: + name: ZNewsSys + type: Acme +utilities: + uR: + label: "Average Response Time" + mapping: "[EAvg]ClientT.experRespTime" + description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" + utility: + 0: 1.00 + 100: 1.00 + 200: 0.99 + 500: 0.90 + 1000: 0.75 + 1500: 0.50 + 2000: 0.25 + 4000: 0.00 + uC: + label: "Average Server Cost" + mapping: "[EXPR]size(/self/components:ServerT[isArchEnabled])" + description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers. Adapted to a 3-server configuration." + utility: + 0: 1.00 + 1: 0.90 + 2: 0.30 + 3: 0.10 + uM: + label: "Malicious Clients" + mapping: "[EXPR](2*size(/self/components:PotentiallyMaliciousT[maliciousness > self.MALICIOUS_THRESHOLD]))/(size(/self/components:PotentiallyMaliciousT)+1)*100" + description: "Percentage of malicious clients." + utility: + 0: 1.00 + 5: 1.00 + 20: 0.80 + 50: 0.40 + 70: 0.00 + uA: + label: "Average User Annoyance" + mapping: "[EAvg]ClientT.annoyance" + description: "Client experienced annoyance level, should be defined as an int property 'ClientT.annoyance' in the architecture, with a range 0-100" + utility: + 0: 1.00 + 100: 0.00 + +# Weighted utility preferences, each set should sum to 1. +# Three scenarios: +# 1.) Priority is given to eliminating malicious clients. +# 2.) Priority is given to optimizing good client experience (both serving them in a timely manner, and minimizing annoyance). +# 3.) Priority is given to keeping cost down. +# Note: Original Weight of uR is now split 50/50% among uR and uA in every scenario. +weights: + scenario 1: + uR: 0.15 + uM: 0.6 + uC: 0.1 + uA: 0.15 + scenario 2: + uR: 0.3 + uM: 0.3 + uC: 0.1 + uA: 0.3 + scenario 3: + uR: 0.2 + uM: 0.2 + uC: 0.4 + uA: 0.2 + +# Tactic quality attribute vectors +# +vectors: +# Utility: [^] R; [<>] M; [v] C; [<>]A +# assume each server will drop response time by 1000 ms and increase cost by 1 unit + enlistServers: + uR: -1000 + uM: 0 + uC: +1.00 + uA: 0 + +# Utility: [^] R; [<>] M; [^] C; [v]A +# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit, increases annoyance of users 5% for low-quality service + lowerFidelity: + uR: -500 + uM: 0 + uC: -0.10 + uA: +5 + +# Utility: [^] R; [^] M; [v] C; [v]A +# assume that adding the captcha reduces response time by 250 ms, reduces level of malicious users by 90%, increases cost 1/2 unit, and increases user annoyance by 50% + addCaptcha: + uR: -250 + uM: -90 + uC: +0.50 + uA: +50 + +# Utility: [^] R; [^] M; [<>] C; [v]A +# assume that forcing users to reauthenticate reduces response time by 250 ms, reduces level of malicious users by 70%, and increases user annoyance by 50% + forceReauthentication: + uR: -250 + uM: -70 + uC: 0.00 + uA: +50 + +# Utility: [^] R; [^] M; [<>] C; [v]A +# assume that blackholing potential attackers reduces response time by 1000 ms, reduces level of malicious users by 100%, and increases user annoyance by 100% + blackholeAttacker: + uR: -1000 + uM: -100 + uC: 0.00 + uA: +50 + +# Utility: [^] R; [<>] M; [<>] C; [v]A +# assume that throttling suspicious clients reduces response time by 500 ms, and increases user annoyance by 50% + throttleSuspicious: + uR: -500 +# uM may need to change if we decide to substitute % of malicious clients by % of malicious user throughput + uM: 0 + uC: 0.00 + uA: +25 + +# Utility: [^] R; [<>] M; [^] C; [^]A +# assume that removing the captcha reduces cost 1/2 unit, and reduces user annoyance by 50% + removeCaptcha: + uR: -500 + uM: 0 + uC: -0.50 + uA: -50 + +# Utility: [<>] R; [<>] M; [<>] C; [^]A +# assume that removing the captcha reduces user annoyance by 100% + unblackholeAttacker: + uR: 0 + uM: 0 + uC: 0.00 + uA: -100 + +# Utility: [<>] R; [<>] M; [<>] C; [^]A +# assume that unthrottling suspicious clients reduces user annoyance by 50% + unthrottle: + uR: 0 + uM: 0 + uC: 0.00 + uA: -50 + diff --git a/targets/znews-ss-prediction/system/debpkgs.txt b/targets/znews-ss-prediction/system/debpkgs.txt index 96003b50f..544fb5fca 100644 --- a/targets/znews-ss-prediction/system/debpkgs.txt +++ b/targets/znews-ss-prediction/system/debpkgs.txt @@ -1,19 +1,19 @@ - -Debian packages required: -* sysstat - iostat, vmstat, etc. - -Nice packages: -* bc - calculator (under section "math") -* ganglia-monitor?? - for the Ganglia monitoring framework - -If compiling own Apache HTTPd 2.0.x, PHP, and MySQL... -Things to have in the system in order to compile/build: -- libncurses5 -- gcc/g++ 4.0 (3.3+ should work) -- pkg-config -- make/automake(1.8)/autoconf -- flex (lex generator) -- gettext -- openssl/libssl-dev -- zlib-dev -- libxml2/libxml2-dev + +Debian packages required: +* sysstat - iostat, vmstat, etc. + +Nice packages: +* bc - calculator (under section "math") +* ganglia-monitor?? - for the Ganglia monitoring framework + +If compiling own Apache HTTPd 2.0.x, PHP, and MySQL... +Things to have in the system in order to compile/build: +- libncurses5 +- gcc/g++ 4.0 (3.3+ should work) +- pkg-config +- make/automake(1.8)/autoconf +- flex (lex generator) +- gettext +- openssl/libssl-dev +- zlib-dev +- libxml2/libxml2-dev diff --git a/targets/znews-ss-prediction/system/effectors.yml b/targets/znews-ss-prediction/system/effectors.yml index 8a8e12463..36bcbdd4f 100644 --- a/targets/znews-ss-prediction/system/effectors.yml +++ b/targets/znews-ss-prediction/system/effectors.yml @@ -1,280 +1,280 @@ -# Created January 30, 2007 (Shang-Wen Cheng) -# -# Effector descriptions. -# -# History: -# - [SWC 2007.01.30] Created file, populated ZNews effector descriptions. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# -vars: -# _effectors.commonPath: "${rainbow.path}/system/effectors" -# @ZNN_HOME will be replaced by the rainbow-install script -# _effectors.commonPath: "@ZNN_HOME/effectors" - _effectors.commonPath: "/home/znn/effectors" - - -effectors: - - blackhole: - location: "${customize.system.target.lb}" - command: setBlackholed ($) - type: script - scriptInfo: - path : "/home/znn/effectors/ip-block-mgmt" - argument: "block {0}" - - throttle: - location: "${customize.system.target.lb}" - command: setThrottled($) - type: script - scriptInfo: - path: "/home/znn/effectors/ip-throttle-mgmt" - argument: "throttle {0}" - - flushAuthentication-web0: - location: "${cusomize.system.target.web0}" - command: "${customize.system.target.lb}.forceReauthentication()" - type: script - scriptInfo: - path: "/home/znn/effectors/force-reauthentication" - - flushAuthentication-web1: - location: "${cusomize.system.target.web1}" - command: "${customize.system.target.lb}.forceReauthentication()" - type: script - scriptInfo: - path: "/home/znn/effectors/force-reauthentication" - - flushAuthentication-web2: - location: "${cusomize.system.target.web2}" - command: "${customize.system.target.lb}.forceReauthentication()" - type: script - scriptInfo: - path: "/home/znn/effectors/force-reauthentication" - - enableCaptcha-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-lb: - location: "${customize.system.target.lb}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-web2: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - disableCaptcha-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-lb: - location: "${customize.system.target.lb}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-web2: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - setFidelity-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web0.httpPort}" - - setFidelity-web1: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web1.httpPort}" - - setFidelity-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web2.httpPort}" - - enable-server-web0: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web0}, true)" - type: script - scriptInfo: - path : /home/znn/effectors/enable-server - argument : "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - disable-server-web0: - location: "${customize.system.target.lb}" - command: "LB0.enableServer (${customize.system.target.web0}, false)" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - enable-server-web1: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web1}, true)" - type: script - scriptInfo: - path : /home/znn/effectors/enable-server - argument : "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - disable-server-web1: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web1}, false)" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - enable-server-web2: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web2}, true)" - type: script - scriptInfo: - path : /home/znn/effectors/enable-server - argument : "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - disable-server-web2: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web2}, false)" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - delete-server-web0: - location: "${customize.system.target.lb}" - command: "${customize.system.target.web0}.deleteServer ()" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - add-server-web0: - location: "${customize.system.target.lb}" - command: "LB0.connectServer (${customize.system.target.web0})" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - delete-server-web1: - location: "${customize.system.target.lb}" - command: "${customize.system.target.web1}.deleteServer ()" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - add-server-web1: - location: "${customize.system.target.lb}" - command: "LB0.connectServer (${customize.system.target.web1})" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - delete-server-web2: - location: "${customize.system.target.lb}" - command: "${customize.system.target.web2}.deleteServer ()" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - add-server-web2: - location: "${customize.system.target.lb}" - command: "LB0.connectServer (${customize.system.target.web2})" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - -unused-effectors: - unblackhole: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path: "/home/znn/effectors/ip-block-mgmt" - argument: "unblock {clients}" - killDelegate2: -# Causes the designated RainbowDelegate to exit process -# Illustrates effector time-out as well as tests executor execution - location: "${customize.system.target.3}" - type: java - javaInfo: - class : org.sa.rainbow.translator.effectors.KillDelegateEffector - - # test from GUI with , SetFidelity, fidelity=<1|3|5> - - - activateServer1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/turnServer.pl" - argument: "-s on" - deactivateServer1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/turnServer.pl" - argument: "-s off" -# test from GUI with , RandomReject, frequency=<0..?> - randomReject1: - location: "${customize.system.target.2}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/setRandomReject.pl" - argument: "-r {frequency}" - killDelegate1: - location: "${customize.system.target.2}" - type: java - javaInfo: - class : org.sa.rainbow.translator.effectors.KillDelegateEffector +# Created January 30, 2007 (Shang-Wen Cheng) +# +# Effector descriptions. +# +# History: +# - [SWC 2007.01.30] Created file, populated ZNews effector descriptions. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# +vars: +# _effectors.commonPath: "${rainbow.path}/system/effectors" +# @ZNN_HOME will be replaced by the rainbow-install script +# _effectors.commonPath: "@ZNN_HOME/effectors" + _effectors.commonPath: "/home/znn/effectors" + + +effectors: + + blackhole: + location: "${customize.system.target.lb}" + command: setBlackholed ($) + type: script + scriptInfo: + path : "/home/znn/effectors/ip-block-mgmt" + argument: "block {0}" + + throttle: + location: "${customize.system.target.lb}" + command: setThrottled($) + type: script + scriptInfo: + path: "/home/znn/effectors/ip-throttle-mgmt" + argument: "throttle {0}" + + flushAuthentication-web0: + location: "${cusomize.system.target.web0}" + command: "${customize.system.target.lb}.forceReauthentication()" + type: script + scriptInfo: + path: "/home/znn/effectors/force-reauthentication" + + flushAuthentication-web1: + location: "${cusomize.system.target.web1}" + command: "${customize.system.target.lb}.forceReauthentication()" + type: script + scriptInfo: + path: "/home/znn/effectors/force-reauthentication" + + flushAuthentication-web2: + location: "${cusomize.system.target.web2}" + command: "${customize.system.target.lb}.forceReauthentication()" + type: script + scriptInfo: + path: "/home/znn/effectors/force-reauthentication" + + enableCaptcha-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-lb: + location: "${customize.system.target.lb}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-web2: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + disableCaptcha-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-lb: + location: "${customize.system.target.lb}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-web2: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + setFidelity-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web0.httpPort}" + + setFidelity-web1: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web1.httpPort}" + + setFidelity-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web2.httpPort}" + + enable-server-web0: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web0}, true)" + type: script + scriptInfo: + path : /home/znn/effectors/enable-server + argument : "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + disable-server-web0: + location: "${customize.system.target.lb}" + command: "LB0.enableServer (${customize.system.target.web0}, false)" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + enable-server-web1: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web1}, true)" + type: script + scriptInfo: + path : /home/znn/effectors/enable-server + argument : "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + disable-server-web1: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web1}, false)" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + enable-server-web2: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web2}, true)" + type: script + scriptInfo: + path : /home/znn/effectors/enable-server + argument : "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + disable-server-web2: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web2}, false)" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + delete-server-web0: + location: "${customize.system.target.lb}" + command: "${customize.system.target.web0}.deleteServer ()" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + add-server-web0: + location: "${customize.system.target.lb}" + command: "LB0.connectServer (${customize.system.target.web0})" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + delete-server-web1: + location: "${customize.system.target.lb}" + command: "${customize.system.target.web1}.deleteServer ()" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + add-server-web1: + location: "${customize.system.target.lb}" + command: "LB0.connectServer (${customize.system.target.web1})" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + delete-server-web2: + location: "${customize.system.target.lb}" + command: "${customize.system.target.web2}.deleteServer ()" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + add-server-web2: + location: "${customize.system.target.lb}" + command: "LB0.connectServer (${customize.system.target.web2})" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + +unused-effectors: + unblackhole: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path: "/home/znn/effectors/ip-block-mgmt" + argument: "unblock {clients}" + killDelegate2: +# Causes the designated RainbowDelegate to exit process +# Illustrates effector time-out as well as tests executor execution + location: "${customize.system.target.3}" + type: java + javaInfo: + class : org.sa.rainbow.translator.effectors.KillDelegateEffector + + # test from GUI with , SetFidelity, fidelity=<1|3|5> + + + activateServer1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/turnServer.pl" + argument: "-s on" + deactivateServer1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/turnServer.pl" + argument: "-s off" +# test from GUI with , RandomReject, frequency=<0..?> + randomReject1: + location: "${customize.system.target.2}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/setRandomReject.pl" + argument: "-r {frequency}" + killDelegate1: + location: "${customize.system.target.2}" + type: java + javaInfo: + class : org.sa.rainbow.translator.effectors.KillDelegateEffector diff --git a/targets/znews-ss-prediction/system/effectors/changeFidelity.pl b/targets/znews-ss-prediction/system/effectors/changeFidelity.pl index a24df7cef..80123eba4 100644 --- a/targets/znews-ss-prediction/system/effectors/changeFidelity.pl +++ b/targets/znews-ss-prediction/system/effectors/changeFidelity.pl @@ -1,83 +1,83 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -my $isCygwin = 0; -my $uname; -if ( -e "/bin/uname" ) { - $uname = `/bin/uname`; -} elsif ( -e "/usr/bin/uname" ) { - $uname = `/usr/bin/uname`; -} else { - $uname = "UNKNOWN"; -} -if ($uname =~ /CYGWIN/i) { - $isCygwin = 1; -} - -chomp(my $SCRIPT_DIR = `/usr/bin/dirname "$0"`); -my $APACHE_CONF_DIR = ($isCygwin) ? - "/cygdrive/c/server/Apache2/conf" : - "/etc/apache2"; -my $APACHE_CONF_FILE = ($isCygwin) ? - "httpd.conf" : - "apache2.conf"; -my $APACHE_SITE_DIR = "$APACHE_CONF_DIR/sites-available"; -my $APACHE_SITE_FILE = "z.com"; -my $SOURCE_CONF_DIR = ($isCygwin) ? - "$SCRIPT_DIR/fidelity.conf/cygwin" : - "$SCRIPT_DIR/fidelity.conf/oracle"; - -sub usage() { - print STDERR << "EOF"; - -This effector program changes the webserver fidelity level (1,3,5). - - usage: $0 [option] -l level - - -h : this (help) message - -l level : the new fidelity setting, should be 1, 3, or 5 (0 for original) - -EOF - exit; -} - -# get options -my %opts; -getopts('hl:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{l})); - -my $level = $opts{l}; -usage() if ($level != 0 && $level != 1 && $level != 3 && $level != 5); - -my $fExt = "-f"; -if ($level == 0) { - if ($isCygwin) { - $fExt = ".default"; - } else { - $fExt .= "5"; - } -} else { - $fExt .= $level; -} - -if ($isCygwin) { - - print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; - print `/usr/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; - print "\nGracefully restarting Apache..."; - print `/cygdrive/c/server/Apache2/bin/Apache.exe -w -n "Apache2" -k restart`; - print "\nDone."; - -} else { - - print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; - print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; - print "\nSwapping site to level $level..."; - print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_SITE_FILE$fExt $APACHE_SITE_DIR/$APACHE_SITE_FILE`; - print "\nGracefully restarting Apache..."; - print `/etc/init.d/apache2 reload`; - print "\nDone."; - -} +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +my $isCygwin = 0; +my $uname; +if ( -e "/bin/uname" ) { + $uname = `/bin/uname`; +} elsif ( -e "/usr/bin/uname" ) { + $uname = `/usr/bin/uname`; +} else { + $uname = "UNKNOWN"; +} +if ($uname =~ /CYGWIN/i) { + $isCygwin = 1; +} + +chomp(my $SCRIPT_DIR = `/usr/bin/dirname "$0"`); +my $APACHE_CONF_DIR = ($isCygwin) ? + "/cygdrive/c/server/Apache2/conf" : + "/etc/apache2"; +my $APACHE_CONF_FILE = ($isCygwin) ? + "httpd.conf" : + "apache2.conf"; +my $APACHE_SITE_DIR = "$APACHE_CONF_DIR/sites-available"; +my $APACHE_SITE_FILE = "z.com"; +my $SOURCE_CONF_DIR = ($isCygwin) ? + "$SCRIPT_DIR/fidelity.conf/cygwin" : + "$SCRIPT_DIR/fidelity.conf/oracle"; + +sub usage() { + print STDERR << "EOF"; + +This effector program changes the webserver fidelity level (1,3,5). + + usage: $0 [option] -l level + + -h : this (help) message + -l level : the new fidelity setting, should be 1, 3, or 5 (0 for original) + +EOF + exit; +} + +# get options +my %opts; +getopts('hl:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{l})); + +my $level = $opts{l}; +usage() if ($level != 0 && $level != 1 && $level != 3 && $level != 5); + +my $fExt = "-f"; +if ($level == 0) { + if ($isCygwin) { + $fExt = ".default"; + } else { + $fExt .= "5"; + } +} else { + $fExt .= $level; +} + +if ($isCygwin) { + + print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; + print `/usr/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; + print "\nGracefully restarting Apache..."; + print `/cygdrive/c/server/Apache2/bin/Apache.exe -w -n "Apache2" -k restart`; + print "\nDone."; + +} else { + + print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; + print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; + print "\nSwapping site to level $level..."; + print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_SITE_FILE$fExt $APACHE_SITE_DIR/$APACHE_SITE_FILE`; + print "\nGracefully restarting Apache..."; + print `/etc/init.d/apache2 reload`; + print "\nDone."; + +} diff --git a/targets/znews-ss-prediction/system/effectors/dummyBlackhole.pl b/targets/znews-ss-prediction/system/effectors/dummyBlackhole.pl index 0a9e46e42..81ed3be30 100644 --- a/targets/znews-ss-prediction/system/effectors/dummyBlackhole.pl +++ b/targets/znews-ss-prediction/system/effectors/dummyBlackhole.pl @@ -1,24 +1,24 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -sub usage () { - print STDERR << "EOF"; - -This effector program is a dummy blackholer. - - usege: $0 [option] -i IP - - -i IP: the IP address that should be blackholed - -EOF - exit; -} - -#get options -my %opts; -getopts ('i:',\%opts) or usage (); -usage () if (!defined($opts{i})); -my $IP = $opts{i} -print "Blackholing $IP...\n"; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +sub usage () { + print STDERR << "EOF"; + +This effector program is a dummy blackholer. + + usege: $0 [option] -i IP + + -i IP: the IP address that should be blackholed + +EOF + exit; +} + +#get options +my %opts; +getopts ('i:',\%opts) or usage (); +usage () if (!defined($opts{i})); +my $IP = $opts{i} +print "Blackholing $IP...\n"; diff --git a/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf b/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf index 4adbba299..5b13550db 100644 --- a/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf +++ b/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf @@ -1,967 +1,967 @@ -### Fidelity-5 Conf file -## - full featured -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -AddType application/x-httpd-php .php - -# configure the path to php.ini -PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.php index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -AddType text/html .shtml -AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-5 Conf file +## - full featured +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +AddType application/x-httpd-php .php + +# configure the path to php.ini +PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.php index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +AddType text/html .shtml +AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 b/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 index 95dd86268..6907bc89d 100644 --- a/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 +++ b/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 @@ -1,974 +1,974 @@ -### Fidelity-1 Conf file -## - reduced timeout from 300 to 30 sec -## - reduced max keep alive reqs from 100 to 10 -## - threads per child reduced from 250 to 10 -## - set an upper limit of max requests per child to 5 -## - excluded user dir function -## - excluded modules dav, imap, rewrite, userdir -## - reduced Directory Options to indexes & symlink only -## - reduced AllowOverride to None -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 30 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 10 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 10 -MaxRequestsPerChild 5 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -#LoadModule cgi_module modules/mod_cgi.so -#LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -#LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -#LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -#LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -#AddType application/x-httpd-php .php - -# configure the path to php.ini -#PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www1" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options Indexes SymLinksIfOwnerMatch - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride None - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -#UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - -# -# Options Indexes -# AllowOverride None -# Order allow,deny -# Allow from all -# -# -# SetHandler type-map -# -# -# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 -# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 -# - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# -# -# AllowOverride None -# Options None -# Order allow,deny -# Allow from all -# - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -#AddType application/x-compress .Z -#AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# -# -# Include conf/ssl.conf -# - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-1 Conf file +## - reduced timeout from 300 to 30 sec +## - reduced max keep alive reqs from 100 to 10 +## - threads per child reduced from 250 to 10 +## - set an upper limit of max requests per child to 5 +## - excluded user dir function +## - excluded modules dav, imap, rewrite, userdir +## - reduced Directory Options to indexes & symlink only +## - reduced AllowOverride to None +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 30 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 10 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 10 +MaxRequestsPerChild 5 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule cgi_module modules/mod_cgi.so +#LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +#LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +#LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +#LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +#AddType application/x-httpd-php .php + +# configure the path to php.ini +#PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www1" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options Indexes SymLinksIfOwnerMatch + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride None + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +#UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + +# +# Options Indexes +# AllowOverride None +# Order allow,deny +# Allow from all +# +# +# SetHandler type-map +# +# +# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 +# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 +# + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +# +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +# + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +#AddType application/x-compress .Z +#AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# +# +# Include conf/ssl.conf +# + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 b/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 index 7fd0f402b..eaab99348 100644 --- a/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 +++ b/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 @@ -1,971 +1,971 @@ -### Fidelity-3 Conf file -## - excluded CGI handling -## - excluded PHP module -## - excluded SSI -## - excluded compression type -## - excluded server manual -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -#LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -#AddType application/x-httpd-php .php - -# configure the path to php.ini -#PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www3" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - -# -# Options Indexes -# AllowOverride None -# Order allow,deny -# Allow from all -# -# -# SetHandler type-map -# -# -# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 -# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 -# - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# -# -# AllowOverride None -# Options None -# Order allow,deny -# Allow from all -# - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -#AddType application/x-compress .Z -#AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-3 Conf file +## - excluded CGI handling +## - excluded PHP module +## - excluded SSI +## - excluded compression type +## - excluded server manual +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +#AddType application/x-httpd-php .php + +# configure the path to php.ini +#PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www3" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + +# +# Options Indexes +# AllowOverride None +# Order allow,deny +# Allow from all +# +# +# SetHandler type-map +# +# +# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 +# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 +# + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +# +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +# + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +#AddType application/x-compress .Z +#AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 b/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 index 4adbba299..5b13550db 100644 --- a/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 +++ b/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 @@ -1,967 +1,967 @@ -### Fidelity-5 Conf file -## - full featured -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -AddType application/x-httpd-php .php - -# configure the path to php.ini -PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.php index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -AddType text/html .shtml -AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-5 Conf file +## - full featured +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +AddType application/x-httpd-php .php + +# configure the path to php.ini +PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.php index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +AddType text/html .shtml +AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf.default b/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf.default index 20dd3c11d..ff8505b79 100644 --- a/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf.default +++ b/targets/znews-ss-prediction/system/effectors/fidelity.conf/cygwin/httpd.conf.default @@ -1,952 +1,952 @@ -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -#LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -#LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin admin@able.cs.cmu.edu - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/Apache2/htdocs" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options Indexes FollowSymLinks - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride None - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +#LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +#LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin admin@able.cs.cmu.edu + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/Apache2/htdocs" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options Indexes FollowSymLinks + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride None + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# diff --git a/targets/znews-ss-prediction/system/effectors/setRandomReject.pl b/targets/znews-ss-prediction/system/effectors/setRandomReject.pl index 5d6b91697..58f70c7b0 100644 --- a/targets/znews-ss-prediction/system/effectors/setRandomReject.pl +++ b/targets/znews-ss-prediction/system/effectors/setRandomReject.pl @@ -1,35 +1,35 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -my $APACHE_WWW_DIR = "/home/owen/project/rainbow/delegate/targets/znews1-d/system/webpages/www5"; - -sub usage() { - print STDERR << "EOF"; - -This effector program affects random reject frequency (0 or mod over seconds). - - usage: $0 [option] -r [0|modval] - - -h : this (help) message - -r 0|mod : the modulus value for request rejection (0 for NO reject) - -EOF - exit; -} - -# get options -my %opts; -getopts('hr:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{r})); - -my $modVal = $opts{r}; -usage() if ($modVal < 0 && $modVal > 10); - -my $file = "reject.mod"; -print "Setting reject modulus value to $modVal..."; -open(FOUT, ">$APACHE_WWW_DIR/$file"); -print FOUT $modVal; -close(FOUT); -print "\nDone."; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +my $APACHE_WWW_DIR = "/home/owen/project/rainbow/delegate/targets/znews1-d/system/webpages/www5"; + +sub usage() { + print STDERR << "EOF"; + +This effector program affects random reject frequency (0 or mod over seconds). + + usage: $0 [option] -r [0|modval] + + -h : this (help) message + -r 0|mod : the modulus value for request rejection (0 for NO reject) + +EOF + exit; +} + +# get options +my %opts; +getopts('hr:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{r})); + +my $modVal = $opts{r}; +usage() if ($modVal < 0 && $modVal > 10); + +my $file = "reject.mod"; +print "Setting reject modulus value to $modVal..."; +open(FOUT, ">$APACHE_WWW_DIR/$file"); +print FOUT $modVal; +close(FOUT); +print "\nDone."; diff --git a/targets/znews-ss-prediction/system/effectors/turnServer.pl b/targets/znews-ss-prediction/system/effectors/turnServer.pl index 8cc10dd33..9d46f681e 100644 --- a/targets/znews-ss-prediction/system/effectors/turnServer.pl +++ b/targets/znews-ss-prediction/system/effectors/turnServer.pl @@ -1,36 +1,36 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; -use IO::Handle; - -sub usage() { - print STDERR << "EOF"; - -This effector program turns the webserver on or off - - usage: $0 [option] -s on|off - - -h : this (help) message - -s on|off : on or off to start/stop webserver - -EOF - exit; -} - -# get options -my %opts; -getopts('hs:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{s})); - -my $switch = $opts{s}; -usage() if ($switch ne "on" && $switch ne "off"); - -if ($switch eq "on") { - print "\nStarting Apache..."; - print `/etc/init.d/apache2 start`; -} else { - print "\nStopping Apache..."; - print `/etc/init.d/apache2 stop`; -} -print "\nDone."; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; +use IO::Handle; + +sub usage() { + print STDERR << "EOF"; + +This effector program turns the webserver on or off + + usage: $0 [option] -s on|off + + -h : this (help) message + -s on|off : on or off to start/stop webserver + +EOF + exit; +} + +# get options +my %opts; +getopts('hs:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{s})); + +my $switch = $opts{s}; +usage() if ($switch ne "on" && $switch ne "off"); + +if ($switch eq "on") { + print "\nStarting Apache..."; + print `/etc/init.d/apache2 start`; +} else { + print "\nStopping Apache..."; + print `/etc/init.d/apache2 stop`; +} +print "\nDone."; diff --git a/targets/znews-ss-prediction/system/probes.yml b/targets/znews-ss-prediction/system/probes.yml index ab49aa777..2e5fc47bf 100644 --- a/targets/znews-ss-prediction/system/probes.yml +++ b/targets/znews-ss-prediction/system/probes.yml @@ -1,175 +1,175 @@ -# -# Probe descriptions. -# -# History: -# - [SWC 2007.03.18] Created file, populated new probe descriptions. -# - [SWC 2007.04.09] Added array of host names as arguments to PingRTTProbe. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# - [SWC 2007.04.11] Added ClientProxyProbe -# -vars: -# _probes.commonPath: "${rainbow.path}/system/probes" - _probes.commonPath: /home/znn/znn-benchmark/system/probes - -probes: - - EnablementProbe: - alias: enablementprobe - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ServerEnablementProbe - period: 2000 - args.length: 1 - args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/balanced.conf - - DummyMaliciousnessProbe: - alias: dummymaliciousness - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.DummyProbe - period: 2000 - args.length: 1 - args.0: /home/znn/maliciousness - - BlackholeProbe: - alias: blackhole - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.BlackholeProbe - period: 2000 - args.length: 1 - args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/blocked.conf - - ThrottleProbe: - alias: throttle - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ThrottleProbe - period: 2000 - args.length: 1 - args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/security.conf - - CaptchaProbe: - alias: captchaprobe - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.CaptchaProbe - period: 2000 - args.length: 1 - args.0: /tmp/znn-wrapper-1080 -# args.0: /home/znn/lb0/sw/httpd-2.4.2/conf/captcha.on - - AuthenticationProbe: - alias: authenticationprobe - location: "${customize.system.target.web0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.AuthenticationProbe - period: 2000 - args.length: 1 - args.0: /tmp/znn-wrapper-auth-1080 - - ClientProxyProbe0: - alias: clientproxy - location: "${customize.system.target.master}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe - period: 2000 - args.length: 1 - args.0: "http://${customize.system.target.lb}:1081/news.php" - - ClientProxyProbe1: - alias: clientproxy - location: "${customize.system.target.bad}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe - period: 2000 - args.length: 1 - args.0: "http://${customize.system.target.lb}:1081/news.php" - - FidelityProbe1: - alias: fidelity - location: "${customize.system.target.web0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.FidelityProbe - period: 2000 - args.length: 1 - args.0: "/tmp/znn-fidelity-${customize.system.target.web0.httpPort}" - -unused-probes: - ApacheTopProbe1: - alias: apachetop - location: "${customize.system.target.web0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/apachetopProbe.pl" - argument: "-k -s" - DiskIOProbe1: - alias: diskio - location: "${customize.system.target.web0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/diskIOProbe.pl" - argument: "-k -s" - PingRTTProbe1: - alias: pingrtt - location: "${customize.system.target.web0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.PingRTTProbe -# sample period in milliseconds - period: 1500 - args.length: 1 - args.0: "${rainbow.master.location.host}" -# args.1: "${customize.system.target.2}" - LoadProbe1: - alias: load - location: "${customize.system.target.web0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" - NullProbe0: - alias: NIL - location: "${customize.system.target.0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.probes.NullProbe - ApacheTopProbe0: - alias: apachetop - location: "${customize.system.target.0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/apachetopProbe.pl" - argument: "-k -s" - LoadProbe0: - alias: load - location: "${customize.system.target.0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" - PingRTTProbe3: - alias: pingrtt - location: "${customize.system.target.3}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znews.probes.PingRTTProbe - period: 1500 - args.length: 1 - args.0: "${rainbow.master.location.host}" - LoadProbe3: - alias: load - location: "${customize.system.target.3}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" +# +# Probe descriptions. +# +# History: +# - [SWC 2007.03.18] Created file, populated new probe descriptions. +# - [SWC 2007.04.09] Added array of host names as arguments to PingRTTProbe. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# - [SWC 2007.04.11] Added ClientProxyProbe +# +vars: +# _probes.commonPath: "${rainbow.path}/system/probes" + _probes.commonPath: /home/znn/znn-benchmark/system/probes + +probes: + + EnablementProbe: + alias: enablementprobe + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ServerEnablementProbe + period: 2000 + args.length: 1 + args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/balanced.conf + + DummyMaliciousnessProbe: + alias: dummymaliciousness + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.DummyProbe + period: 2000 + args.length: 1 + args.0: /home/znn/maliciousness + + BlackholeProbe: + alias: blackhole + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.BlackholeProbe + period: 2000 + args.length: 1 + args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/blocked.conf + + ThrottleProbe: + alias: throttle + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ThrottleProbe + period: 2000 + args.length: 1 + args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/security.conf + + CaptchaProbe: + alias: captchaprobe + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.CaptchaProbe + period: 2000 + args.length: 1 + args.0: /tmp/znn-wrapper-1080 +# args.0: /home/znn/lb0/sw/httpd-2.4.2/conf/captcha.on + + AuthenticationProbe: + alias: authenticationprobe + location: "${customize.system.target.web0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.AuthenticationProbe + period: 2000 + args.length: 1 + args.0: /tmp/znn-wrapper-auth-1080 + + ClientProxyProbe0: + alias: clientproxy + location: "${customize.system.target.master}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe + period: 2000 + args.length: 1 + args.0: "http://${customize.system.target.lb}:1081/news.php" + + ClientProxyProbe1: + alias: clientproxy + location: "${customize.system.target.bad}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe + period: 2000 + args.length: 1 + args.0: "http://${customize.system.target.lb}:1081/news.php" + + FidelityProbe1: + alias: fidelity + location: "${customize.system.target.web0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.FidelityProbe + period: 2000 + args.length: 1 + args.0: "/tmp/znn-fidelity-${customize.system.target.web0.httpPort}" + +unused-probes: + ApacheTopProbe1: + alias: apachetop + location: "${customize.system.target.web0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/apachetopProbe.pl" + argument: "-k -s" + DiskIOProbe1: + alias: diskio + location: "${customize.system.target.web0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/diskIOProbe.pl" + argument: "-k -s" + PingRTTProbe1: + alias: pingrtt + location: "${customize.system.target.web0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.PingRTTProbe +# sample period in milliseconds + period: 1500 + args.length: 1 + args.0: "${rainbow.master.location.host}" +# args.1: "${customize.system.target.2}" + LoadProbe1: + alias: load + location: "${customize.system.target.web0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" + NullProbe0: + alias: NIL + location: "${customize.system.target.0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.probes.NullProbe + ApacheTopProbe0: + alias: apachetop + location: "${customize.system.target.0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/apachetopProbe.pl" + argument: "-k -s" + LoadProbe0: + alias: load + location: "${customize.system.target.0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" + PingRTTProbe3: + alias: pingrtt + location: "${customize.system.target.3}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znews.probes.PingRTTProbe + period: 1500 + args.length: 1 + args.0: "${rainbow.master.location.host}" + LoadProbe3: + alias: load + location: "${customize.system.target.3}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" diff --git a/targets/znews-ss-prediction/system/probes/apachetopProbe.pl b/targets/znews-ss-prediction/system/probes/apachetopProbe.pl index 79ba71042..9f8989f04 100644 --- a/targets/znews-ss-prediction/system/probes/apachetopProbe.pl +++ b/targets/znews-ss-prediction/system/probes/apachetopProbe.pl @@ -1,90 +1,90 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 5000; # 5 sec delay -my $APACHETOP_LOG = "../../log/apachetop.log"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -if (! -e $APACHETOP_LOG) { # create empty file - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line,$sendBeacon); -while (!shouldTerminate($sock)) { - $sendBeacon = 1; - while ($line = ) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - $sendBeacon = 0; - } - if ($sendBeacon) { # announce something to be alive - announce($ALIAS, "\n", [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 5000; # 5 sec delay +my $APACHETOP_LOG = "../../log/apachetop.log"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +if (! -e $APACHETOP_LOG) { # create empty file + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line,$sendBeacon); +while (!shouldTerminate($sock)) { + $sendBeacon = 1; + while ($line = ) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + $sendBeacon = 0; + } + if ($sendBeacon) { # announce something to be alive + announce($ALIAS, "\n", [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-prediction/system/probes/cygwin/apachetopProbe-single.pl b/targets/znews-ss-prediction/system/probes/cygwin/apachetopProbe-single.pl index 966358241..762a0686a 100644 --- a/targets/znews-ss-prediction/system/probes/cygwin/apachetopProbe-single.pl +++ b/targets/znews-ss-prediction/system/probes/cygwin/apachetopProbe-single.pl @@ -1,98 +1,98 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 10; -my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; -my $APACHETOP_LOG = "apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# fork to the apachetop program -my $pid = fork(); -if ($pid == 0) { ### child process - if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); - } - exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; - exit(0); -} - -### parent process - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line); -while (!shouldTerminate($sock)) { - $line = ; - if (defined($line)) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 10; +my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; +my $APACHETOP_LOG = "apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# fork to the apachetop program +my $pid = fork(); +if ($pid == 0) { ### child process + if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); + } + exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; + exit(0); +} + +### parent process + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line); +while (!shouldTerminate($sock)) { + $line = ; + if (defined($line)) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-prediction/system/probes/cygwin/apachetopProbe.pl b/targets/znews-ss-prediction/system/probes/cygwin/apachetopProbe.pl index 79ba71042..9f8989f04 100644 --- a/targets/znews-ss-prediction/system/probes/cygwin/apachetopProbe.pl +++ b/targets/znews-ss-prediction/system/probes/cygwin/apachetopProbe.pl @@ -1,90 +1,90 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 5000; # 5 sec delay -my $APACHETOP_LOG = "../../log/apachetop.log"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -if (! -e $APACHETOP_LOG) { # create empty file - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line,$sendBeacon); -while (!shouldTerminate($sock)) { - $sendBeacon = 1; - while ($line = ) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - $sendBeacon = 0; - } - if ($sendBeacon) { # announce something to be alive - announce($ALIAS, "\n", [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 5000; # 5 sec delay +my $APACHETOP_LOG = "../../log/apachetop.log"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +if (! -e $APACHETOP_LOG) { # create empty file + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line,$sendBeacon); +while (!shouldTerminate($sock)) { + $sendBeacon = 1; + while ($line = ) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + $sendBeacon = 0; + } + if ($sendBeacon) { # announce something to be alive + announce($ALIAS, "\n", [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-prediction/system/probes/cygwin/fidelityProbe.pl b/targets/znews-ss-prediction/system/probes/cygwin/fidelityProbe.pl index 21dc6255d..abb411a4d 100644 --- a/targets/znews-ss-prediction/system/probes/cygwin/fidelityProbe.pl +++ b/targets/znews-ss-prediction/system/probes/cygwin/fidelityProbe.pl @@ -1,100 +1,100 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "fidelity"; -my $NAME = "FidelityProbe"; -my $DELAY = 1000; -my $REPEATEVERY = 5; -my $APACHE_CONF_DIR = "/cygdrive/c/server/Apache2/conf"; -my $APACHE_CONF_FILE = "httpd.conf"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current server fidelity (1,3,5) to Probe Relay file/socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic server fidelity info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub determineFidelity () { - my $fid = 0; - - open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); - my $firstLine = ; # read the first line - if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { - $fid = $1; - } - close(FIN); - - return $fid; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -my $repeatCnt = $REPEATEVERY; -my $savedFidelity = 0; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # compute new fidelity status - my $fidelity = determineFidelity(); - if ($fidelity != $savedFidelity || $repeatCnt == 0) { - $savedFidelity = $fidelity; #store new fidelity - my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - - if ($repeatCnt == 0) { - $repeatCnt = $REPEATEVERY; - } - } else { - $repeatCnt--; - } -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "fidelity"; +my $NAME = "FidelityProbe"; +my $DELAY = 1000; +my $REPEATEVERY = 5; +my $APACHE_CONF_DIR = "/cygdrive/c/server/Apache2/conf"; +my $APACHE_CONF_FILE = "httpd.conf"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current server fidelity (1,3,5) to Probe Relay file/socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic server fidelity info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub determineFidelity () { + my $fid = 0; + + open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); + my $firstLine = ; # read the first line + if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { + $fid = $1; + } + close(FIN); + + return $fid; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +my $repeatCnt = $REPEATEVERY; +my $savedFidelity = 0; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # compute new fidelity status + my $fidelity = determineFidelity(); + if ($fidelity != $savedFidelity || $repeatCnt == 0) { + $savedFidelity = $fidelity; #store new fidelity + my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + + if ($repeatCnt == 0) { + $repeatCnt = $REPEATEVERY; + } + } else { + $repeatCnt--; + } +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-prediction/system/probes/cygwin/loadProbe.pl b/targets/znews-ss-prediction/system/probes/cygwin/loadProbe.pl index b50e32b17..0ff60debb 100644 --- a/targets/znews-ss-prediction/system/probes/cygwin/loadProbe.pl +++ b/targets/znews-ss-prediction/system/probes/cygwin/loadProbe.pl @@ -1,98 +1,98 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "load"; -my $NAME = "LoadProbe"; -my $DELAY = 1000; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current CPU usage to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic CPU usage info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub cpuTime () { - my ($user, $nice, $sys, $idle); - - local(*FIN); - open(FIN, ") { - chomp; - if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/o) { - ($user, $nice, $sys, $idle) = ($1, $2, $3, $4); - last; - } - } - close(FIN); - return ($user, $nice, $sys, $idle); -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# save current cpu ticks -my($userSv, $niceSv, $sysSv, $idleSv) = cpuTime(); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # retrieve new cpu ticks - my ($userN, $niceN, $sysN, $idleN) = cpuTime(); - # compute delta cpu ticks - my ($user, $nice, $sys, $idle) = - ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv); - # store the new saved ticks - ($userSv, $niceSv, $sysSv, $idleSv) = ($userN, $niceN, $sysN, $idleN); - my $total = $user + $nice + $sys + $idle; - my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), - $user/$total, $nice/$total, $sys/$total, $idle/$total); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "load"; +my $NAME = "LoadProbe"; +my $DELAY = 1000; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current CPU usage to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic CPU usage info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub cpuTime () { + my ($user, $nice, $sys, $idle); + + local(*FIN); + open(FIN, ") { + chomp; + if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/o) { + ($user, $nice, $sys, $idle) = ($1, $2, $3, $4); + last; + } + } + close(FIN); + return ($user, $nice, $sys, $idle); +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# save current cpu ticks +my($userSv, $niceSv, $sysSv, $idleSv) = cpuTime(); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # retrieve new cpu ticks + my ($userN, $niceN, $sysN, $idleN) = cpuTime(); + # compute delta cpu ticks + my ($user, $nice, $sys, $idle) = + ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv); + # store the new saved ticks + ($userSv, $niceSv, $sysSv, $idleSv) = ($userN, $niceN, $sysN, $idleN); + my $total = $user + $nice + $sys + $idle; + my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), + $user/$total, $nice/$total, $sys/$total, $idle/$total); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-prediction/system/probes/cygwin/probe-cygwin.bat b/targets/znews-ss-prediction/system/probes/cygwin/probe-cygwin.bat index 4f192949d..b912671dd 100644 --- a/targets/znews-ss-prediction/system/probes/cygwin/probe-cygwin.bat +++ b/targets/znews-ss-prediction/system/probes/cygwin/probe-cygwin.bat @@ -1,8 +1,8 @@ -@echo off - -C: -chdir C:\server\cygwin\bin -set DEMO_MODE=%1 -set DEMO_TITLE=%2 - -bash --login -i +@echo off + +C: +chdir C:\server\cygwin\bin +set DEMO_MODE=%1 +set DEMO_TITLE=%2 + +bash --login -i diff --git a/targets/znews-ss-prediction/system/probes/cygwin/runApachetop.pl b/targets/znews-ss-prediction/system/probes/cygwin/runApachetop.pl index aca341ab9..0970d810f 100644 --- a/targets/znews-ss-prediction/system/probes/cygwin/runApachetop.pl +++ b/targets/znews-ss-prediction/system/probes/cygwin/runApachetop.pl @@ -1,16 +1,16 @@ -#!/usr/bin/perl -w - -use strict; - -############################# -my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; -my $APACHETOP_LOG = "/cygdrive/c/server/rainbow/oracle/targets/znews1/log/apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - -if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; +#!/usr/bin/perl -w + +use strict; + +############################# +my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; +my $APACHETOP_LOG = "/cygdrive/c/server/rainbow/oracle/targets/znews1/log/apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + +if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; diff --git a/targets/znews-ss-prediction/system/probes/diskIOProbe-diskstats.pl b/targets/znews-ss-prediction/system/probes/diskIOProbe-diskstats.pl index e4a1e3ba5..a40e58938 100644 --- a/targets/znews-ss-prediction/system/probes/diskIOProbe-diskstats.pl +++ b/targets/znews-ss-prediction/system/probes/diskIOProbe-diskstats.pl @@ -1,125 +1,125 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "diskio"; -my $NAME = "DiskIOProbe"; -my $DELAY = 4000; -############################# - -# Determine diskstats format -my $statfile; -my $uname = `uname -a`; -if ($uname =~ /Linux\s+(.+?)\s+(\d+[.]\d+)/) { - if ($2 eq "2.6") { - $statfile = "/proc/diskstats"; -# } elsif ($2 <= 2.5) { -# $statfile = "/proc/partitions"; # granularity of info more coarse - } -} else { - print "Linux version unsupported for diskstat access! Unable to continue probing\n"; - exit -1; -} - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current accumulated Disk IO to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic Disk IO info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub diskUsage () { - my ($MINOR, $FIRST, $TMIO) = (2, 4, 14); # index to stat entry - my (@accumStat) = (0,0,0,0,0,0,0,0,0,0,0); - my (@dstat); #$rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio - - open(FIN, "< $statfile"); - while () { - chomp; - @dstat = split(/\s+/); # blank zeroth element due to space(s) in beginning - if ($dstat[$MINOR] == 0 && $dstat[$TMIO] > 0) { # accum reading from device - for my $i ($FIRST..$#dstat) { - $accumStat[$i-$FIRST] += $dstat[$i]; - } - #print "Accumulated @accumStat\n"; - } - } - close(FIN); - return @accumStat; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# zero out disk IO stats -my($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) - = (0,0,0,0,0,0,0,0,0,0,0); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - # retrieve new disk IO stats - my ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN) = diskUsage(); - # compute delta stats for all except 9th and 10th - my ($rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio) = - ($rcmpN-$rcmpS, $rmrgN-$rmrgS, $rsectN-$rsectS, $rmsN-$rmsS, $wcmpN-$wcmpS, - $wmrgN-$wmrgS, $wsectN-$wsectS, $wmsN-$wmsS, $curioN, $curmsN, $tmioN-$tmioS); - # store the new saved ticks - ($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) = - ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN); - # each sector is 512 bytes as of kernel 2.4, so divide 2 to get kb - #print "D: $rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio\n" if ($doPrint); - my $kbRead = $rsect/2.0; - my $kbRps = ($rms == 0) ? 0 : ($kbRead / $rms) * 1000; # sec = 1000 ms - my $kbWritten = $wsect/2.0; - my $kbWps = ($wms == 0) ? 0 : ($kbWritten / $wms) * 1000; - my $tps = ($rms+$wms == 0) ? 0 : ($rcmp+$wcmp)/($rms+$wms) * 1000; - my $rpt = sprintf("[%s] %9.2f %9.2f %9.2f %9d %9d %9d %9d %9d\n", "".localtime(), - $tps, $kbRps, $kbWps, $kbRead, $kbWritten, $curio, $curms, $tmio); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "diskio"; +my $NAME = "DiskIOProbe"; +my $DELAY = 4000; +############################# + +# Determine diskstats format +my $statfile; +my $uname = `uname -a`; +if ($uname =~ /Linux\s+(.+?)\s+(\d+[.]\d+)/) { + if ($2 eq "2.6") { + $statfile = "/proc/diskstats"; +# } elsif ($2 <= 2.5) { +# $statfile = "/proc/partitions"; # granularity of info more coarse + } +} else { + print "Linux version unsupported for diskstat access! Unable to continue probing\n"; + exit -1; +} + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current accumulated Disk IO to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic Disk IO info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub diskUsage () { + my ($MINOR, $FIRST, $TMIO) = (2, 4, 14); # index to stat entry + my (@accumStat) = (0,0,0,0,0,0,0,0,0,0,0); + my (@dstat); #$rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio + + open(FIN, "< $statfile"); + while () { + chomp; + @dstat = split(/\s+/); # blank zeroth element due to space(s) in beginning + if ($dstat[$MINOR] == 0 && $dstat[$TMIO] > 0) { # accum reading from device + for my $i ($FIRST..$#dstat) { + $accumStat[$i-$FIRST] += $dstat[$i]; + } + #print "Accumulated @accumStat\n"; + } + } + close(FIN); + return @accumStat; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# zero out disk IO stats +my($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) + = (0,0,0,0,0,0,0,0,0,0,0); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + # retrieve new disk IO stats + my ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN) = diskUsage(); + # compute delta stats for all except 9th and 10th + my ($rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio) = + ($rcmpN-$rcmpS, $rmrgN-$rmrgS, $rsectN-$rsectS, $rmsN-$rmsS, $wcmpN-$wcmpS, + $wmrgN-$wmrgS, $wsectN-$wsectS, $wmsN-$wmsS, $curioN, $curmsN, $tmioN-$tmioS); + # store the new saved ticks + ($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) = + ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN); + # each sector is 512 bytes as of kernel 2.4, so divide 2 to get kb + #print "D: $rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio\n" if ($doPrint); + my $kbRead = $rsect/2.0; + my $kbRps = ($rms == 0) ? 0 : ($kbRead / $rms) * 1000; # sec = 1000 ms + my $kbWritten = $wsect/2.0; + my $kbWps = ($wms == 0) ? 0 : ($kbWritten / $wms) * 1000; + my $tps = ($rms+$wms == 0) ? 0 : ($rcmp+$wcmp)/($rms+$wms) * 1000; + my $rpt = sprintf("[%s] %9.2f %9.2f %9.2f %9d %9d %9d %9d %9d\n", "".localtime(), + $tps, $kbRps, $kbWps, $kbRead, $kbWritten, $curio, $curms, $tmio); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-prediction/system/probes/diskIOProbe.pl b/targets/znews-ss-prediction/system/probes/diskIOProbe.pl index ec3391891..fe4b002b3 100644 --- a/targets/znews-ss-prediction/system/probes/diskIOProbe.pl +++ b/targets/znews-ss-prediction/system/probes/diskIOProbe.pl @@ -1,101 +1,101 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "diskio"; -my $NAME = "DiskIOProbe"; -my $DELAY = 5000; -############################# - -# Determine diskstats format -my $IOSTAT = "/usr/bin/iostat"; -if (! -e $IOSTAT) { - print "No iostat found, please install the sysstat package to continue!\n"; - exit -1; -} -my $IOSTAT_ARGS = "-k " . ($DELAY/1000); # period, with indefinite ouput - -sub usage() { - print STDERR << "EOF"; - -This program dumps periodic Disk IO status to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic Disk IO info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# init disk IO stats vars -my($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); -my($isInitial, $cntCycle) = (1, 0); -open(FIN, "$IOSTAT $IOSTAT_ARGS |") - || die "Can't fork $IOSTAT: $!"; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - # retrieve new disk IO stats - while () { - chomp; - if (/^Device:/i) { - ++$cntCycle; - if ($isInitial && $cntCycle > 1) { # no longer initial - print "Filtered initial round!\n" if ($doPrint); - $isInitial = 0; - } - } - if (!$isInitial && - /^(\w+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/) { - ($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB) = ($1, $2, $3, $4, $5, $6); - last; - } - } - my $rpt = sprintf("[%s] %s %.2f %.2f %.2f %d %d\n", "".localtime(), - $dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -close(FIN) || die "Bad $IOSTAT: $! $?"; -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "diskio"; +my $NAME = "DiskIOProbe"; +my $DELAY = 5000; +############################# + +# Determine diskstats format +my $IOSTAT = "/usr/bin/iostat"; +if (! -e $IOSTAT) { + print "No iostat found, please install the sysstat package to continue!\n"; + exit -1; +} +my $IOSTAT_ARGS = "-k " . ($DELAY/1000); # period, with indefinite ouput + +sub usage() { + print STDERR << "EOF"; + +This program dumps periodic Disk IO status to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic Disk IO info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# init disk IO stats vars +my($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); +my($isInitial, $cntCycle) = (1, 0); +open(FIN, "$IOSTAT $IOSTAT_ARGS |") + || die "Can't fork $IOSTAT: $!"; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + # retrieve new disk IO stats + while () { + chomp; + if (/^Device:/i) { + ++$cntCycle; + if ($isInitial && $cntCycle > 1) { # no longer initial + print "Filtered initial round!\n" if ($doPrint); + $isInitial = 0; + } + } + if (!$isInitial && + /^(\w+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/) { + ($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB) = ($1, $2, $3, $4, $5, $6); + last; + } + } + my $rpt = sprintf("[%s] %s %.2f %.2f %.2f %d %d\n", "".localtime(), + $dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +close(FIN) || die "Bad $IOSTAT: $! $?"; +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-prediction/system/probes/fidelityProbe.pl b/targets/znews-ss-prediction/system/probes/fidelityProbe.pl index d5a8214ff..d22e3f086 100644 --- a/targets/znews-ss-prediction/system/probes/fidelityProbe.pl +++ b/targets/znews-ss-prediction/system/probes/fidelityProbe.pl @@ -1,100 +1,100 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "fidelity"; -my $NAME = "FidelityProbe"; -my $DELAY = 1000; -my $REPEATEVERY = 5; -my $APACHE_CONF_DIR = "/etc/apache2"; -my $APACHE_CONF_FILE = "apache2.conf"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current server fidelity (1,3,5) to Probe Relay file/socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic server fidelity info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub determineFidelity () { - my $fid = 0; - - open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); - my $firstLine = ; # read the first line - if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { - $fid = $1; - } - close(FIN); - - return $fid; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -my $repeatCnt = $REPEATEVERY; -my $savedFidelity = 0; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # compute new fidelity status - my $fidelity = determineFidelity(); - if ($fidelity != $savedFidelity || $repeatCnt == 0) { - $savedFidelity = $fidelity; #store new fidelity - my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - - if ($repeatCnt == 0) { - $repeatCnt = $REPEATEVERY; - } - } else { - $repeatCnt--; - } -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "fidelity"; +my $NAME = "FidelityProbe"; +my $DELAY = 1000; +my $REPEATEVERY = 5; +my $APACHE_CONF_DIR = "/etc/apache2"; +my $APACHE_CONF_FILE = "apache2.conf"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current server fidelity (1,3,5) to Probe Relay file/socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic server fidelity info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub determineFidelity () { + my $fid = 0; + + open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); + my $firstLine = ; # read the first line + if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { + $fid = $1; + } + close(FIN); + + return $fid; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +my $repeatCnt = $REPEATEVERY; +my $savedFidelity = 0; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # compute new fidelity status + my $fidelity = determineFidelity(); + if ($fidelity != $savedFidelity || $repeatCnt == 0) { + $savedFidelity = $fidelity; #store new fidelity + my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + + if ($repeatCnt == 0) { + $repeatCnt = $REPEATEVERY; + } + } else { + $repeatCnt--; + } +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-prediction/system/probes/iostat.h b/targets/znews-ss-prediction/system/probes/iostat.h index 14abd66ec..644e9af0a 100644 --- a/targets/znews-ss-prediction/system/probes/iostat.h +++ b/targets/znews-ss-prediction/system/probes/iostat.h @@ -1,116 +1,116 @@ -/* - * iostat: report CPU and I/O statistics - * (C) 1999-2004 by Sebastien Godard - */ - -#ifndef _IOSTAT_H -#define _IOSTAT_H - -#include "common.h" - -#define MAX_NAME_LEN 72 - -#define D_CPU_ONLY 0x001 -#define D_DISK_ONLY 0x002 -#define D_TIMESTAMP 0x004 -#define D_EXTENDED 0x008 -#define D_PART_ALL 0x010 -#define D_KILOBYTES 0x020 -#define F_HAS_SYSFS 0x040 -#define F_OLD_KERNEL 0x080 -#define D_UNFILTERED 0x100 -/* 0x100000:0x800000 -> reserved (cf. common.h) */ - -#define DISPLAY_CPU_ONLY(m) (((m) & D_CPU_ONLY) == D_CPU_ONLY) -#define DISPLAY_DISK_ONLY(m) (((m) & D_DISK_ONLY) == D_DISK_ONLY) -#define DISPLAY_TIMESTAMP(m) (((m) & D_TIMESTAMP) == D_TIMESTAMP) -#define DISPLAY_EXTENDED(m) (((m) & D_EXTENDED) == D_EXTENDED) -#define DISPLAY_PART_ALL(m) (((m) & D_PART_ALL) == D_PART_ALL) -#define DISPLAY_KILOBYTES(m) (((m) & D_KILOBYTES) == D_KILOBYTES) -#define HAS_SYSFS(m) (((m) & F_HAS_SYSFS) == F_HAS_SYSFS) -#define HAS_OLD_KERNEL(m) (((m) & F_OLD_KERNEL) == F_OLD_KERNEL) -#define DISPLAY_UNFILTERED(m) (((m) & D_UNFILTERED) == D_UNFILTERED) - -#define DT_DEVICE 0 -#define DT_PARTITION 1 - - -struct comm_stats { - unsigned long uptime; - unsigned long uptime0; - unsigned long cpu_iowait; - unsigned long cpu_idle; - unsigned int cpu_user; - unsigned int cpu_nice; - unsigned int cpu_system; -}; - -#define COMM_STATS_SIZE (sizeof(struct comm_stats)) - -/* - * Structures for I/O stats. - * The number of structures allocated corresponds to the number of devices - * present in the system, plus a preallocation number to handle those - * that can be registered dynamically. - * The number of devices is found by using /sys filesystem (if mounted), - * or the number of "disk_io:" entries in /proc/stat (2.4 kernels), - * else the default value is 4 (for old kernels, which maintained stats - * for the first four devices in /proc/stat). - * For each io_stats structure allocated corresponds a io_hdr_stats structure. - * A io_stats structure is considered as unused or "free" (containing no stats - * for a particular device) if the 'major' field of the io_hdr_stats - * structure is set to 0. - */ -struct io_stats { - /* # of read operations issued to the device */ - unsigned int rd_ios __attribute__ ((aligned (8))); - /* # of read requests merged */ - unsigned int rd_merges __attribute__ ((packed)); - /* # of sectors read */ - unsigned int rd_sectors __attribute__ ((packed)); - /* Time of read requests in queue */ - unsigned int rd_ticks __attribute__ ((packed)); - /* # of write operations issued to the device */ - unsigned int wr_ios __attribute__ ((packed)); - /* # of write requests merged */ - unsigned int wr_merges __attribute__ ((packed)); - /* # of sectors written */ - unsigned int wr_sectors __attribute__ ((packed)); - /* Time of write requests in queue */ - unsigned int wr_ticks __attribute__ ((packed)); - /* # of I/Os in progress */ - unsigned int ios_pgr __attribute__ ((packed)); - /* # of ticks total (for this device) for I/O */ - unsigned int tot_ticks __attribute__ ((packed)); - /* # of ticks requests spent in queue */ - unsigned int rq_ticks __attribute__ ((packed)); - /* # of I/O done since last reboot */ - unsigned int dk_drive __attribute__ ((packed)); - /* # of blocks read */ - unsigned int dk_drive_rblk __attribute__ ((packed)); - /* # of blocks written */ - unsigned int dk_drive_wblk __attribute__ ((packed)); -}; - -#define IO_STATS_SIZE (sizeof(struct io_stats)) - -struct io_hdr_stats { - unsigned int active __attribute__ ((aligned (8))); - unsigned int major __attribute__ ((packed)); - unsigned int index __attribute__ ((packed)); - char name[MAX_NAME_LEN] __attribute__ ((packed)); -}; - -#define IO_HDR_STATS_SIZE (sizeof(struct io_hdr_stats)) - -/* List of devices entered on the command line */ -struct io_dlist { - /* Indicate whether its partitions are to be displayed or not */ - int disp_part __attribute__ ((aligned (8))); - /* Device name */ - char dev_name[MAX_NAME_LEN] __attribute__ ((packed)); -}; - -#define IO_DLIST_SIZE (sizeof(struct io_dlist)) - -#endif /* _IOSTAT_H */ +/* + * iostat: report CPU and I/O statistics + * (C) 1999-2004 by Sebastien Godard + */ + +#ifndef _IOSTAT_H +#define _IOSTAT_H + +#include "common.h" + +#define MAX_NAME_LEN 72 + +#define D_CPU_ONLY 0x001 +#define D_DISK_ONLY 0x002 +#define D_TIMESTAMP 0x004 +#define D_EXTENDED 0x008 +#define D_PART_ALL 0x010 +#define D_KILOBYTES 0x020 +#define F_HAS_SYSFS 0x040 +#define F_OLD_KERNEL 0x080 +#define D_UNFILTERED 0x100 +/* 0x100000:0x800000 -> reserved (cf. common.h) */ + +#define DISPLAY_CPU_ONLY(m) (((m) & D_CPU_ONLY) == D_CPU_ONLY) +#define DISPLAY_DISK_ONLY(m) (((m) & D_DISK_ONLY) == D_DISK_ONLY) +#define DISPLAY_TIMESTAMP(m) (((m) & D_TIMESTAMP) == D_TIMESTAMP) +#define DISPLAY_EXTENDED(m) (((m) & D_EXTENDED) == D_EXTENDED) +#define DISPLAY_PART_ALL(m) (((m) & D_PART_ALL) == D_PART_ALL) +#define DISPLAY_KILOBYTES(m) (((m) & D_KILOBYTES) == D_KILOBYTES) +#define HAS_SYSFS(m) (((m) & F_HAS_SYSFS) == F_HAS_SYSFS) +#define HAS_OLD_KERNEL(m) (((m) & F_OLD_KERNEL) == F_OLD_KERNEL) +#define DISPLAY_UNFILTERED(m) (((m) & D_UNFILTERED) == D_UNFILTERED) + +#define DT_DEVICE 0 +#define DT_PARTITION 1 + + +struct comm_stats { + unsigned long uptime; + unsigned long uptime0; + unsigned long cpu_iowait; + unsigned long cpu_idle; + unsigned int cpu_user; + unsigned int cpu_nice; + unsigned int cpu_system; +}; + +#define COMM_STATS_SIZE (sizeof(struct comm_stats)) + +/* + * Structures for I/O stats. + * The number of structures allocated corresponds to the number of devices + * present in the system, plus a preallocation number to handle those + * that can be registered dynamically. + * The number of devices is found by using /sys filesystem (if mounted), + * or the number of "disk_io:" entries in /proc/stat (2.4 kernels), + * else the default value is 4 (for old kernels, which maintained stats + * for the first four devices in /proc/stat). + * For each io_stats structure allocated corresponds a io_hdr_stats structure. + * A io_stats structure is considered as unused or "free" (containing no stats + * for a particular device) if the 'major' field of the io_hdr_stats + * structure is set to 0. + */ +struct io_stats { + /* # of read operations issued to the device */ + unsigned int rd_ios __attribute__ ((aligned (8))); + /* # of read requests merged */ + unsigned int rd_merges __attribute__ ((packed)); + /* # of sectors read */ + unsigned int rd_sectors __attribute__ ((packed)); + /* Time of read requests in queue */ + unsigned int rd_ticks __attribute__ ((packed)); + /* # of write operations issued to the device */ + unsigned int wr_ios __attribute__ ((packed)); + /* # of write requests merged */ + unsigned int wr_merges __attribute__ ((packed)); + /* # of sectors written */ + unsigned int wr_sectors __attribute__ ((packed)); + /* Time of write requests in queue */ + unsigned int wr_ticks __attribute__ ((packed)); + /* # of I/Os in progress */ + unsigned int ios_pgr __attribute__ ((packed)); + /* # of ticks total (for this device) for I/O */ + unsigned int tot_ticks __attribute__ ((packed)); + /* # of ticks requests spent in queue */ + unsigned int rq_ticks __attribute__ ((packed)); + /* # of I/O done since last reboot */ + unsigned int dk_drive __attribute__ ((packed)); + /* # of blocks read */ + unsigned int dk_drive_rblk __attribute__ ((packed)); + /* # of blocks written */ + unsigned int dk_drive_wblk __attribute__ ((packed)); +}; + +#define IO_STATS_SIZE (sizeof(struct io_stats)) + +struct io_hdr_stats { + unsigned int active __attribute__ ((aligned (8))); + unsigned int major __attribute__ ((packed)); + unsigned int index __attribute__ ((packed)); + char name[MAX_NAME_LEN] __attribute__ ((packed)); +}; + +#define IO_HDR_STATS_SIZE (sizeof(struct io_hdr_stats)) + +/* List of devices entered on the command line */ +struct io_dlist { + /* Indicate whether its partitions are to be displayed or not */ + int disp_part __attribute__ ((aligned (8))); + /* Device name */ + char dev_name[MAX_NAME_LEN] __attribute__ ((packed)); +}; + +#define IO_DLIST_SIZE (sizeof(struct io_dlist)) + +#endif /* _IOSTAT_H */ diff --git a/targets/znews-ss-prediction/system/probes/iostats.txt b/targets/znews-ss-prediction/system/probes/iostats.txt index 612dc5511..ba75611ea 100644 --- a/targets/znews-ss-prediction/system/probes/iostats.txt +++ b/targets/znews-ss-prediction/system/probes/iostats.txt @@ -1,151 +1,151 @@ -I/O statistics fields ---------------- - -Based on kernel version 2.6.20. Page generated on 2007-02-07 22:05 EST -Last modified Sep 30, 2003 - -Since 2.4.20 (and some versions before, with patches), and 2.5.45, -more extensive disk statistics have been introduced to help measure disk -activity. Tools such as sar and iostat typically interpret these and do -the work for you, but in case you are interested in creating your own -tools, the fields are explained here. - -In 2.4 now, the information is found as additional fields in -/proc/partitions. In 2.6, the same information is found in two -places: one is in the file /proc/diskstats, and the other is within -the sysfs file system, which must be mounted in order to obtain -the information. Throughout this document we'll assume that sysfs -is mounted on /sys, although of course it may be mounted anywhere. -Both /proc/diskstats and sysfs use the same source for the information -and so should not differ. - -Here are examples of these different formats: - -2.4: - 3 0 39082680 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 3 1 9221278 hda1 35486 0 35496 38030 0 0 0 0 0 38030 38030 - - -2.6 sysfs: - 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 35486 38030 38030 38030 - -2.6 diskstats: - 3 0 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 3 1 hda1 35486 38030 38030 38030 - -On 2.4 you might execute "grep 'hda ' /proc/partitions". On 2.6, you have -a choice of "cat /sys/block/hda/stat" or "grep 'hda ' /proc/diskstats". -The advantage of one over the other is that the sysfs choice works well -if you are watching a known, small set of disks. /proc/diskstats may -be a better choice if you are watching a large number of disks because -you'll avoid the overhead of 50, 100, or 500 or more opens/closes with -each snapshot of your disk statistics. - -In 2.4, the statistics fields are those after the device name. In -the above example, the first field of statistics would be 446216. -By contrast, in 2.6 if you look at /sys/block/hda/stat, you'll -find just the eleven fields, beginning with 446216. If you look at -/proc/diskstats, the eleven fields will be preceded by the major and -minor device numbers, and device name. Each of these formats provide -eleven fields of statistics, each meaning exactly the same things. -All fields except field 9 are cumulative since boot. Field 9 should -go to zero as I/Os complete; all others only increase. Yes, these are -32 bit unsigned numbers, and on a very busy or long-lived system they -may wrap. Applications should be prepared to deal with that; unless -your observations are measured in large numbers of minutes or hours, -they should not wrap twice before you notice them. - -Each set of stats only applies to the indicated device; if you want -system-wide stats you'll have to find all the devices and sum them all up. - -Field 1 -- # of reads issued - This is the total number of reads completed successfully. -Field 2 -- # of reads merged, field 6 -- # of writes merged - Reads and writes which are adjacent to each other may be merged for - efficiency. Thus two 4K reads may become one 8K read before it is - ultimately handed to the disk, and so it will be counted (and queued) - as only one I/O. This field lets you know how often this was done. -Field 3 -- # of sectors read - This is the total number of sectors read successfully. -Field 4 -- # of milliseconds spent reading - This is the total number of milliseconds spent by all reads (as - measured from __make_request() to end_that_request_last()). -Field 5 -- # of writes completed - This is the total number of writes completed successfully. -Field 7 -- # of sectors written - This is the total number of sectors written successfully. -Field 8 -- # of milliseconds spent writing - This is the total number of milliseconds spent by all writes (as - measured from __make_request() to end_that_request_last()). -Field 9 -- # of I/Os currently in progress - The only field that should go to zero. Incremented as requests are - given to appropriate request_queue_t and decremented as they finish. -Field 10 -- # of milliseconds spent doing I/Os - This field is increases so long as field 9 is nonzero. -Field 11 -- weighted # of milliseconds spent doing I/Os - This field is incremented at each I/O start, I/O completion, I/O - merge, or read of these stats by the number of I/Os in progress - (field 9) times the number of milliseconds spent doing I/O since the - last update of this field. This can provide an easy measure of both - I/O completion time and the backlog that may be accumulating. - - -To avoid introducing performance bottlenecks, no locks are held while -modifying these counters. This implies that minor inaccuracies may be -introduced when changes collide, so (for instance) adding up all the -read I/Os issued per partition should equal those made to the disks ... -but due to the lack of locking it may only be very close. - -In 2.6, there are counters for each cpu, which made the lack of locking -almost a non-issue. When the statistics are read, the per-cpu counters -are summed (possibly overflowing the unsigned 32-bit variable they are -summed to) and the result given to the user. There is no convenient -user interface for accessing the per-cpu counters themselves. - -Disks vs Partitions -------------------- - -There were significant changes between 2.4 and 2.6 in the I/O subsystem. -As a result, some statistic information disappeared. The translation from -a disk address relative to a partition to the disk address relative to -the host disk happens much earlier. All merges and timings now happen -at the disk level rather than at both the disk and partition level as -in 2.4. Consequently, you'll see a different statistics output on 2.6 for -partitions from that for disks. There are only *four* fields available -for partitions on 2.6 machines. This is reflected in the examples above. - -Field 1 -- # of reads issued - This is the total number of reads issued to this partition. -Field 2 -- # of sectors read - This is the total number of sectors requested to be read from this - partition. -Field 3 -- # of writes issued - This is the total number of writes issued to this partition. -Field 4 -- # of sectors written - This is the total number of sectors requested to be written to - this partition. - -Note that since the address is translated to a disk-relative one, and no -record of the partition-relative address is kept, the subsequent success -or failure of the read cannot be attributed to the partition. In other -words, the number of reads for partitions is counted slightly before time -of queuing for partitions, and at completion for whole disks. This is -a subtle distinction that is probably uninteresting for most cases. - -Additional notes ----------------- - -In 2.6, sysfs is not mounted by default. If your distribution of -Linux hasn't added it already, here's the line you'll want to add to -your /etc/fstab: - -none /sys sysfs defaults 0 0 - - -In 2.6, all disk statistics were removed from /proc/stat. In 2.4, they -appear in both /proc/partitions and /proc/stat, although the ones in -/proc/stat take a very different format from those in /proc/partitions -(see proc(5), if your system has it.) - --- ricklind[AT]us.ibm[DOT]com +I/O statistics fields +--------------- + +Based on kernel version 2.6.20. Page generated on 2007-02-07 22:05 EST +Last modified Sep 30, 2003 + +Since 2.4.20 (and some versions before, with patches), and 2.5.45, +more extensive disk statistics have been introduced to help measure disk +activity. Tools such as sar and iostat typically interpret these and do +the work for you, but in case you are interested in creating your own +tools, the fields are explained here. + +In 2.4 now, the information is found as additional fields in +/proc/partitions. In 2.6, the same information is found in two +places: one is in the file /proc/diskstats, and the other is within +the sysfs file system, which must be mounted in order to obtain +the information. Throughout this document we'll assume that sysfs +is mounted on /sys, although of course it may be mounted anywhere. +Both /proc/diskstats and sysfs use the same source for the information +and so should not differ. + +Here are examples of these different formats: + +2.4: + 3 0 39082680 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 3 1 9221278 hda1 35486 0 35496 38030 0 0 0 0 0 38030 38030 + + +2.6 sysfs: + 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 35486 38030 38030 38030 + +2.6 diskstats: + 3 0 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 3 1 hda1 35486 38030 38030 38030 + +On 2.4 you might execute "grep 'hda ' /proc/partitions". On 2.6, you have +a choice of "cat /sys/block/hda/stat" or "grep 'hda ' /proc/diskstats". +The advantage of one over the other is that the sysfs choice works well +if you are watching a known, small set of disks. /proc/diskstats may +be a better choice if you are watching a large number of disks because +you'll avoid the overhead of 50, 100, or 500 or more opens/closes with +each snapshot of your disk statistics. + +In 2.4, the statistics fields are those after the device name. In +the above example, the first field of statistics would be 446216. +By contrast, in 2.6 if you look at /sys/block/hda/stat, you'll +find just the eleven fields, beginning with 446216. If you look at +/proc/diskstats, the eleven fields will be preceded by the major and +minor device numbers, and device name. Each of these formats provide +eleven fields of statistics, each meaning exactly the same things. +All fields except field 9 are cumulative since boot. Field 9 should +go to zero as I/Os complete; all others only increase. Yes, these are +32 bit unsigned numbers, and on a very busy or long-lived system they +may wrap. Applications should be prepared to deal with that; unless +your observations are measured in large numbers of minutes or hours, +they should not wrap twice before you notice them. + +Each set of stats only applies to the indicated device; if you want +system-wide stats you'll have to find all the devices and sum them all up. + +Field 1 -- # of reads issued + This is the total number of reads completed successfully. +Field 2 -- # of reads merged, field 6 -- # of writes merged + Reads and writes which are adjacent to each other may be merged for + efficiency. Thus two 4K reads may become one 8K read before it is + ultimately handed to the disk, and so it will be counted (and queued) + as only one I/O. This field lets you know how often this was done. +Field 3 -- # of sectors read + This is the total number of sectors read successfully. +Field 4 -- # of milliseconds spent reading + This is the total number of milliseconds spent by all reads (as + measured from __make_request() to end_that_request_last()). +Field 5 -- # of writes completed + This is the total number of writes completed successfully. +Field 7 -- # of sectors written + This is the total number of sectors written successfully. +Field 8 -- # of milliseconds spent writing + This is the total number of milliseconds spent by all writes (as + measured from __make_request() to end_that_request_last()). +Field 9 -- # of I/Os currently in progress + The only field that should go to zero. Incremented as requests are + given to appropriate request_queue_t and decremented as they finish. +Field 10 -- # of milliseconds spent doing I/Os + This field is increases so long as field 9 is nonzero. +Field 11 -- weighted # of milliseconds spent doing I/Os + This field is incremented at each I/O start, I/O completion, I/O + merge, or read of these stats by the number of I/Os in progress + (field 9) times the number of milliseconds spent doing I/O since the + last update of this field. This can provide an easy measure of both + I/O completion time and the backlog that may be accumulating. + + +To avoid introducing performance bottlenecks, no locks are held while +modifying these counters. This implies that minor inaccuracies may be +introduced when changes collide, so (for instance) adding up all the +read I/Os issued per partition should equal those made to the disks ... +but due to the lack of locking it may only be very close. + +In 2.6, there are counters for each cpu, which made the lack of locking +almost a non-issue. When the statistics are read, the per-cpu counters +are summed (possibly overflowing the unsigned 32-bit variable they are +summed to) and the result given to the user. There is no convenient +user interface for accessing the per-cpu counters themselves. + +Disks vs Partitions +------------------- + +There were significant changes between 2.4 and 2.6 in the I/O subsystem. +As a result, some statistic information disappeared. The translation from +a disk address relative to a partition to the disk address relative to +the host disk happens much earlier. All merges and timings now happen +at the disk level rather than at both the disk and partition level as +in 2.4. Consequently, you'll see a different statistics output on 2.6 for +partitions from that for disks. There are only *four* fields available +for partitions on 2.6 machines. This is reflected in the examples above. + +Field 1 -- # of reads issued + This is the total number of reads issued to this partition. +Field 2 -- # of sectors read + This is the total number of sectors requested to be read from this + partition. +Field 3 -- # of writes issued + This is the total number of writes issued to this partition. +Field 4 -- # of sectors written + This is the total number of sectors requested to be written to + this partition. + +Note that since the address is translated to a disk-relative one, and no +record of the partition-relative address is kept, the subsequent success +or failure of the read cannot be attributed to the partition. In other +words, the number of reads for partitions is counted slightly before time +of queuing for partitions, and at completion for whole disks. This is +a subtle distinction that is probably uninteresting for most cases. + +Additional notes +---------------- + +In 2.6, sysfs is not mounted by default. If your distribution of +Linux hasn't added it already, here's the line you'll want to add to +your /etc/fstab: + +none /sys sysfs defaults 0 0 + + +In 2.6, all disk statistics were removed from /proc/stat. In 2.4, they +appear in both /proc/partitions and /proc/stat, although the ones in +/proc/stat take a very different format from those in /proc/partitions +(see proc(5), if your system has it.) + +-- ricklind[AT]us.ibm[DOT]com diff --git a/targets/znews-ss-prediction/system/probes/loadProbe.pl b/targets/znews-ss-prediction/system/probes/loadProbe.pl index 7f2e12dc8..3b648fd9c 100644 --- a/targets/znews-ss-prediction/system/probes/loadProbe.pl +++ b/targets/znews-ss-prediction/system/probes/loadProbe.pl @@ -1,101 +1,101 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "load"; -my $NAME = "LoadProbe"; -my $DELAY = 2500; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current CPU usage to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic CPU usage info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub cpuTime () { - my ($user, $nice, $sys, $idle, $iowait); - - local(*FIN); - open(FIN, ") { - chomp; - if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(\s+(\d+))?/o) { - ($user, $nice, $sys, $idle, $iowait) = ($1, $2, $3, $4, $6); - if (!defined($iowait)) { - $iowait = 0; - } - last; - } - } - close(FIN); - return ($user, $nice, $sys, $idle, $iowait); -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# save current cpu ticks -my($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = cpuTime(); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # retrieve new cpu ticks - my ($userN, $niceN, $sysN, $idleN, $iowaitN) = cpuTime(); - # compute delta cpu ticks - my ($user, $nice, $sys, $idle, $iowait) = - ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv, $iowaitN - $iowaitSv); - # store the new saved ticks - ($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = ($userN, $niceN, $sysN, $idleN, $iowaitN); - my $total = $user + $nice + $sys + $idle + $iowait; - my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), - $user/$total, $nice/$total, $sys/$total, $idle/$total, $iowait/$total); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "load"; +my $NAME = "LoadProbe"; +my $DELAY = 2500; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current CPU usage to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic CPU usage info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub cpuTime () { + my ($user, $nice, $sys, $idle, $iowait); + + local(*FIN); + open(FIN, ") { + chomp; + if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(\s+(\d+))?/o) { + ($user, $nice, $sys, $idle, $iowait) = ($1, $2, $3, $4, $6); + if (!defined($iowait)) { + $iowait = 0; + } + last; + } + } + close(FIN); + return ($user, $nice, $sys, $idle, $iowait); +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# save current cpu ticks +my($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = cpuTime(); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # retrieve new cpu ticks + my ($userN, $niceN, $sysN, $idleN, $iowaitN) = cpuTime(); + # compute delta cpu ticks + my ($user, $nice, $sys, $idle, $iowait) = + ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv, $iowaitN - $iowaitSv); + # store the new saved ticks + ($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = ($userN, $niceN, $sysN, $idleN, $iowaitN); + my $total = $user + $nice + $sys + $idle + $iowait; + my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), + $user/$total, $nice/$total, $sys/$total, $idle/$total, $iowait/$total); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss-prediction/system/probes/runApachetop.pl b/targets/znews-ss-prediction/system/probes/runApachetop.pl index 2d9a80a4d..741ee43f6 100644 --- a/targets/znews-ss-prediction/system/probes/runApachetop.pl +++ b/targets/znews-ss-prediction/system/probes/runApachetop.pl @@ -1,16 +1,16 @@ -#!/usr/bin/perl -w - -use strict; - -############################# -my $APACHE_LOG = "/var/log/apache2/access-delegate.log"; -my $APACHETOP_LOG = "../../log/apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - -if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; +#!/usr/bin/perl -w + +use strict; + +############################# +my $APACHE_LOG = "/var/log/apache2/access-delegate.log"; +my $APACHETOP_LOG = "../../log/apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + +if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; diff --git a/targets/znews-ss-prediction/system/webpages/www1/index.html b/targets/znews-ss-prediction/system/webpages/www1/index.html index 050159b89..4ec9f5304 100644 --- a/targets/znews-ss-prediction/system/webpages/www1/index.html +++ b/targets/znews-ss-prediction/system/webpages/www1/index.html @@ -1,46 +1,46 @@ - - -Somewhere Over the Rainbow - - -

Z.com News - Hello World! (Low-fidelity Settings)

- -We apologize for this text-only content, as we are currently swamped with visitors. Thank you for your patience as we work hard to serve your requests. (This file is a little over 3 KB.) -

-SYDNEY, Australia (Reuters) -- In death as in life, iconic TV naturalist Steve Irwin captivated millions worldwide and clogged the Internet as fans from Guam to Glasgow reacted with disbelief to news "The Crocodile Hunter" was dead. -

-Some Web sites groaned to a halt within hours of the first reports Monday that Irwin had been killed by a stingray's barb through his chest in a freak diving accident off Australia's northeast coast. -

-Web measurement company Hitwise said Irwin's death was the biggest news event read by Australians on the Internet since two Australian miners were trapped by a mine collapse in southern Tasmania state in late April. -

-"We noticed that the Web site www.crocodilehunter.com increased in popularity quite substantially. It became the number one entertainment personality Web site in Australia yesterday and in the United States it also became the third most popular," Hitwise Asia-Pacific marketing director James Borg told Reuters. -

-Australian news Web sites struggled to keep up with demand. -

-The Australian Broadcasting Corp.'s site (www.abc.com.au) had to temporarily shut down, posting a notice Monday that it was experiencing higher than normal traffic. -

-It resumed soon after in a low-bandwidth format to cope with hundreds of thousands of hits. -

-Newspaper Web sites also wobbled but kept up with demand. -

-A spokesman for The Sydney Morning Herald's site, www.smh.com.au, said it had experienced a "huge" 40 percent spike in page impressions compared with the previous week's average weekday number of about 500,000. -

-There was also a 70 percent jump in visitors to its pages, the spokesman said. -

-That pattern was mirrored around the world, with Irwin's death leading major news Web sites such as CNN.com and U.S. and British newspaper Web sites, as well as swamping their most viewed and most emailed categories. -

-Web logs and Internet feedback pages were also awash with postings from shocked readers from around the world, many of them from Americans charmed by Irwin's quirky style and his typically Australian catchphrase of "crikey." -

-Irwin first found fame in the United States before his "Crocodile Hunter" documentaries on U.S.-based television company Discovery Communications' Animal Planet attracted a global audience of 200 million -- 10 times Australia's population. -

-"Crikey!, I miss him so much," Tina Treece from Pittsburgh, Pennsylvania, posted on CNN.com's feedback page CNN Exchange. -

-The site had contributions from readers in Guam, Romania, Thailand, France, Scotland, India, New Zealand, Canada, Brunei, Britain, Malaysia, Denmark and the Netherlands. -

-Many faced the problem of explaining to their children how one of their favorite TV characters had died. -

-"Why did it have to be Steve Irwin?" 11-year-old Daniel told Australian Associated Press. -

-Copyright 2006 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed. - - + + +Somewhere Over the Rainbow + + +

Z.com News - Hello World! (Low-fidelity Settings)

+ +We apologize for this text-only content, as we are currently swamped with visitors. Thank you for your patience as we work hard to serve your requests. (This file is a little over 3 KB.) +

+SYDNEY, Australia (Reuters) -- In death as in life, iconic TV naturalist Steve Irwin captivated millions worldwide and clogged the Internet as fans from Guam to Glasgow reacted with disbelief to news "The Crocodile Hunter" was dead. +

+Some Web sites groaned to a halt within hours of the first reports Monday that Irwin had been killed by a stingray's barb through his chest in a freak diving accident off Australia's northeast coast. +

+Web measurement company Hitwise said Irwin's death was the biggest news event read by Australians on the Internet since two Australian miners were trapped by a mine collapse in southern Tasmania state in late April. +

+"We noticed that the Web site www.crocodilehunter.com increased in popularity quite substantially. It became the number one entertainment personality Web site in Australia yesterday and in the United States it also became the third most popular," Hitwise Asia-Pacific marketing director James Borg told Reuters. +

+Australian news Web sites struggled to keep up with demand. +

+The Australian Broadcasting Corp.'s site (www.abc.com.au) had to temporarily shut down, posting a notice Monday that it was experiencing higher than normal traffic. +

+It resumed soon after in a low-bandwidth format to cope with hundreds of thousands of hits. +

+Newspaper Web sites also wobbled but kept up with demand. +

+A spokesman for The Sydney Morning Herald's site, www.smh.com.au, said it had experienced a "huge" 40 percent spike in page impressions compared with the previous week's average weekday number of about 500,000. +

+There was also a 70 percent jump in visitors to its pages, the spokesman said. +

+That pattern was mirrored around the world, with Irwin's death leading major news Web sites such as CNN.com and U.S. and British newspaper Web sites, as well as swamping their most viewed and most emailed categories. +

+Web logs and Internet feedback pages were also awash with postings from shocked readers from around the world, many of them from Americans charmed by Irwin's quirky style and his typically Australian catchphrase of "crikey." +

+Irwin first found fame in the United States before his "Crocodile Hunter" documentaries on U.S.-based television company Discovery Communications' Animal Planet attracted a global audience of 200 million -- 10 times Australia's population. +

+"Crikey!, I miss him so much," Tina Treece from Pittsburgh, Pennsylvania, posted on CNN.com's feedback page CNN Exchange. +

+The site had contributions from readers in Guam, Romania, Thailand, France, Scotland, India, New Zealand, Canada, Brunei, Britain, Malaysia, Denmark and the Netherlands. +

+Many faced the problem of explaining to their children how one of their favorite TV characters had died. +

+"Why did it have to be Steve Irwin?" 11-year-old Daniel told Australian Associated Press. +

+Copyright 2006 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed. + + diff --git a/targets/znews-ss-prediction/system/webpages/www3/index.html b/targets/znews-ss-prediction/system/webpages/www3/index.html index d5801caa4..dee934b7c 100644 --- a/targets/znews-ss-prediction/system/webpages/www3/index.html +++ b/targets/znews-ss-prediction/system/webpages/www3/index.html @@ -1,11 +1,11 @@ - - -Somewhere Over the Rainbow - - -

Z.com News - Hello World! (Medium-fidelity Settings)

-This file contains an 800x600 pixel image. The total size of this file is approximately 53K. -
- - + + +Somewhere Over the Rainbow + + +

Z.com News - Hello World! (Medium-fidelity Settings)

+This file contains an 800x600 pixel image. The total size of this file is approximately 53K. +
+ + \ No newline at end of file diff --git a/targets/znews-ss-prediction/system/webpages/www5/cgi-bin/computePi.pl b/targets/znews-ss-prediction/system/webpages/www5/cgi-bin/computePi.pl index 6871ac9b4..235516a09 100644 --- a/targets/znews-ss-prediction/system/webpages/www5/cgi-bin/computePi.pl +++ b/targets/znews-ss-prediction/system/webpages/www5/cgi-bin/computePi.pl @@ -1,118 +1,118 @@ -#!/usr/bin/perl - -use strict; -use Carp; -use Math::BigFloat; -use Class::Struct qw(struct); -use Data::Dumper; - -# With due homage to Mathsoft's site: -# http://www.mathsoft.com/asolve/constant/pi/pi.html - -# Set the global precision. Faster than passing it everywhichwhere. -my $precision = @ARGV>0?$ARGV[0]:512; - -# Set the iteration count. -my $maxIterations = @ARGV>1?$ARGV[1]:10; - -# Set the verbose debugging flag. -my $debugVerbose = 0; - -# Constants: -my $_1 = Math::BigFloat->new(1); -my $_2 = Math::BigFloat->new(2); -my $_3 = Math::BigFloat->new(3); -my $_4 = Math::BigFloat->new(4); -my $_6 = Math::BigFloat->new(6); -my $_8 = Math::BigFloat->new(8); -my $_239 = Math::BigFloat->new(239); -my $_half = Math::BigFloat->new(0.5); -my $_fifth = Math::BigFloat->new(0.2); -my $_25th = Math::BigFloat->new(0.04); -my $_239th = inv($_239); -my $_57121th = inv($_239*$_239); - - -# Utility methods: -sub div { - my $a = shift; - my $b = shift; - return new Math::BigFloat $a->copy()->fdiv($b,$precision); -} -sub inv { # Inverse (1/x) function. - my $a = shift; - return new Math::BigFloat $_1->copy()->fdiv($a,$precision); -} -sub root2 { - my $self = shift; - return new Math::BigFloat $self->copy()->fsqrt($precision); -} -sub root4 { - my $self = shift; - return root2(root2($self)); -} -sub pow4 { - my $self = shift; - my $square = round($self*$self); - return round($square*$square); -} -sub round { - my $self = shift; - return new Math::BigFloat $self->copy()->fround($precision); -} - -# Method 4: - -# This uses Ramanujan's elliptic integral-based technique to -# compute Pi monstrously quickly. -# -# This algorithm is neat, since it is quartically convergent - -# that means that the error goes as 4^(-iteration_count). -# -# In other words, one more step = four times the # of correct digits. - -sub RamanujanEI { - if (@_) { - my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. - - my $z_4_term = root4($_1 - pow4($z)); - my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); - - my $z_next_plus_1 = $z_next + $_1; - - my $a_next = pow4($z_next_plus_1) * $a - - $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); - $a_next = round($a_next); - return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; - - } else { # Seed the recurrence - my $a = $_6-$_4*root2($_2); - return [ $a, root2($_2)-$_1, $_8, inv($a)]; - } -} - - - -###################################################################### -# -# Main routine: -# -# - -my $iterResult = RamanujanEI(); -for (my $i=1; $i<$maxIterations; $i++) { - $iterResult = RamanujanEI($iterResult); -} -my $piValue = ${$iterResult}[-1]; -my $piStr = "" . $piValue; - -my $CHUNK = 32; -my $i = $CHUNK + 1; -print "Content-type: text/plain\r\n"; -print "Content-length: 570\r\n\r\n"; -print "Pi_512 :=\n"; -print " " . substr($piValue, 0, $i) . "\n"; -for (; $i < length($piValue) ; $i+=$CHUNK) { - print " " . substr($piValue, $i, $CHUNK) . "\n"; -} - +#!/usr/bin/perl + +use strict; +use Carp; +use Math::BigFloat; +use Class::Struct qw(struct); +use Data::Dumper; + +# With due homage to Mathsoft's site: +# http://www.mathsoft.com/asolve/constant/pi/pi.html + +# Set the global precision. Faster than passing it everywhichwhere. +my $precision = @ARGV>0?$ARGV[0]:512; + +# Set the iteration count. +my $maxIterations = @ARGV>1?$ARGV[1]:10; + +# Set the verbose debugging flag. +my $debugVerbose = 0; + +# Constants: +my $_1 = Math::BigFloat->new(1); +my $_2 = Math::BigFloat->new(2); +my $_3 = Math::BigFloat->new(3); +my $_4 = Math::BigFloat->new(4); +my $_6 = Math::BigFloat->new(6); +my $_8 = Math::BigFloat->new(8); +my $_239 = Math::BigFloat->new(239); +my $_half = Math::BigFloat->new(0.5); +my $_fifth = Math::BigFloat->new(0.2); +my $_25th = Math::BigFloat->new(0.04); +my $_239th = inv($_239); +my $_57121th = inv($_239*$_239); + + +# Utility methods: +sub div { + my $a = shift; + my $b = shift; + return new Math::BigFloat $a->copy()->fdiv($b,$precision); +} +sub inv { # Inverse (1/x) function. + my $a = shift; + return new Math::BigFloat $_1->copy()->fdiv($a,$precision); +} +sub root2 { + my $self = shift; + return new Math::BigFloat $self->copy()->fsqrt($precision); +} +sub root4 { + my $self = shift; + return root2(root2($self)); +} +sub pow4 { + my $self = shift; + my $square = round($self*$self); + return round($square*$square); +} +sub round { + my $self = shift; + return new Math::BigFloat $self->copy()->fround($precision); +} + +# Method 4: + +# This uses Ramanujan's elliptic integral-based technique to +# compute Pi monstrously quickly. +# +# This algorithm is neat, since it is quartically convergent - +# that means that the error goes as 4^(-iteration_count). +# +# In other words, one more step = four times the # of correct digits. + +sub RamanujanEI { + if (@_) { + my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. + + my $z_4_term = root4($_1 - pow4($z)); + my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); + + my $z_next_plus_1 = $z_next + $_1; + + my $a_next = pow4($z_next_plus_1) * $a - + $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); + $a_next = round($a_next); + return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; + + } else { # Seed the recurrence + my $a = $_6-$_4*root2($_2); + return [ $a, root2($_2)-$_1, $_8, inv($a)]; + } +} + + + +###################################################################### +# +# Main routine: +# +# + +my $iterResult = RamanujanEI(); +for (my $i=1; $i<$maxIterations; $i++) { + $iterResult = RamanujanEI($iterResult); +} +my $piValue = ${$iterResult}[-1]; +my $piStr = "" . $piValue; + +my $CHUNK = 32; +my $i = $CHUNK + 1; +print "Content-type: text/plain\r\n"; +print "Content-length: 570\r\n\r\n"; +print "Pi_512 :=\n"; +print " " . substr($piValue, 0, $i) . "\n"; +for (; $i < length($piValue) ; $i+=$CHUNK) { + print " " . substr($piValue, $i, $CHUNK) . "\n"; +} + diff --git a/targets/znews-ss-prediction/system/webpages/www5/cgi-bin/piComputeLib.pl b/targets/znews-ss-prediction/system/webpages/www5/cgi-bin/piComputeLib.pl index c14fe9400..23ce98e01 100644 --- a/targets/znews-ss-prediction/system/webpages/www5/cgi-bin/piComputeLib.pl +++ b/targets/znews-ss-prediction/system/webpages/www5/cgi-bin/piComputeLib.pl @@ -1,233 +1,233 @@ -#!/usr/bin/perl - -#map$x+=(-1)**$_*4/(2*$_+1),0..1e6;die$x - -use strict; -use Carp; -use Math::BigFloat; -use Class::Struct qw(struct); -use Data::Dumper; - -# With due homage to Mathsoft's site: -# http://www.mathsoft.com/asolve/constant/pi/pi.html - -# Set the global precision. Faster than passing it everywhichwhere. -my $precision = @ARGV>0?$ARGV[0]:10; - -# Set the iteration count. -my $maxIterations = @ARGV>1?$ARGV[1]:10; - -# Set the verbose debugging flag. -my $debugVerbose = 0; - -# Constants: -my $_1 = Math::BigFloat->new(1); -my $_2 = Math::BigFloat->new(2); -my $_3 = Math::BigFloat->new(3); -my $_4 = Math::BigFloat->new(4); -my $_6 = Math::BigFloat->new(6); -my $_8 = Math::BigFloat->new(8); -my $_239 = Math::BigFloat->new(239); -my $_half = Math::BigFloat->new(0.5); -my $_fifth = Math::BigFloat->new(0.2); -my $_25th = Math::BigFloat->new(0.04); -my $_239th = inv($_239); -my $_57121th = inv($_239*$_239); - - -# Utility methods: -sub div { - my $a = shift; - my $b = shift; - return new Math::BigFloat $a->copy()->fdiv($b,$precision); -} -sub inv { # Inverse (1/x) function. - my $a = shift; - return new Math::BigFloat $_1->copy()->fdiv($a,$precision); -} -sub root2 { - my $self = shift; - return new Math::BigFloat $self->copy()->fsqrt($precision); -} -sub root4 { - my $self = shift; - return root2(root2($self)); -} -sub pow4 { - my $self = shift; - my $square = round($self*$self); - return round($square*$square); -} -sub round { - my $self = shift; - return new Math::BigFloat $self->copy()->fround($precision); -} - - -# Method 1: - -# This gives Archimedes' approximation, -# 3+10/71 < Pi < 3+1/7 -# ...on the 4th iteration. - -sub BorchardtPfaff { - if (@_) { - my ($a,$b) = @{shift()}; # Retrieve the last iteration. - my $a_next = div( $_2*$a*$b, $a+$b ); - my $b_next = root2($a_next*$b); - return [ round($a_next), round($b_next) ]; - } else { # Seed the recurrence - return [ $_2*root2($_3), $_3 ]; - } -} - -# Method 2: - -# This uses Borwein's AGM method to compute Pi very quickly. -# The 'AGM' is short for the iterated arithmetic-geometric mean; -# which was looked at by Lagrange and Gauss way back in 1799. -# We basically look at the tuple [a,b] which holds the arithmetic -# and geometric means of the previous iteration: -# a[n+1] = (a[n] + b[n])/2 // Arithmetic mean -# b[n+1] = sqrt(a[n] * b[n]) // Geometric mean -# -# This algorithm is neat, since it is quadratically convergent - -# that means that the error goes as 2^(-iteration_count). -# -# In other words, one more step = twice the # of correct digits. - -sub BorweinAGM { - if (@_) { - my ($a,$b,$pi) = @{shift()}; # Retrieve the last iteration. - - my $sqrt_a = root2($a); - my $inv_sqrt_a = inv($sqrt_a); - my $b_plus_1 = $b+$_1; - - my $a_next = $_half * ($sqrt_a+$inv_sqrt_a); - my $b_next = div( $b*$sqrt_a+$inv_sqrt_a , $b_plus_1 ); - my $pi_next = $pi*div( $a_next+$_1 , $b_next+$_1 ); - return [ round($a_next), round($b_next), round($pi_next) ]; - - } else { # Seed the recurrence - my $a0 = root2($_2); - my $pi0 = $_2+root2($_2); - my $b1 = root2($a0); # = root4($_2) - my $a1 = $_half * ($b1 + inv($b1)); - - return [ round($a1), round($b1), round($pi0 * div($a1 + $_1, $b1 + $_1)) ]; - } -} - -# Method 3: - -# The arctangent approximation, as determined by Machin (1706). -# Pi = 4(4 * arctan(1/5) - arctan(1/239)), -# ...where arctan(x) = sum( (-1)^k/(2*k+1)*x^(2*k+1), x=0..infinity). - -sub ArctanPi { - if (@_) { - my ($k, $atan5, $atan239, $denom5, $denom239, $pi) = @{shift()}; # Retrieve the last iteration. - - $k++; - my $parity=$k & 1; - $denom5 = $denom5 * $_25th; - - my $inv_2_k_plus_1='Math::BigFloat'->new(2*$k+1); - - my $term5 = div($denom5, $inv_2_k_plus_1 ); - $denom239 = $denom239 * $_57121th; - - my $term239 = div($denom239, $inv_2_k_plus_1 ); - $atan5 = $parity ? $atan5 - $term5 : $atan5 + $term5; - $atan239 = $parity ? $atan239 - $term239 : $atan239 + $term239; - my $pi = $_4*($_4*$atan5 - $atan239); - - return [ $k, round($atan5), round($atan239), - round($denom5), round($denom239), round($pi) ]; - } else { # Seed the recurrence - my ($k, $atan5, $atan239) = (0, $_fifth, $_239th); - return [ $k, $atan5, $atan239, $atan5, $atan239, $_4*($_4*$atan5 - $atan239)]; - } -} - -# Method 4: - -# This uses Ramanujan's elliptic integral-based technique to -# compute Pi monstrously quickly. -# -# This algorithm is neat, since it is quartically convergent - -# that means that the error goes as 4^(-iteration_count). -# -# In other words, one more step = four times the # of correct digits. - -sub RamanujanEI { - if (@_) { - my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. - - my $z_4_term = root4($_1 - pow4($z)); - my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); - - my $z_next_plus_1 = $z_next + $_1; - - my $a_next = pow4($z_next_plus_1) * $a - - $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); - $a_next = round($a_next); - return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; - - } else { # Seed the recurrence - my $a = $_6-$_4*root2($_2); - return [ $a, root2($_2)-$_1, $_8, inv($a)]; - } -} - - - -###################################################################### -# -# Main routine: -# -# - -my $methods = ["BorchardtPfaff", "ArctanPi", "BorweinAGM", "RamanujanEI" ]; - -my $longestMethodLen=0; -foreach my $method (@{$methods}) { - $longestMethodLen = length($method) if length($method) > $longestMethodLen; -} - -my $pis = [ BorchardtPfaff(), ArctanPi(), BorweinAGM(), RamanujanEI() ]; - -for (my $i=0; $i<$maxIterations; $i++) { - print "Iteration $i:\n"; - if (!$debugVerbose) { - for (my $j=0; $j<@{$methods}; $j++) { - - # The following piece of line noise is equivalent to the - # STL C++, " - - # piValue = pis[j].last(); - - # ", if the declaration for pis is: - - # std::vector > pis; - # - - my $methodName = ${$methods}[$j]; - my $piValue = ${${$pis}[$j]}[-1]; - print ${$methods}[$j] . ": " . - ' ' x ($longestMethodLen - length($methodName)) . - $piValue . "\n"; - } - print "\n"; - } - print(Dumper($pis)) if $debugVerbose; - - last if $i+1 == $maxIterations; - - $pis = [ BorchardtPfaff(${$pis}[0]), - ArctanPi(${$pis}[1]), - BorweinAGM(${$pis}[2]), - RamanujanEI(${$pis}[3]) ]; -} - +#!/usr/bin/perl + +#map$x+=(-1)**$_*4/(2*$_+1),0..1e6;die$x + +use strict; +use Carp; +use Math::BigFloat; +use Class::Struct qw(struct); +use Data::Dumper; + +# With due homage to Mathsoft's site: +# http://www.mathsoft.com/asolve/constant/pi/pi.html + +# Set the global precision. Faster than passing it everywhichwhere. +my $precision = @ARGV>0?$ARGV[0]:10; + +# Set the iteration count. +my $maxIterations = @ARGV>1?$ARGV[1]:10; + +# Set the verbose debugging flag. +my $debugVerbose = 0; + +# Constants: +my $_1 = Math::BigFloat->new(1); +my $_2 = Math::BigFloat->new(2); +my $_3 = Math::BigFloat->new(3); +my $_4 = Math::BigFloat->new(4); +my $_6 = Math::BigFloat->new(6); +my $_8 = Math::BigFloat->new(8); +my $_239 = Math::BigFloat->new(239); +my $_half = Math::BigFloat->new(0.5); +my $_fifth = Math::BigFloat->new(0.2); +my $_25th = Math::BigFloat->new(0.04); +my $_239th = inv($_239); +my $_57121th = inv($_239*$_239); + + +# Utility methods: +sub div { + my $a = shift; + my $b = shift; + return new Math::BigFloat $a->copy()->fdiv($b,$precision); +} +sub inv { # Inverse (1/x) function. + my $a = shift; + return new Math::BigFloat $_1->copy()->fdiv($a,$precision); +} +sub root2 { + my $self = shift; + return new Math::BigFloat $self->copy()->fsqrt($precision); +} +sub root4 { + my $self = shift; + return root2(root2($self)); +} +sub pow4 { + my $self = shift; + my $square = round($self*$self); + return round($square*$square); +} +sub round { + my $self = shift; + return new Math::BigFloat $self->copy()->fround($precision); +} + + +# Method 1: + +# This gives Archimedes' approximation, +# 3+10/71 < Pi < 3+1/7 +# ...on the 4th iteration. + +sub BorchardtPfaff { + if (@_) { + my ($a,$b) = @{shift()}; # Retrieve the last iteration. + my $a_next = div( $_2*$a*$b, $a+$b ); + my $b_next = root2($a_next*$b); + return [ round($a_next), round($b_next) ]; + } else { # Seed the recurrence + return [ $_2*root2($_3), $_3 ]; + } +} + +# Method 2: + +# This uses Borwein's AGM method to compute Pi very quickly. +# The 'AGM' is short for the iterated arithmetic-geometric mean; +# which was looked at by Lagrange and Gauss way back in 1799. +# We basically look at the tuple [a,b] which holds the arithmetic +# and geometric means of the previous iteration: +# a[n+1] = (a[n] + b[n])/2 // Arithmetic mean +# b[n+1] = sqrt(a[n] * b[n]) // Geometric mean +# +# This algorithm is neat, since it is quadratically convergent - +# that means that the error goes as 2^(-iteration_count). +# +# In other words, one more step = twice the # of correct digits. + +sub BorweinAGM { + if (@_) { + my ($a,$b,$pi) = @{shift()}; # Retrieve the last iteration. + + my $sqrt_a = root2($a); + my $inv_sqrt_a = inv($sqrt_a); + my $b_plus_1 = $b+$_1; + + my $a_next = $_half * ($sqrt_a+$inv_sqrt_a); + my $b_next = div( $b*$sqrt_a+$inv_sqrt_a , $b_plus_1 ); + my $pi_next = $pi*div( $a_next+$_1 , $b_next+$_1 ); + return [ round($a_next), round($b_next), round($pi_next) ]; + + } else { # Seed the recurrence + my $a0 = root2($_2); + my $pi0 = $_2+root2($_2); + my $b1 = root2($a0); # = root4($_2) + my $a1 = $_half * ($b1 + inv($b1)); + + return [ round($a1), round($b1), round($pi0 * div($a1 + $_1, $b1 + $_1)) ]; + } +} + +# Method 3: + +# The arctangent approximation, as determined by Machin (1706). +# Pi = 4(4 * arctan(1/5) - arctan(1/239)), +# ...where arctan(x) = sum( (-1)^k/(2*k+1)*x^(2*k+1), x=0..infinity). + +sub ArctanPi { + if (@_) { + my ($k, $atan5, $atan239, $denom5, $denom239, $pi) = @{shift()}; # Retrieve the last iteration. + + $k++; + my $parity=$k & 1; + $denom5 = $denom5 * $_25th; + + my $inv_2_k_plus_1='Math::BigFloat'->new(2*$k+1); + + my $term5 = div($denom5, $inv_2_k_plus_1 ); + $denom239 = $denom239 * $_57121th; + + my $term239 = div($denom239, $inv_2_k_plus_1 ); + $atan5 = $parity ? $atan5 - $term5 : $atan5 + $term5; + $atan239 = $parity ? $atan239 - $term239 : $atan239 + $term239; + my $pi = $_4*($_4*$atan5 - $atan239); + + return [ $k, round($atan5), round($atan239), + round($denom5), round($denom239), round($pi) ]; + } else { # Seed the recurrence + my ($k, $atan5, $atan239) = (0, $_fifth, $_239th); + return [ $k, $atan5, $atan239, $atan5, $atan239, $_4*($_4*$atan5 - $atan239)]; + } +} + +# Method 4: + +# This uses Ramanujan's elliptic integral-based technique to +# compute Pi monstrously quickly. +# +# This algorithm is neat, since it is quartically convergent - +# that means that the error goes as 4^(-iteration_count). +# +# In other words, one more step = four times the # of correct digits. + +sub RamanujanEI { + if (@_) { + my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. + + my $z_4_term = root4($_1 - pow4($z)); + my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); + + my $z_next_plus_1 = $z_next + $_1; + + my $a_next = pow4($z_next_plus_1) * $a - + $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); + $a_next = round($a_next); + return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; + + } else { # Seed the recurrence + my $a = $_6-$_4*root2($_2); + return [ $a, root2($_2)-$_1, $_8, inv($a)]; + } +} + + + +###################################################################### +# +# Main routine: +# +# + +my $methods = ["BorchardtPfaff", "ArctanPi", "BorweinAGM", "RamanujanEI" ]; + +my $longestMethodLen=0; +foreach my $method (@{$methods}) { + $longestMethodLen = length($method) if length($method) > $longestMethodLen; +} + +my $pis = [ BorchardtPfaff(), ArctanPi(), BorweinAGM(), RamanujanEI() ]; + +for (my $i=0; $i<$maxIterations; $i++) { + print "Iteration $i:\n"; + if (!$debugVerbose) { + for (my $j=0; $j<@{$methods}; $j++) { + + # The following piece of line noise is equivalent to the + # STL C++, " + + # piValue = pis[j].last(); + + # ", if the declaration for pis is: + + # std::vector > pis; + # + + my $methodName = ${$methods}[$j]; + my $piValue = ${${$pis}[$j]}[-1]; + print ${$methods}[$j] . ": " . + ' ' x ($longestMethodLen - length($methodName)) . + $piValue . "\n"; + } + print "\n"; + } + print(Dumper($pis)) if $debugVerbose; + + last if $i+1 == $maxIterations; + + $pis = [ BorchardtPfaff(${$pis}[0]), + ArctanPi(${$pis}[1]), + BorweinAGM(${$pis}[2]), + RamanujanEI(${$pis}[3]) ]; +} + diff --git a/targets/znews-ss-prediction/system/webpages/www5/index.php b/targets/znews-ss-prediction/system/webpages/www5/index.php index 6c66bd469..b3b52ea5e 100644 --- a/targets/znews-ss-prediction/system/webpages/www5/index.php +++ b/targets/znews-ss-prediction/system/webpages/www5/index.php @@ -1,84 +1,84 @@ - 1 && time()%$content == 0) { - echo << - -Please come back... - - -I (the server) am swamped right now!!
-Please kindly come back in a couple of minutes.
-Sorry for the inconvenience, and thanks for understanding! - - -REJECT; - exit(); -} - -/* -$mysql_url = ''; -$mysql_user = ''; -$mysql_password = ''; -$mysql_db = ''; - -$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) - or die('Could not connect: ' . mysql_error()); - -$mydb = mysql_select_db($mysql_db, $link); -if(!$mydb) { - die('Could not select Test database: ' . mysql_error()); -} - -// Performing SQL query -$query = "SELECT COUNT(*) FROM cur"; -$result = mysql_query($query, $link) - or die('Query COUNT failed: ' . mysql_error()); -$row = mysql_fetch_row($result); -if ($row != false) { - $numItems = $row[0]; -} - -$idx = rand(1, $numItems); -$query = "SELECT cur_text FROM cur LIMIT $idx,1"; -$result = mysql_query($query, $link) - or die('Query item $idx failed: ' . mysql_error()); -$row = mysql_fetch_row($result); -if($row != false) { - $text = $row[0]; -} -*/ -$idx = 0; -$text = ""; - -echo << - -Somewhere Over the Rainbow - - - -

Z.com News - Hello World! (High-fidelity Settings)

-This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. - - - - -END - -?> + 1 && time()%$content == 0) { + echo << + +Please come back... + + +I (the server) am swamped right now!!
+Please kindly come back in a couple of minutes.
+Sorry for the inconvenience, and thanks for understanding! + + +REJECT; + exit(); +} + +/* +$mysql_url = ''; +$mysql_user = ''; +$mysql_password = ''; +$mysql_db = ''; + +$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) + or die('Could not connect: ' . mysql_error()); + +$mydb = mysql_select_db($mysql_db, $link); +if(!$mydb) { + die('Could not select Test database: ' . mysql_error()); +} + +// Performing SQL query +$query = "SELECT COUNT(*) FROM cur"; +$result = mysql_query($query, $link) + or die('Query COUNT failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if ($row != false) { + $numItems = $row[0]; +} + +$idx = rand(1, $numItems); +$query = "SELECT cur_text FROM cur LIMIT $idx,1"; +$result = mysql_query($query, $link) + or die('Query item $idx failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if($row != false) { + $text = $row[0]; +} +*/ +$idx = 0; +$text = ""; + +echo << + +Somewhere Over the Rainbow + + + +

Z.com News - Hello World! (High-fidelity Settings)

+This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. + + + + +END + +?> diff --git a/targets/znews-ss/log/topic/effectorBus.log b/targets/znews-ss/log/topic/effectorBus.log index a70dc671f..51df60945 100644 --- a/targets/znews-ss/log/topic/effectorBus.log +++ b/targets/znews-ss/log/topic/effectorBus.log @@ -1 +1 @@ -{location=10.0.2.15, name=blackhole, msg-created=1347630591011, action=EXECUTE, channel=topic/effectorBus, msg-sent=1347630591011, argument_size=1, argument_0=client=10.0.2.2} +{location=10.0.2.15, name=blackhole, msg-created=1347630591011, action=EXECUTE, channel=topic/effectorBus, msg-sent=1347630591011, argument_size=1, argument_0=client=10.0.2.2} diff --git a/targets/znews-ss/log/topic/gaugeBus.log b/targets/znews-ss/log/topic/gaugeBus.log index 92bf5ae39..90ece3525 100644 --- a/targets/znews-ss/log/topic/gaugeBus.log +++ b/targets/znews-ss/log/topic/gaugeBus.log @@ -1,191 +1,191 @@ -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiagnosisGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness::x, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=DG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=DiagnosisGaugeT} -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.End2EndRespTimeGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=end2endRespTime(delegate.oracle)::c0.experRespTime, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=EERTG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=ResponseTimeGaugeT} -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.EchoGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness(c1)::c0.maliciousness, setupParam_size=3, mapping_1=maliciousness(c2)::c1.maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357101, action=CREATE, gaugeName=EG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630357101, gaugeType=MaliciousnessGaugeT} -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.2, mapping_0=load::s0.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357102, action=CREATE, gaugeName=LoG0, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357102, gaugeType=LoadGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357187, action=REPORT_CREATED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630357187, gaugeType=DiagnosisGaugeT} -{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357189, action=REPORT_CREATED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630357189, gaugeType=ResponseTimeGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357191, action=REPORT_CREATED, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630357191, gaugeType=MaliciousnessGaugeT} -{uid=LoadGaugeT0914094557193@10.0.2.2, beaconPer=20000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357193, action=REPORT_CREATED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630357193, gaugeType=LoadGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630377197, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630377197} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630387192, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387192} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630387194, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387194} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630387196, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387196} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630397201, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630397201} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630417198, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417198} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630417200, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417200} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630417202, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417202} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630417205, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417205} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630437209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630437209} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630447204, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447204} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630447206, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447206} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630447209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447209} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=DiagnosisGaugeT} -{uid=LoadGaugeT0914094557193@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=LoadGaugeT} -{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454372, action=REPORT_CONFIGURED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630454372, gaugeType=ResponseTimeGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.ApacheTopGauge, mapping_6=reqServiceRate::s0.reqServiceRate, setupParam_2=beaconPeriod:long=20000, mapping_5=pageHit::s0.lastPageHit, setupParam_1=targetIP=10.0.2.15, mapping_4=numReqsSuccess::conn0.numReqsSuccess, mapping_0=byteServiceRate::s0.byteServiceRate, mapping_3=numReqsServerError::conn0.numReqsServerError, mapping_2=numReqsRedirect::conn0.numReqsRedirect, setupParam_size=3, mapping_1=numReqsClientError::conn0.numReqsClientError, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454668, action=CREATE, gaugeName=ATG1, mapping_size=7, channel=topic/gaugeBus, msg-sent=1347630454668, gaugeType=ApacheTopGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiskIOGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=readRate::s0.diskReadRate, mapping_2=writeRate::s0.diskWriteRate, setupParam_size=3, mapping_1=transferRate::s0.diskXferRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454669, action=CREATE, gaugeName=DioG1, mapping_size=3, channel=topic/gaugeBus, msg-sent=1347630454669, gaugeType=DiskIOGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.FidelityGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.15, mapping_0=fidelity::s0.fidelity, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=FiG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=FidelityGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latency(10.0.2.2)::conn0.latency, setupParam_size=3, mapping_1=latency(phoenix)::conn1.latency, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=LatG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=LatencyGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latencyRate(10.0.2.2)::conn0.latencyRate, setupParam_size=3, mapping_1=latencyRate(phoenix)::conn1.latencyRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454671, action=CREATE, gaugeName=LatRoCG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454671, gaugeType=LatencyRateGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=load::s1.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454672, action=CREATE, gaugeName=LoG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454672, gaugeType=LoadGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630457213, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630457213} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630459410, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630459410, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460095, action=CONFIGURE, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460095, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460154, action=REPORT_CONFIGURED, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460154, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464412, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630464412, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464467, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464467, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464471, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469414, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630469414, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469510, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469510, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469511, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469511, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474415, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630474415, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474420, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.10000000000000002, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474420, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474421, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474421, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630477215, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477215} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630477217, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477217} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630477223, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477223} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479417, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630479418, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479492, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479492, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479493, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630479518, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630479518} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484419, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630484419, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484508, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484508, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484509, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484509, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489421, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630489421, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494423, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630494423, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494437, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494437, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494438, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494438, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630497221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630497221} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499425, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630499425, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499449, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499449, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499450, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499450, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504427, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630504427, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504459, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504460, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504460, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630507221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507221} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630507229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507229} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509429, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630509429, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509470, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509471, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630509530, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630509530} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514430, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630514431, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514481, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514482, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630517225, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630517225} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519433, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630519433, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524435, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630524435, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524504, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524505, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524505, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529437, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630529437, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534438, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630534438, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630537227, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537227} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630537229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537229} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630537235, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537235} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539441, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630539441, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630539542, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630539542} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544443, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630544443, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544547, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544548, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544548, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549446, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630549446, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554448, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630554449, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554470, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554471, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630557233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630557233} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559451, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630559451, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564453, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630564453, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630567233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567233} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630567241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567241} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569456, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630569456, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630569557, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630569557} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574458, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630574458, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574516, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574516, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574517, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574517, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630577237, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630577237} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579460, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630579460, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584463, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630584463, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589465, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630589465, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630594467, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630594467, value_size=2, gaugeType=DiagnosisGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630597239, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597239} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630597241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597241} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630597247, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597247} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599469, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630599469, value_size=2, gaugeType=DiagnosisGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630599570, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630599570} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604470, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630604470, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609473, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630609473, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614475, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630614475, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614481, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614482, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630617245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630617245} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619477, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630619477, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619493, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619494, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619494, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624478, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630624478, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630627245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627245} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630627253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627253} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629481, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630629481, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629511, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629511, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629512, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629512, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630629581, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630629581} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634483, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630634483, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634520, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634520, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634521, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634521, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630637249, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630637249} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639485, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630639485, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639530, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639530, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639531, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639531, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644487, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630644487, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649490, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630649490, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649547, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649548, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654492, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630654492, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630657251, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657251} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630657253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657253} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630657259, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657259} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659495, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630659495, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659564, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659565, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659565, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630659596, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630659596} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665048, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630665048, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670050, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630670050, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiagnosisGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness::x, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=DG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=DiagnosisGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.End2EndRespTimeGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=end2endRespTime(delegate.oracle)::c0.experRespTime, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=EERTG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=ResponseTimeGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.EchoGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness(c1)::c0.maliciousness, setupParam_size=3, mapping_1=maliciousness(c2)::c1.maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357101, action=CREATE, gaugeName=EG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630357101, gaugeType=MaliciousnessGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.2, mapping_0=load::s0.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357102, action=CREATE, gaugeName=LoG0, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357102, gaugeType=LoadGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357187, action=REPORT_CREATED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630357187, gaugeType=DiagnosisGaugeT} +{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357189, action=REPORT_CREATED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630357189, gaugeType=ResponseTimeGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357191, action=REPORT_CREATED, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630357191, gaugeType=MaliciousnessGaugeT} +{uid=LoadGaugeT0914094557193@10.0.2.2, beaconPer=20000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357193, action=REPORT_CREATED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630357193, gaugeType=LoadGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630377197, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630377197} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630387192, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387192} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630387194, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387194} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630387196, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387196} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630397201, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630397201} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630417198, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417198} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630417200, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417200} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630417202, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417202} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630417205, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417205} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630437209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630437209} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630447204, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447204} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630447206, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447206} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630447209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447209} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=DiagnosisGaugeT} +{uid=LoadGaugeT0914094557193@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=LoadGaugeT} +{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454372, action=REPORT_CONFIGURED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630454372, gaugeType=ResponseTimeGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.ApacheTopGauge, mapping_6=reqServiceRate::s0.reqServiceRate, setupParam_2=beaconPeriod:long=20000, mapping_5=pageHit::s0.lastPageHit, setupParam_1=targetIP=10.0.2.15, mapping_4=numReqsSuccess::conn0.numReqsSuccess, mapping_0=byteServiceRate::s0.byteServiceRate, mapping_3=numReqsServerError::conn0.numReqsServerError, mapping_2=numReqsRedirect::conn0.numReqsRedirect, setupParam_size=3, mapping_1=numReqsClientError::conn0.numReqsClientError, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454668, action=CREATE, gaugeName=ATG1, mapping_size=7, channel=topic/gaugeBus, msg-sent=1347630454668, gaugeType=ApacheTopGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiskIOGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=readRate::s0.diskReadRate, mapping_2=writeRate::s0.diskWriteRate, setupParam_size=3, mapping_1=transferRate::s0.diskXferRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454669, action=CREATE, gaugeName=DioG1, mapping_size=3, channel=topic/gaugeBus, msg-sent=1347630454669, gaugeType=DiskIOGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.FidelityGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.15, mapping_0=fidelity::s0.fidelity, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=FiG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=FidelityGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latency(10.0.2.2)::conn0.latency, setupParam_size=3, mapping_1=latency(phoenix)::conn1.latency, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=LatG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=LatencyGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latencyRate(10.0.2.2)::conn0.latencyRate, setupParam_size=3, mapping_1=latencyRate(phoenix)::conn1.latencyRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454671, action=CREATE, gaugeName=LatRoCG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454671, gaugeType=LatencyRateGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=load::s1.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454672, action=CREATE, gaugeName=LoG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454672, gaugeType=LoadGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630457213, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630457213} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630459410, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630459410, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460095, action=CONFIGURE, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460095, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460154, action=REPORT_CONFIGURED, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460154, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464412, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630464412, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464467, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464467, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464471, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469414, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630469414, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469510, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469510, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469511, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469511, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474415, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630474415, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474420, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.10000000000000002, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474420, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474421, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474421, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630477215, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477215} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630477217, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477217} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630477223, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477223} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479417, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630479418, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479492, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479492, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479493, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630479518, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630479518} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484419, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630484419, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484508, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484508, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484509, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484509, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489421, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630489421, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494423, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630494423, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494437, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494437, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494438, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494438, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630497221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630497221} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499425, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630499425, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499449, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499449, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499450, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499450, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504427, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630504427, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504459, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504460, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504460, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630507221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507221} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630507229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507229} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509429, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630509429, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509470, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509471, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630509530, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630509530} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514430, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630514431, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514481, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514482, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630517225, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630517225} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519433, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630519433, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524435, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630524435, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524504, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524505, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524505, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529437, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630529437, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534438, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630534438, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630537227, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537227} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630537229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537229} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630537235, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537235} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539441, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630539441, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630539542, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630539542} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544443, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630544443, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544547, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544548, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544548, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549446, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630549446, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554448, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630554449, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554470, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554471, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630557233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630557233} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559451, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630559451, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564453, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630564453, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630567233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567233} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630567241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567241} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569456, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630569456, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630569557, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630569557} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574458, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630574458, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574516, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574516, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574517, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574517, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630577237, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630577237} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579460, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630579460, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584463, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630584463, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589465, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630589465, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630594467, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630594467, value_size=2, gaugeType=DiagnosisGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630597239, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597239} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630597241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597241} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630597247, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597247} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599469, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630599469, value_size=2, gaugeType=DiagnosisGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630599570, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630599570} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604470, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630604470, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609473, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630609473, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614475, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630614475, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614481, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614482, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630617245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630617245} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619477, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630619477, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619493, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619494, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619494, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624478, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630624478, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630627245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627245} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630627253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627253} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629481, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630629481, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629511, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629511, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629512, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629512, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630629581, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630629581} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634483, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630634483, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634520, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634520, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634521, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634521, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630637249, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630637249} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639485, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630639485, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639530, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639530, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639531, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639531, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644487, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630644487, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649490, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630649490, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649547, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649548, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654492, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630654492, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630657251, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657251} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630657253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657253} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630657259, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657259} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659495, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630659495, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659564, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659565, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659565, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630659596, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630659596} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665048, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630665048, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670050, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630670050, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} diff --git a/targets/znews-ss/log/topic/rainbowHealth.log b/targets/znews-ss/log/topic/rainbowHealth.log index 33931f7a8..23bde129f 100644 --- a/targets/znews-ss/log/topic/rainbowHealth.log +++ b/targets/znews-ss/log/topic/rainbowHealth.log @@ -1,102 +1,102 @@ -{msg-created=1347630325763, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325773, txt=EventServiceManager initialized!} -{msg-created=1347630325789, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325789, txt=T[topic/rainbowHealth] +listener Oracle@10.0.2.2} -{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/rainbowHealth] +listener SystemDelegate@10.0.2.2} -{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/effectorBus] +listener SystemDelegate@10.0.2.2} -{msg-created=1347630351995, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351995, txt=T[topic/gaugeBus] +listener GaugeCoordinator@10.0.2.2} -{msg-created=1347630351996, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351996, txt=T[topic/rainbowHealth] +listener ModelManager@10.0.2.2} -{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/rainbowHealth] +listener del1} -{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/effectorBus] +listener del1} -{msg-created=1347630352014, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352014, txt=T[topic/gaugeBus] +listener ApacheTopGaugeT@10.0.2.2} -{msg-created=1347630352018, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352018, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT@10.0.2.2} -{msg-created=1347630352020, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352020, txt=T[topic/gaugeBus] +listener DiskIOGaugeT@10.0.2.2} -{msg-created=1347630352021, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352021, txt=T[topic/gaugeBus] +listener FidelityGaugeT@10.0.2.2} -{msg-created=1347630352022, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352022, txt=T[topic/gaugeBus] +listener LatencyGaugeT@10.0.2.2} -{msg-created=1347630352024, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352024, txt=T[topic/gaugeBus] +listener LatencyRateGaugeT@10.0.2.2} -{msg-created=1347630352025, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352025, txt=T[topic/gaugeBus] +listener LoadGaugeT@10.0.2.2} -{msg-created=1347630352026, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352026, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT@10.0.2.2} -{msg-created=1347630352031, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352031, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT@10.0.2.2} -{beaconPer=5000, id=del1, location=10.0.2.2, cloudT=DELEGATE, msg-created=1347630357039, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630357039} -{id=del1, location=10.0.2.2, msg-created=1347630357099, action=START, channel=topic/rainbowHealth, msg-sent=1347630357099} -{msg-created=1347630357187, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357187, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT0914094557185@10.0.2.2} -{msg-created=1347630357188, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357188, txt=G[DiagnosisGaugeT0914094557185@10.0.2.2] G - Diagnosis started.} -{msg-created=1347630357189, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357189, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} -{msg-created=1347630357190, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=T[topic/probeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} -{msg-created=1347630357190, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=G[ResponseTimeGaugeT0914094557188@10.0.2.2] G - End-End Resp Time started.} -{msg-created=1347630357191, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357191, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} -{msg-created=1347630357192, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} -{msg-created=1347630357192, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=G[MaliciousnessGaugeT0914094557191@10.0.2.2] G - Maliciousness started.} -{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/gaugeBus] +listener LoadGaugeT0914094557193@10.0.2.2} -{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/probeBus] +listener LoadGaugeT0914094557193@10.0.2.2} -{msg-created=1347630357193, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357194, txt=G[LoadGaugeT0914094557193@10.0.2.2] G - CPU Load started.} -{id=del1, msg-created=1347630362096, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630362096} -{id=del1, msg-created=1347630367196, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630367196} -{id=del1, msg-created=1347630372296, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630372296} -{id=del1, msg-created=1347630377297, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630377297} -{id=del1, msg-created=1347630382298, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630382298} -{id=del1, msg-created=1347630387299, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630387299} -{id=del1, msg-created=1347630392300, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630392300} -{id=del1, msg-created=1347630397301, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630397301} -{id=del1, msg-created=1347630402302, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630402302} -{id=del1, msg-created=1347630407303, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630407303} -{id=del1, msg-created=1347630412304, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630412304} -{id=del1, msg-created=1347630417305, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630417305} -{id=del1, msg-created=1347630422306, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630422306} -{id=del1, msg-created=1347630427307, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630427307} -{id=del1, msg-created=1347630432308, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630432308} -{id=del1, msg-created=1347630437309, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630437309} -{id=del1, msg-created=1347630442310, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630442310} -{id=del1, msg-created=1347630447311, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630447311} -{id=del1, msg-created=1347630452312, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630452312} -{location=10.0.2.2, msg-created=1347630454176, action=START_PROBES, channel=topic/rainbowHealth, msg-sent=1347630454176} -{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/rainbowHealth] +listener ProbeBusRelay@10.0.2.2} -{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/probeBus] +listener ProbeBusRelay@10.0.2.2} -{beaconPer=0, id=ProbeBusRelay@10.0.2.2, location=10.0.2.2, cloudT=PB_RELAY, msg-created=1347630454321, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630454321} -{msg-created=1347630454322, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454322, txt=[PBR] Rainbow Runtime - Probe Bus Relay started.} -{msg-created=1347630454370, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454370, txt=[PBR] IProbe ClientProxyProbe0@10.0.2.2:clientproxy added!} -{beaconPer=0, id=ClientProxyProbe0@10.0.2.2, probeK=JAVA, alias=clientproxy, location=10.0.2.2, cloudT=PROBE, msg-created=1347630454370, action=REPORT_CREATED, svcName=ClientProxyProbe0, channel=topic/rainbowHealth, msg-sent=1347630454370} -{id=del1, location=10.0.2.15, msg-created=1347630454667, action=START, channel=topic/rainbowHealth, msg-sent=1347630454667} -{id=del1, msg-created=1347630457373, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630457373} -{id=del1, location=10.0.2.15, msg-created=1347630459775, action=START, channel=topic/rainbowHealth, msg-sent=1347630459775} -{id=del1, msg-created=1347630462374, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630462374} -{id=del1, msg-created=1347630467375, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630467375} -{id=del1, msg-created=1347630472376, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630472376} -{id=del1, msg-created=1347630477377, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630477377} -{id=del1, msg-created=1347630482378, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630482378} -{id=del1, msg-created=1347630487379, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630487379} -{id=del1, msg-created=1347630492380, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630492380} -{id=del1, msg-created=1347630497381, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630497381} -{id=del1, msg-created=1347630502382, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630502382} -{id=del1, msg-created=1347630507383, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630507383} -{id=del1, msg-created=1347630512384, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630512384} -{id=del1, msg-created=1347630517385, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630517385} -{id=del1, msg-created=1347630522386, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630522386} -{id=del1, msg-created=1347630527387, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630527387} -{id=del1, msg-created=1347630532388, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630532388} -{id=del1, msg-created=1347630537389, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630537389} -{id=del1, msg-created=1347630542390, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630542390} -{id=del1, msg-created=1347630547391, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630547391} -{id=del1, msg-created=1347630552392, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630552392} -{id=del1, msg-created=1347630557393, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630557393} -{id=del1, msg-created=1347630562394, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630562394} -{id=del1, msg-created=1347630567395, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630567395} -{id=del1, msg-created=1347630572396, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630572396} -{id=del1, msg-created=1347630577397, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630577397} -{id=del1, msg-created=1347630582398, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630582398} -{id=del1, msg-created=1347630587399, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630587399} -{id=del1, msg-created=1347630592400, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630592400} -{id=del1, msg-created=1347630597401, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630597401} -{id=del1, msg-created=1347630602402, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630602402} -{id=del1, msg-created=1347630607403, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630607403} -{id=del1, msg-created=1347630612404, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630612404} -{id=del1, msg-created=1347630617405, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630617405} -{id=del1, msg-created=1347630622406, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630622406} -{id=del1, msg-created=1347630627407, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630627407} -{id=del1, msg-created=1347630632408, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630632408} -{id=del1, msg-created=1347630637409, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630637409} -{id=del1, msg-created=1347630642410, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630642410} -{id=del1, msg-created=1347630647411, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630647411} -{id=del1, msg-created=1347630652412, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630652412} -{id=del1, msg-created=1347630657413, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630657413} -{id=del1, msg-created=1347630662414, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630662414} -{id=del1, msg-created=1347630667415, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630667415} -{id=del1, msg-created=1347630672416, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630672416} +{msg-created=1347630325763, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325773, txt=EventServiceManager initialized!} +{msg-created=1347630325789, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325789, txt=T[topic/rainbowHealth] +listener Oracle@10.0.2.2} +{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/rainbowHealth] +listener SystemDelegate@10.0.2.2} +{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/effectorBus] +listener SystemDelegate@10.0.2.2} +{msg-created=1347630351995, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351995, txt=T[topic/gaugeBus] +listener GaugeCoordinator@10.0.2.2} +{msg-created=1347630351996, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351996, txt=T[topic/rainbowHealth] +listener ModelManager@10.0.2.2} +{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/rainbowHealth] +listener del1} +{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/effectorBus] +listener del1} +{msg-created=1347630352014, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352014, txt=T[topic/gaugeBus] +listener ApacheTopGaugeT@10.0.2.2} +{msg-created=1347630352018, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352018, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT@10.0.2.2} +{msg-created=1347630352020, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352020, txt=T[topic/gaugeBus] +listener DiskIOGaugeT@10.0.2.2} +{msg-created=1347630352021, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352021, txt=T[topic/gaugeBus] +listener FidelityGaugeT@10.0.2.2} +{msg-created=1347630352022, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352022, txt=T[topic/gaugeBus] +listener LatencyGaugeT@10.0.2.2} +{msg-created=1347630352024, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352024, txt=T[topic/gaugeBus] +listener LatencyRateGaugeT@10.0.2.2} +{msg-created=1347630352025, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352025, txt=T[topic/gaugeBus] +listener LoadGaugeT@10.0.2.2} +{msg-created=1347630352026, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352026, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT@10.0.2.2} +{msg-created=1347630352031, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352031, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT@10.0.2.2} +{beaconPer=5000, id=del1, location=10.0.2.2, cloudT=DELEGATE, msg-created=1347630357039, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630357039} +{id=del1, location=10.0.2.2, msg-created=1347630357099, action=START, channel=topic/rainbowHealth, msg-sent=1347630357099} +{msg-created=1347630357187, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357187, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT0914094557185@10.0.2.2} +{msg-created=1347630357188, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357188, txt=G[DiagnosisGaugeT0914094557185@10.0.2.2] G - Diagnosis started.} +{msg-created=1347630357189, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357189, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} +{msg-created=1347630357190, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=T[topic/probeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} +{msg-created=1347630357190, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=G[ResponseTimeGaugeT0914094557188@10.0.2.2] G - End-End Resp Time started.} +{msg-created=1347630357191, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357191, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} +{msg-created=1347630357192, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} +{msg-created=1347630357192, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=G[MaliciousnessGaugeT0914094557191@10.0.2.2] G - Maliciousness started.} +{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/gaugeBus] +listener LoadGaugeT0914094557193@10.0.2.2} +{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/probeBus] +listener LoadGaugeT0914094557193@10.0.2.2} +{msg-created=1347630357193, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357194, txt=G[LoadGaugeT0914094557193@10.0.2.2] G - CPU Load started.} +{id=del1, msg-created=1347630362096, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630362096} +{id=del1, msg-created=1347630367196, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630367196} +{id=del1, msg-created=1347630372296, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630372296} +{id=del1, msg-created=1347630377297, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630377297} +{id=del1, msg-created=1347630382298, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630382298} +{id=del1, msg-created=1347630387299, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630387299} +{id=del1, msg-created=1347630392300, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630392300} +{id=del1, msg-created=1347630397301, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630397301} +{id=del1, msg-created=1347630402302, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630402302} +{id=del1, msg-created=1347630407303, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630407303} +{id=del1, msg-created=1347630412304, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630412304} +{id=del1, msg-created=1347630417305, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630417305} +{id=del1, msg-created=1347630422306, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630422306} +{id=del1, msg-created=1347630427307, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630427307} +{id=del1, msg-created=1347630432308, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630432308} +{id=del1, msg-created=1347630437309, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630437309} +{id=del1, msg-created=1347630442310, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630442310} +{id=del1, msg-created=1347630447311, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630447311} +{id=del1, msg-created=1347630452312, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630452312} +{location=10.0.2.2, msg-created=1347630454176, action=START_PROBES, channel=topic/rainbowHealth, msg-sent=1347630454176} +{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/rainbowHealth] +listener ProbeBusRelay@10.0.2.2} +{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/probeBus] +listener ProbeBusRelay@10.0.2.2} +{beaconPer=0, id=ProbeBusRelay@10.0.2.2, location=10.0.2.2, cloudT=PB_RELAY, msg-created=1347630454321, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630454321} +{msg-created=1347630454322, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454322, txt=[PBR] Rainbow Runtime - Probe Bus Relay started.} +{msg-created=1347630454370, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454370, txt=[PBR] IProbe ClientProxyProbe0@10.0.2.2:clientproxy added!} +{beaconPer=0, id=ClientProxyProbe0@10.0.2.2, probeK=JAVA, alias=clientproxy, location=10.0.2.2, cloudT=PROBE, msg-created=1347630454370, action=REPORT_CREATED, svcName=ClientProxyProbe0, channel=topic/rainbowHealth, msg-sent=1347630454370} +{id=del1, location=10.0.2.15, msg-created=1347630454667, action=START, channel=topic/rainbowHealth, msg-sent=1347630454667} +{id=del1, msg-created=1347630457373, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630457373} +{id=del1, location=10.0.2.15, msg-created=1347630459775, action=START, channel=topic/rainbowHealth, msg-sent=1347630459775} +{id=del1, msg-created=1347630462374, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630462374} +{id=del1, msg-created=1347630467375, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630467375} +{id=del1, msg-created=1347630472376, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630472376} +{id=del1, msg-created=1347630477377, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630477377} +{id=del1, msg-created=1347630482378, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630482378} +{id=del1, msg-created=1347630487379, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630487379} +{id=del1, msg-created=1347630492380, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630492380} +{id=del1, msg-created=1347630497381, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630497381} +{id=del1, msg-created=1347630502382, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630502382} +{id=del1, msg-created=1347630507383, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630507383} +{id=del1, msg-created=1347630512384, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630512384} +{id=del1, msg-created=1347630517385, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630517385} +{id=del1, msg-created=1347630522386, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630522386} +{id=del1, msg-created=1347630527387, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630527387} +{id=del1, msg-created=1347630532388, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630532388} +{id=del1, msg-created=1347630537389, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630537389} +{id=del1, msg-created=1347630542390, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630542390} +{id=del1, msg-created=1347630547391, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630547391} +{id=del1, msg-created=1347630552392, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630552392} +{id=del1, msg-created=1347630557393, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630557393} +{id=del1, msg-created=1347630562394, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630562394} +{id=del1, msg-created=1347630567395, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630567395} +{id=del1, msg-created=1347630572396, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630572396} +{id=del1, msg-created=1347630577397, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630577397} +{id=del1, msg-created=1347630582398, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630582398} +{id=del1, msg-created=1347630587399, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630587399} +{id=del1, msg-created=1347630592400, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630592400} +{id=del1, msg-created=1347630597401, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630597401} +{id=del1, msg-created=1347630602402, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630602402} +{id=del1, msg-created=1347630607403, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630607403} +{id=del1, msg-created=1347630612404, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630612404} +{id=del1, msg-created=1347630617405, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630617405} +{id=del1, msg-created=1347630622406, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630622406} +{id=del1, msg-created=1347630627407, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630627407} +{id=del1, msg-created=1347630632408, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630632408} +{id=del1, msg-created=1347630637409, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630637409} +{id=del1, msg-created=1347630642410, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630642410} +{id=del1, msg-created=1347630647411, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630647411} +{id=del1, msg-created=1347630652412, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630652412} +{id=del1, msg-created=1347630657413, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630657413} +{id=del1, msg-created=1347630662414, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630662414} +{id=del1, msg-created=1347630667415, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630667415} +{id=del1, msg-created=1347630672416, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630672416} diff --git a/targets/znews-ss/model/DoSFam.acme b/targets/znews-ss/model/DoSFam.acme index 517612eea..2e54d6974 100644 --- a/targets/znews-ss/model/DoSFam.acme +++ b/targets/znews-ss/model/DoSFam.acme @@ -1,46 +1,46 @@ -Family DoSFam = { - - Element Type PotentiallyMaliciousT = { - - Property deploymentLocation : string; - - Property maliciousness : float << default : float = 0.0; >> ; - - } - - Element Type MaliciousT extends PotentiallyMaliciousT with { - rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; - } - - Element Type SuspiciousT extends PotentiallyMaliciousT with { - rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD && maliciousness <= MALICIOUS_THRESHOLD; - } - - Element Type NormalT extends PotentiallyMaliciousT with { - rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; - - Element Type BlackholerT = { - - Property blackholed : Set {string} << default : Set {string} = {}; >> ; - - } - Port Type BlackholedPortT = { - - Property isBlackholed : boolean = true; - - } - - Port Type CaptchaPortT = { - Property captchaEnabled : boolean << default : boolean = false;>>; - } - - Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; - Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; - rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | - exists bh : BlackholerT in self.COMPONENTS | - contains(c.deploymentLocation, bh.blackholed); - rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.components | - forall ip : string in lb.blackholed | - forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | - c.maliciousness > self.MALICIOUS_THRESHOLD; +Family DoSFam = { + + Element Type PotentiallyMaliciousT = { + + Property deploymentLocation : string; + + Property maliciousness : float << default : float = 0.0; >> ; + + } + + Element Type MaliciousT extends PotentiallyMaliciousT with { + rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; + } + + Element Type SuspiciousT extends PotentiallyMaliciousT with { + rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD && maliciousness <= MALICIOUS_THRESHOLD; + } + + Element Type NormalT extends PotentiallyMaliciousT with { + rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; + + Element Type BlackholerT = { + + Property blackholed : Set {string} << default : Set {string} = {}; >> ; + + } + Port Type BlackholedPortT = { + + Property isBlackholed : boolean = true; + + } + + Port Type CaptchaPortT = { + Property captchaEnabled : boolean << default : boolean = false;>>; + } + + Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; + Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; + rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | + exists bh : BlackholerT in self.COMPONENTS | + contains(c.deploymentLocation, bh.blackholed); + rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.components | + forall ip : string in lb.blackholed | + forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | + c.maliciousness > self.MALICIOUS_THRESHOLD; } \ No newline at end of file diff --git a/targets/znews-ss/model/TargetEnv.acme b/targets/znews-ss/model/TargetEnv.acme index 4331c55b7..2ec6be259 100644 --- a/targets/znews-ss/model/TargetEnv.acme +++ b/targets/znews-ss/model/TargetEnv.acme @@ -1,4 +1,4 @@ -System TargetEnv = { - -} - +System TargetEnv = { + +} + diff --git a/targets/znews-ss/model/TargetEnvType.acme b/targets/znews-ss/model/TargetEnvType.acme index a91a99173..91e499a0e 100644 --- a/targets/znews-ss/model/TargetEnvType.acme +++ b/targets/znews-ss/model/TargetEnvType.acme @@ -1,67 +1,67 @@ -Family EnvType = { - - Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; - - Role Type ArchRoleT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type PartPortT = { - - } - Component Type ArchElementT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type NetworkRoleT = { - - } - Connector Type MappingT = { - - } - Role Type PartRoleT = { - - } - Connector Type EdgeT = { - - Property bandwidthAvg : ResourceStatePropT; - - Property capacity : ResourceStatePropT; - - } - Component Type NodeT = { - - Property cpuOverall : ResourceStatePropT; - - Property memoryMain : ResourceStatePropT; - - Property storageLocal : ResourceStatePropT; - - Property socketPool : ResourceStatePropT; - - Property batteryOverall : ResourceStatePropT; - - } - Port Type NetworkPortT = { - - } - Connector Type ArchConnT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type ArchPortT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type ContainerRoleT = { - - } - Port Type ContainmentPortT = { - - } -} - +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type PartPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type NetworkRoleT = { + + } + Connector Type MappingT = { + + } + Role Type PartRoleT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Port Type NetworkPortT = { + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type ContainerRoleT = { + + } + Port Type ContainmentPortT = { + + } +} + diff --git a/targets/znews-ss/model/TargetEnvType.mtd b/targets/znews-ss/model/TargetEnvType.mtd index 6817ebfa8..9d8d87f85 100644 --- a/targets/znews-ss/model/TargetEnvType.mtd +++ b/targets/znews-ss/model/TargetEnvType.mtd @@ -1,475 +1,475 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews-ss/model/ZNewsSys.acme b/targets/znews-ss/model/ZNewsSys.acme index 91fe005e2..a6ac63fff 100644 --- a/targets/znews-ss/model/ZNewsSys.acme +++ b/targets/znews-ss/model/ZNewsSys.acme @@ -1,612 +1,612 @@ -Family EnvType = { - - Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; - Port Type PartPortT = { - - } - Port Type NetworkPortT = { - - } - Port Type ArchPortT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } - Port Type ContainmentPortT = { - - } - Component Type ArchElementT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } - Component Type NodeT = { - - Property cpuOverall : ResourceStatePropT; - - Property memoryMain : ResourceStatePropT; - - Property storageLocal : ResourceStatePropT; - - Property socketPool : ResourceStatePropT; - - Property batteryOverall : ResourceStatePropT; - - } - Role Type ArchRoleT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } - Role Type NetworkRoleT = { - - } - Role Type PartRoleT = { - - } - Role Type ContainerRoleT = { - - } - Connector Type MappingT = { - - } - Connector Type EdgeT = { - - Property bandwidthAvg : ResourceStatePropT; - - Property capacity : ResourceStatePropT; - - } - Connector Type ArchConnT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } -} - -Family ZNewsFam extends EnvType with { - - Port Type HttpPortT extends ArchPortT with { - - } - Port Type ProxyForwardPortT extends ArchPortT with { - - } - Port Type HttpReqPortT extends ArchPortT with { - - } - Port Type SqlReqPort extends ArchPortT with { - - } - Port Type SqlRecPort extends ArchPortT with { - - } - Component Type ProxyT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - } - Component Type ServerT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - Property reqServiceRate : float << default : float = 0.0; >> ; - - Property byteServiceRate : float << default : float = 0.0; >> ; - - Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; - - Property cost : float << default : float = 1.0; >> ; - - Property lastPageHit : Record [uri : string; cnt : int; kbytes : float; ]; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - Component Type ClientT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property experRespTime : float << default : float = 0.0; >> ; - - Property reqRate : float << default : float = 0.0; >> ; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - Component Type DBT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "locahost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - } - Role Type ReceiverRoleT extends ArchRoleT with { - - } - Role Type RequestorRoleT extends ArchRoleT with { - - } - Connector Type ProxyConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - Connector Type SQLConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - Connector Type HttpConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - Property bandwidth : float << default : float = 0.0; >> ; - - Property latency : float << default : float = 0.0; >> ; - - Property numReqsSuccess : int << default : int = 0; >> ; - - Property numReqsRedirect : int << default : int = 0; >> ; - - Property numReqsClientError : int << default : int = 0; >> ; - - Property numReqsServerError : int << default : int = 0; >> ; - - Property latencyRate : float; - - } - - Property MIN_RESPTIME : float; - - Property MAX_RESPTIME : float << default : float = 2; >> ; - - Property TOLERABLE_PERCENT_UNHAPPY : float; - - Property UNHAPPY_GRADIENT_1 : float; - - Property UNHAPPY_GRADIENT_2 : float; - - Property UNHAPPY_GRADIENT_3 : float; - - Property FRACTION_GRADIENT_1 : float; - - Property FRACTION_GRADIENT_2 : float; - - Property FRACTION_GRADIENT_3 : float; - - Property MIN_UTIL : float; - - Property MAX_UTIL : float << default : float = 1; >> ; - - Property MAX_FIDELITY_LEVEL : int; - - Property THRESHOLD_FIDELITY : int; - - Property THRESHOLD_COST : float; -} - -Family DoSFam = { - - Element Type PotentiallyMaliciousT = { - - Property deploymentLocation : string; - - Property maliciousness : float << default : float = 0.0; >> ; - - } - Element Type MaliciousT extends PotentiallyMaliciousT with { - rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; - - } - Element Type SuspiciousT extends PotentiallyMaliciousT with { - rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD AND maliciousness <= MALICIOUS_THRESHOLD; - - } - Element Type NormalT extends PotentiallyMaliciousT with { - rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; - - } - Element Type BlackholerT = { - - Property blackholed : Set {string} << default : Set {string} = {}; >> ; - - } - Element Type CaptchaRedirectT = { - - Property captchaEnabled : boolean << default : boolean = false; >> ; - - } - Element Type ThrottlerT = { - - Property throttled : Set {string} << default : Set {string} = {}; >> ; - - } - Element Type CaptchaHandlerT = { - - Property captcha : int << default : int = 0; >> ; - - } - Element Type AuthenticationHandlerT = { - - Property authenticate : int << default : int = 0; >> ; - - } - Port Type BlackholedPortT = { - - Property isBlackholed : boolean = true; - - } - - Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; - - Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; - rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | - exists bh : BlackholerT in self.COMPONENTS | - contains(c.deploymentLocation, bh.blackholed); - rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | - forall ip : string in lb.blackholed | - forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | - c.maliciousness > self.MALICIOUS_THRESHOLD; -} - -Family ZNewsDosFam extends ZNewsFam, DoSFam with { - - Component Type ZNewsClientT extends ClientT, PotentiallyMaliciousT, CaptchaHandlerT, AuthenticationHandlerT with { - - } - Component Type ZNewsLBT extends ProxyT, CaptchaRedirectT, BlackholerT, ThrottlerT with { - - } -} - -System ZNewsSys : ZNewsDosFam = new ZNewsDosFam extended with { - - Component Server0 : ArchElementT, ServerT = new ArchElementT, ServerT extended with { - Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { - - Property isArchEnabled = true; - - } - Port sql0 : SqlReqPort = new SqlReqPort extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.web0}"; - Property httpPort : string = "${customize.system.target.web0.httpPort}"; - - Property load = 0.0; - - Property reqServiceRate = 0.0; - - Property byteServiceRate = 0.0; - - Property fidelity = 5; - - Property cost = 1.0; - - Property isArchEnabled = true; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - - Component Server1 : ServerT = new ServerT extended with { - Port p : HttpPortT = new HttpPortT extended with { - - } - Port p0 : SqlReqPort = new SqlReqPort extended with { - - } - Property deploymentLocation = "${customize.system.target.web1}"; - Property httpPort : string = "${customize.system.target.web1.httpPort}"; - - Property load = 0.0; - - Property reqServiceRate = 0.0; - - Property byteServiceRate = 0.0; - - Property fidelity = 5; - - Property cost = 1.0; - - Property isArchEnabled = true; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - - Component ServerB0 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { - - Property isArchEnabled = false; - - } - Port sql0 : SqlReqPort = new SqlReqPort extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.web2}"; - Property httpPort : string = "${customize.system.target.web2.httpPort}"; - - Property load = 0.0; - - Property reqServiceRate = 0.0; - - Property byteServiceRate = 0.0; - - Property fidelity = 5; - - Property cost = 1.0; - - Property isArchEnabled = false; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - Component LB0 : ZNewsLBT = new ZNewsLBT extended with { - Port http0 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - Port http1 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - Property captchaEnabled = false; - - } - Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - Property isArchEnabled = true; - - } - Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - Property isArchEnabled = false; - - } - Port p : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - - Property deploymentLocation = "${customize.system.target.lb}"; - - Property load = 0.0; - - Property isArchEnabled = true; - - Property blackholed = {}; - - Property captchaEnabled = false; - - Property throttled = {}; - - } - Component DB0 : DBT = new DBT extended with { - Port rec0 : SqlRecPort = new SqlRecPort extended with { - - Property isArchEnabled = true; - - } - Port rec1 : SqlRecPort = new SqlRecPort extended with { - - Property isArchEnabled = true; - - } - Port p : SqlRecPort = new SqlRecPort extended with { - - } - - Property deploymentLocation = "${customize.system.target.db}"; - - Property load = 0.0; - - Property isArchEnabled = true; - - } - Component Client0 : ZNewsClientT = new ZNewsClientT extended with { - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.client1}"; - - Property experRespTime = 0; - - Property reqRate = 0.0; - - Property isArchEnabled = true; - - Property maliciousness = 0.0; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - Component Client1 : ZNewsClientT = new ZNewsClientT extended with { - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.client2}"; - - Property experRespTime = 0.0; - - Property reqRate = 0.0; - - Property isArchEnabled = true; - - Property maliciousness = 0.0; - - Property captcha = 0; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - - Connector httpConn_0_0 : HttpConnT = new HttpConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property bandwidth = 0.0; - - Property latency = 0.0; - - Property numReqsSuccess = 0; - - Property numReqsRedirect = 0; - - Property numReqsClientError = 0; - - Property numReqsServerError = 0; - - Property isArchEnabled = true; - - } - Connector httpConn_1_0 : HttpConnT = new HttpConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property bandwidth = 0.0; - - Property latency = 0.0; - - Property numReqsSuccess = 0; - - Property numReqsRedirect = 0; - - Property numReqsClientError = 0; - - Property numReqsServerError = 0; - - Property isArchEnabled = true; - - } - Connector proxyConn_0_0 : ProxyConnT = new ProxyConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = true; - - } - Connector proxyConn_1_0 : ProxyConnT = new ProxyConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = false; - - } - Connector dbConn_0_0 : SQLConnT = new SQLConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = true; - - } - Connector dbConn_1_0 : SQLConnT = new SQLConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = true; - - } - Connector ProxyConnT0 : ProxyConnT = new ProxyConnT extended with { - - } - Connector SQLConnT0 : SQLConnT = new SQLConnT extended with { - - } - Attachment Client1.p0 to httpConn_0_0.req; - Attachment LB0.http0 to httpConn_0_0.rec; - Attachment Client0.p0 to httpConn_1_0.req; - Attachment LB0.http1 to httpConn_1_0.rec; - Attachment Server0.http0 to proxyConn_0_0.rec; - Attachment LB0.fwd0 to proxyConn_0_0.req; - Attachment ServerB0.http0 to proxyConn_1_0.rec; - Attachment LB0.fwd1 to proxyConn_1_0.req; - Attachment Server0.sql0 to dbConn_0_0.rec; - Attachment DB0.rec0 to dbConn_0_0.req; - Attachment ServerB0.sql0 to dbConn_1_0.rec; - Attachment DB0.rec1 to dbConn_1_0.req; - Attachment LB0.p to ProxyConnT0.req; - Attachment Server1.p to ProxyConnT0.rec; - Attachment Server1.p0 to SQLConnT0.req; - Attachment DB0.p to SQLConnT0.rec; - - Property MAX_RESPTIME = 2000.0; - - Property MAX_UTIL = 1; - - Property MALICIOUS_THRESHOLD = 0.8; - rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | - exists bh : BlackholerT in self.COMPONENTS | - contains(c.deploymentLocation, bh.blackholed); - rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | - forall ip : string in lb.blackholed | - forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | - c.maliciousness > self.MALICIOUS_THRESHOLD; -} - +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + Port Type PartPortT = { + + } + Port Type NetworkPortT = { + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Port Type ContainmentPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Role Type NetworkRoleT = { + + } + Role Type PartRoleT = { + + } + Role Type ContainerRoleT = { + + } + Connector Type MappingT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } +} + +Family ZNewsFam extends EnvType with { + + Port Type HttpPortT extends ArchPortT with { + + } + Port Type ProxyForwardPortT extends ArchPortT with { + + } + Port Type HttpReqPortT extends ArchPortT with { + + } + Port Type SqlReqPort extends ArchPortT with { + + } + Port Type SqlRecPort extends ArchPortT with { + + } + Component Type ProxyT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Component Type ServerT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + Property reqServiceRate : float << default : float = 0.0; >> ; + + Property byteServiceRate : float << default : float = 0.0; >> ; + + Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; + + Property cost : float << default : float = 1.0; >> ; + + Property lastPageHit : Record [uri : string; cnt : int; kbytes : float; ]; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + Component Type ClientT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property experRespTime : float << default : float = 0.0; >> ; + + Property reqRate : float << default : float = 0.0; >> ; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + Component Type DBT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "locahost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Role Type ReceiverRoleT extends ArchRoleT with { + + } + Role Type RequestorRoleT extends ArchRoleT with { + + } + Connector Type ProxyConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Connector Type SQLConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Connector Type HttpConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + Property bandwidth : float << default : float = 0.0; >> ; + + Property latency : float << default : float = 0.0; >> ; + + Property numReqsSuccess : int << default : int = 0; >> ; + + Property numReqsRedirect : int << default : int = 0; >> ; + + Property numReqsClientError : int << default : int = 0; >> ; + + Property numReqsServerError : int << default : int = 0; >> ; + + Property latencyRate : float; + + } + + Property MIN_RESPTIME : float; + + Property MAX_RESPTIME : float << default : float = 2; >> ; + + Property TOLERABLE_PERCENT_UNHAPPY : float; + + Property UNHAPPY_GRADIENT_1 : float; + + Property UNHAPPY_GRADIENT_2 : float; + + Property UNHAPPY_GRADIENT_3 : float; + + Property FRACTION_GRADIENT_1 : float; + + Property FRACTION_GRADIENT_2 : float; + + Property FRACTION_GRADIENT_3 : float; + + Property MIN_UTIL : float; + + Property MAX_UTIL : float << default : float = 1; >> ; + + Property MAX_FIDELITY_LEVEL : int; + + Property THRESHOLD_FIDELITY : int; + + Property THRESHOLD_COST : float; +} + +Family DoSFam = { + + Element Type PotentiallyMaliciousT = { + + Property deploymentLocation : string; + + Property maliciousness : float << default : float = 0.0; >> ; + + } + Element Type MaliciousT extends PotentiallyMaliciousT with { + rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; + + } + Element Type SuspiciousT extends PotentiallyMaliciousT with { + rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD AND maliciousness <= MALICIOUS_THRESHOLD; + + } + Element Type NormalT extends PotentiallyMaliciousT with { + rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; + + } + Element Type BlackholerT = { + + Property blackholed : Set {string} << default : Set {string} = {}; >> ; + + } + Element Type CaptchaRedirectT = { + + Property captchaEnabled : boolean << default : boolean = false; >> ; + + } + Element Type ThrottlerT = { + + Property throttled : Set {string} << default : Set {string} = {}; >> ; + + } + Element Type CaptchaHandlerT = { + + Property captcha : int << default : int = 0; >> ; + + } + Element Type AuthenticationHandlerT = { + + Property authenticate : int << default : int = 0; >> ; + + } + Port Type BlackholedPortT = { + + Property isBlackholed : boolean = true; + + } + + Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; + + Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; + rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | + exists bh : BlackholerT in self.COMPONENTS | + contains(c.deploymentLocation, bh.blackholed); + rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | + forall ip : string in lb.blackholed | + forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | + c.maliciousness > self.MALICIOUS_THRESHOLD; +} + +Family ZNewsDosFam extends ZNewsFam, DoSFam with { + + Component Type ZNewsClientT extends ClientT, PotentiallyMaliciousT, CaptchaHandlerT, AuthenticationHandlerT with { + + } + Component Type ZNewsLBT extends ProxyT, CaptchaRedirectT, BlackholerT, ThrottlerT with { + + } +} + +System ZNewsSys : ZNewsDosFam = new ZNewsDosFam extended with { + + Component Server0 : ArchElementT, ServerT = new ArchElementT, ServerT extended with { + Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { + + Property isArchEnabled = true; + + } + Port sql0 : SqlReqPort = new SqlReqPort extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.web0}"; + Property httpPort : string = "${customize.system.target.web0.httpPort}"; + + Property load = 0.0; + + Property reqServiceRate = 0.0; + + Property byteServiceRate = 0.0; + + Property fidelity = 5; + + Property cost = 1.0; + + Property isArchEnabled = true; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + + Component Server1 : ServerT = new ServerT extended with { + Port p : HttpPortT = new HttpPortT extended with { + + } + Port p0 : SqlReqPort = new SqlReqPort extended with { + + } + Property deploymentLocation = "${customize.system.target.web1}"; + Property httpPort : string = "${customize.system.target.web1.httpPort}"; + + Property load = 0.0; + + Property reqServiceRate = 0.0; + + Property byteServiceRate = 0.0; + + Property fidelity = 5; + + Property cost = 1.0; + + Property isArchEnabled = true; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + + Component ServerB0 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { + + Property isArchEnabled = false; + + } + Port sql0 : SqlReqPort = new SqlReqPort extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.web2}"; + Property httpPort : string = "${customize.system.target.web2.httpPort}"; + + Property load = 0.0; + + Property reqServiceRate = 0.0; + + Property byteServiceRate = 0.0; + + Property fidelity = 5; + + Property cost = 1.0; + + Property isArchEnabled = false; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + Component LB0 : ZNewsLBT = new ZNewsLBT extended with { + Port http0 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + Port http1 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + Property captchaEnabled = false; + + } + Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + Property isArchEnabled = true; + + } + Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + Property isArchEnabled = false; + + } + Port p : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + + Property deploymentLocation = "${customize.system.target.lb}"; + + Property load = 0.0; + + Property isArchEnabled = true; + + Property blackholed = {}; + + Property captchaEnabled = false; + + Property throttled = {}; + + } + Component DB0 : DBT = new DBT extended with { + Port rec0 : SqlRecPort = new SqlRecPort extended with { + + Property isArchEnabled = true; + + } + Port rec1 : SqlRecPort = new SqlRecPort extended with { + + Property isArchEnabled = true; + + } + Port p : SqlRecPort = new SqlRecPort extended with { + + } + + Property deploymentLocation = "${customize.system.target.db}"; + + Property load = 0.0; + + Property isArchEnabled = true; + + } + Component Client0 : ZNewsClientT = new ZNewsClientT extended with { + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.client1}"; + + Property experRespTime = 0; + + Property reqRate = 0.0; + + Property isArchEnabled = true; + + Property maliciousness = 0.0; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + Component Client1 : ZNewsClientT = new ZNewsClientT extended with { + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.client2}"; + + Property experRespTime = 0.0; + + Property reqRate = 0.0; + + Property isArchEnabled = true; + + Property maliciousness = 0.0; + + Property captcha = 0; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + + Connector httpConn_0_0 : HttpConnT = new HttpConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property bandwidth = 0.0; + + Property latency = 0.0; + + Property numReqsSuccess = 0; + + Property numReqsRedirect = 0; + + Property numReqsClientError = 0; + + Property numReqsServerError = 0; + + Property isArchEnabled = true; + + } + Connector httpConn_1_0 : HttpConnT = new HttpConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property bandwidth = 0.0; + + Property latency = 0.0; + + Property numReqsSuccess = 0; + + Property numReqsRedirect = 0; + + Property numReqsClientError = 0; + + Property numReqsServerError = 0; + + Property isArchEnabled = true; + + } + Connector proxyConn_0_0 : ProxyConnT = new ProxyConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = true; + + } + Connector proxyConn_1_0 : ProxyConnT = new ProxyConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = false; + + } + Connector dbConn_0_0 : SQLConnT = new SQLConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = true; + + } + Connector dbConn_1_0 : SQLConnT = new SQLConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = true; + + } + Connector ProxyConnT0 : ProxyConnT = new ProxyConnT extended with { + + } + Connector SQLConnT0 : SQLConnT = new SQLConnT extended with { + + } + Attachment Client1.p0 to httpConn_0_0.req; + Attachment LB0.http0 to httpConn_0_0.rec; + Attachment Client0.p0 to httpConn_1_0.req; + Attachment LB0.http1 to httpConn_1_0.rec; + Attachment Server0.http0 to proxyConn_0_0.rec; + Attachment LB0.fwd0 to proxyConn_0_0.req; + Attachment ServerB0.http0 to proxyConn_1_0.rec; + Attachment LB0.fwd1 to proxyConn_1_0.req; + Attachment Server0.sql0 to dbConn_0_0.rec; + Attachment DB0.rec0 to dbConn_0_0.req; + Attachment ServerB0.sql0 to dbConn_1_0.rec; + Attachment DB0.rec1 to dbConn_1_0.req; + Attachment LB0.p to ProxyConnT0.req; + Attachment Server1.p to ProxyConnT0.rec; + Attachment Server1.p0 to SQLConnT0.req; + Attachment DB0.p to SQLConnT0.rec; + + Property MAX_RESPTIME = 2000.0; + + Property MAX_UTIL = 1; + + Property MALICIOUS_THRESHOLD = 0.8; + rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | + exists bh : BlackholerT in self.COMPONENTS | + contains(c.deploymentLocation, bh.blackholed); + rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | + forall ip : string in lb.blackholed | + forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | + c.maliciousness > self.MALICIOUS_THRESHOLD; +} + diff --git a/targets/znews-ss/model/ZNewsSys.mtd b/targets/znews-ss/model/ZNewsSys.mtd index 9975f54af..e847ff51b 100644 --- a/targets/znews-ss/model/ZNewsSys.mtd +++ b/targets/znews-ss/model/ZNewsSys.mtd @@ -1,396 +1,396 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews-ss/model/gauges.yml b/targets/znews-ss/model/gauges.yml index 884789fce..211642e90 100644 --- a/targets/znews-ss/model/gauges.yml +++ b/targets/znews-ss/model/gauges.yml @@ -1,134 +1,134 @@ -# -# Gauge Type and Gauge Instance Specifications -# - time periods generally in milliseconds -# -# History: -# - [SWC 2007.01.18] Created file, populated ZNews gauge descriptions. -# - [SWC 2007.04.09] Changed LatencyGaugeT to use RtLatencyMultiHostGauge. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# - [SWC 2007.04.11] Added ResponseTimeGaugeT -# - [BRS 2013.11.13] Changed to new format -# -gauge-types: - - - BlackHoleGaugeT: - commands: - blockedIPs: "BlackholerT.setBlackholed({String})" - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.BlackholeGauge" - configParams: - targetProbeType: - type: String - default: ~ - - ThrottleGaugeT: - commands: - throttledIPs: "ThrottlerT.setThrottled({String})" - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.ThrottleGauge" - configParams: - targetProbeType: - type: String - default: ~ - - MaliciousnessGaugeT: - commands: - maliciousness : PotentiallyMaliciousT.setMaliciousness (float) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.EchoGauge" - configParams: - targetGaugeName: - type: String - default: ~ - targetGaugeType: - type: String - default: ~ - targetGaugeValue: - type: String - default: ~ - comment: "EchoGaugeT echos a value reported by another gauge" - - DummyDiagnosisGaugeT: - commands: - maliciousness: PotentiallyMaliciousT.setMaliciousness (float) - captcha: CaptchaHandlerT.setCaptchaResponse (int) - authenticate: CaptchaHandlerT.setAuthenticationResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.DummyDiagnosisGauge" - configParams: - targetProbeList: - type: String - default: ~ - - CaptchaGaugeT: - commands: - enablement : ProxyT.setCaptchaEnabled (boolean) - clientMgmt : CaptchaHandlerT.setCaptchaResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 5000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.CaptchaGauge" - configParams: - targetProbeType: - type: String - default: ~ - - AuthenticationEnablementGaugeT: - commands: - clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 5000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge" - configParams: - targetProbeType: - type: String - default: ~ +# +# Gauge Type and Gauge Instance Specifications +# - time periods generally in milliseconds +# +# History: +# - [SWC 2007.01.18] Created file, populated ZNews gauge descriptions. +# - [SWC 2007.04.09] Changed LatencyGaugeT to use RtLatencyMultiHostGauge. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# - [SWC 2007.04.11] Added ResponseTimeGaugeT +# - [BRS 2013.11.13] Changed to new format +# +gauge-types: + + + BlackHoleGaugeT: + commands: + blockedIPs: "BlackholerT.setBlackholed({String})" + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.BlackholeGauge" + configParams: + targetProbeType: + type: String + default: ~ + + ThrottleGaugeT: + commands: + throttledIPs: "ThrottlerT.setThrottled({String})" + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.ThrottleGauge" + configParams: + targetProbeType: + type: String + default: ~ + + MaliciousnessGaugeT: + commands: + maliciousness : PotentiallyMaliciousT.setMaliciousness (float) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.EchoGauge" + configParams: + targetGaugeName: + type: String + default: ~ + targetGaugeType: + type: String + default: ~ + targetGaugeValue: + type: String + default: ~ + comment: "EchoGaugeT echos a value reported by another gauge" + + DummyDiagnosisGaugeT: + commands: + maliciousness: PotentiallyMaliciousT.setMaliciousness (float) + captcha: CaptchaHandlerT.setCaptchaResponse (int) + authenticate: CaptchaHandlerT.setAuthenticationResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.DummyDiagnosisGauge" + configParams: + targetProbeList: + type: String + default: ~ + + CaptchaGaugeT: + commands: + enablement : ProxyT.setCaptchaEnabled (boolean) + clientMgmt : CaptchaHandlerT.setCaptchaResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 5000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.CaptchaGauge" + configParams: + targetProbeType: + type: String + default: ~ + + AuthenticationEnablementGaugeT: + commands: + clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 5000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge" + configParams: + targetProbeType: + type: String + default: ~ DiagnosisGaugeT: commands: @@ -143,497 +143,497 @@ gauge-types: javaClass: type: String default: "org.sa.rainbow.translator.znn.gauges.DiagnosisGauge" - configParams: - clients: - type: String + configParams: + clients: + type: String default: "c1=10.5.6.254" reportingPeriod: type: long default: 10000 comment: "Diagnosis gauge for DoS analysis" - - ResponseTimeGaugeT: - commands: - end2endRespTime : ClientT.setResponseTime (float) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.End2EndRespTimeGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "ResponseTimeGaugeT measures and reports the end-to-end response time from a client or its proxy." - - - ServerEnablementGaugeT: - commands: - removeServer: ServerT.deleteServer - addServer: "ProxyT.connectNewServer (String, String, String)" - enableServer: ServerT.enableServer (boolean) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 10000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.ServerEnablementGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - mode: - type: String - default: "enable" - comment: "ServerEnablementGaugeT reports creation/deletion or enablement/disablement of servers. mode can be either enable|new" - - - ApacheTopGaugeT: - commands: - reqServiceRate : ServerT.setReqServiceRate(float) - byteServiceRate : ServerT.setByteServiceRate(float) - numReqsSuccess : HttpConnT.setNumSuccessfulRequests(int) - numReqsRedirect : HttpConnT.setNumRedirectedRequests(int) - numReqsClientError : HttpConnT.setNumRequestsClientError(int) - numReqsServerError : HttpConnT.setNumRequestsServerError(int) - pageHit : ServerT.setLastPageHit(String) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.ApacheTopGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "ApacheTopGaugeT measures and reports properties of an Apache server, via a UNIX top like utility" - - DiskIOGaugeT: - commands: - transferRate : ServerT.setDiskTransferRate(double) - readRate : ServerT.setDiskReadRate(double) - writeRate : ServerT.setDiskWriteRate(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.DiskIOGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "DiskIOGaugeT measures and reports disk IO stat of the target host, read/write reported in KBps" - - LoadGaugeT: - commands: - load : ServerT.setLoad(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.CpuLoadGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "LoadGaugeT measures and reports CPU load of the target host" - - FidelityGaugeT: - commands: - fidelity : ServerT.setFidelity(int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.FidelityGauge" - configParams: - samplingFrequency: - type: long - default: 2500 - targetProbeType: - type: String - default: ~ - comment: "FidelityGaugeT measures and reports the fidelity level of served content" - - LatencyGaugeT: - commands: - latency : HttpConnT.setLatency(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge" - configParams: - samplingFrequency: - type: long - default: 1500 - targetProbeType: - type: String - default: ~ - comment: "LatencyGaugeT measures and reports latency on a connection" - - LatencyRateGaugeT: - commands: - latencyRate : HttpConnT.setLatencyRate(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge" - configParams: - samplingFrequency: - type: long - default: 1500 - targetProbeType: - type: String - default: ~ - comment: "LatencyRateGaugeT measures and reports the latency rate of change on a connection" - - - -gauge-instances: - - BHG1: - type: BlackHoleGaugeT - model: "ZNewsSys:Acme" - commands: - "blockedIPs": LB0.setBlackholed ($) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - reportingPeriod: 10000 - targetProbeType: blackhole - - TG1: - type: ThrottleGaugeT - model: "ZNewsSys:Acme" - commands: - "throttledIPs": LB0.setThrottled ($) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - reportingPeriod: 10000 - targetProbeType: throttle - - MG1: - type: DummyDiagnosisGaugeT - model: "ZNewsSys:Acme" - commands: - "maliciousness(x)": x.setMaliciousness ($) - "captcha(x)": x.setCaptchaResponse ($) - "authenticate(x)": x.setAuthenticationResponse ($) - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - reportingPeriod: 10000 - targetProbeList: "dummymaliciousness@*,authenticationprobe" - - - CG1: - type: CaptchaGaugeT - model: "ZNewsSys:Acme" - commands: - "enabled": LB0.setCaptchaEnabled($) - "clientMgmt(${customize.system.target.client1})": Client0.setCaptchaResponse (0) - "clientMgmt(${customize.system.target.client2})": Client1.setCaptchaResponse (0) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - samplingFrequency: 1000 - targetProbeType: captchaprobe - - AEG1: - type: AuthenticationEnablementGaugeT - model: "ZNewsSys:Acme" - commands: - "clientMgmt(${customize.system.target.client1})": Client0.setAuthenticationResponse (0) - "clientMgmt(${customize.system.target.client2})": Client1.setAuthenticationResponse (0) - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - samplingFrequency: 1000 - targetProbeType: authenticationprobe + + ResponseTimeGaugeT: + commands: + end2endRespTime : ClientT.setResponseTime (float) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.End2EndRespTimeGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "ResponseTimeGaugeT measures and reports the end-to-end response time from a client or its proxy." + + + ServerEnablementGaugeT: + commands: + removeServer: ServerT.deleteServer + addServer: "ProxyT.connectNewServer (String, String, String)" + enableServer: ServerT.enableServer (boolean) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 10000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.ServerEnablementGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + mode: + type: String + default: "enable" + comment: "ServerEnablementGaugeT reports creation/deletion or enablement/disablement of servers. mode can be either enable|new" + + + ApacheTopGaugeT: + commands: + reqServiceRate : ServerT.setReqServiceRate(float) + byteServiceRate : ServerT.setByteServiceRate(float) + numReqsSuccess : HttpConnT.setNumSuccessfulRequests(int) + numReqsRedirect : HttpConnT.setNumRedirectedRequests(int) + numReqsClientError : HttpConnT.setNumRequestsClientError(int) + numReqsServerError : HttpConnT.setNumRequestsServerError(int) + pageHit : ServerT.setLastPageHit(String) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.ApacheTopGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "ApacheTopGaugeT measures and reports properties of an Apache server, via a UNIX top like utility" + + DiskIOGaugeT: + commands: + transferRate : ServerT.setDiskTransferRate(double) + readRate : ServerT.setDiskReadRate(double) + writeRate : ServerT.setDiskWriteRate(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.DiskIOGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "DiskIOGaugeT measures and reports disk IO stat of the target host, read/write reported in KBps" + + LoadGaugeT: + commands: + load : ServerT.setLoad(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.CpuLoadGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "LoadGaugeT measures and reports CPU load of the target host" + + FidelityGaugeT: + commands: + fidelity : ServerT.setFidelity(int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.FidelityGauge" + configParams: + samplingFrequency: + type: long + default: 2500 + targetProbeType: + type: String + default: ~ + comment: "FidelityGaugeT measures and reports the fidelity level of served content" + + LatencyGaugeT: + commands: + latency : HttpConnT.setLatency(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge" + configParams: + samplingFrequency: + type: long + default: 1500 + targetProbeType: + type: String + default: ~ + comment: "LatencyGaugeT measures and reports latency on a connection" + + LatencyRateGaugeT: + commands: + latencyRate : HttpConnT.setLatencyRate(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge" + configParams: + samplingFrequency: + type: long + default: 1500 + targetProbeType: + type: String + default: ~ + comment: "LatencyRateGaugeT measures and reports the latency rate of change on a connection" + + + +gauge-instances: + + BHG1: + type: BlackHoleGaugeT + model: "ZNewsSys:Acme" + commands: + "blockedIPs": LB0.setBlackholed ($) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + reportingPeriod: 10000 + targetProbeType: blackhole + + TG1: + type: ThrottleGaugeT + model: "ZNewsSys:Acme" + commands: + "throttledIPs": LB0.setThrottled ($) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + reportingPeriod: 10000 + targetProbeType: throttle + + MG1: + type: DummyDiagnosisGaugeT + model: "ZNewsSys:Acme" + commands: + "maliciousness(x)": x.setMaliciousness ($) + "captcha(x)": x.setCaptchaResponse ($) + "authenticate(x)": x.setAuthenticationResponse ($) + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + reportingPeriod: 10000 + targetProbeList: "dummymaliciousness@*,authenticationprobe" + + + CG1: + type: CaptchaGaugeT + model: "ZNewsSys:Acme" + commands: + "enabled": LB0.setCaptchaEnabled($) + "clientMgmt(${customize.system.target.client1})": Client0.setCaptchaResponse (0) + "clientMgmt(${customize.system.target.client2})": Client1.setCaptchaResponse (0) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + samplingFrequency: 1000 + targetProbeType: captchaprobe + + AEG1: + type: AuthenticationEnablementGaugeT + model: "ZNewsSys:Acme" + commands: + "clientMgmt(${customize.system.target.client1})": Client0.setAuthenticationResponse (0) + "clientMgmt(${customize.system.target.client2})": Client1.setAuthenticationResponse (0) + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + samplingFrequency: 1000 + targetProbeType: authenticationprobe - EERTG1: - type: ResponseTimeGaugeT - model: "ZNewsSys:Acme" - commands: - "end2endRespTime(${customize.system.target.master})" : Client0.setResponseTime($) - "end2endRespTime(${customize.system.target.bad})" : Client1.setResponseTime($) - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - samplingFrequency: 1000 - targetProbeType : clientproxy@* - comment: "EERTG1 is associated with the client component of the System, ZNewsSys, defined as an Acme model" - - - SEG1: - type: ServerEnablementGaugeT - model: "ZNewsSys:Acme" - commands: - "removeServer(x)": x.deleteServer - "connectServer(x)": "LB0.connectNewServer (Server0, $, $)" - "enableServer(x)": "LB0.enableServer (x, $)" - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - targetProbeType: "enablementprobe@${customize.system.target.lb}" - samplingFrequency: 1000 - mode: new - comment: "This needs to be located on the master because it needs access to the model" - - LoG0: - type: LoadGaugeT - model: "ZNewsSys:Acme" - commands: - load : LB0.setLoad($) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG1 is associated with the component LB0 of the System, ZNewsSys, defined as an Acme model" - - LoG1: - type: LoadGaugeT - model: "ZNewsSys:Acme" - commands: - load : Server0.setLoad($) - setupValues: - targetIP: "${customize.system.target.web0}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG1 is associated with the component LB0 of the System, ZNewsSys, defined as an Acme model" - - LoG2: - type: LoadGaugeT - model: "ZNewsSys:Acme" - commands: - load : Server1.setLoad($) - setupValues: - targetIP: "${customize.system.target.web1}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG1 is associated with the component LB0 of the System, ZNewsSys, defined as an Acme model" - - LoG3: - type: LoadGaugeT - model: "ZNewsSys:Acme" - commands: - load : ServerB0.setLoad($) - setupValues: - targetIP: "${customize.system.target.web2}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG1 is associated with the component LB0 of the System, ZNewsSys, defined as an Acme model" - - -unused-gauge-instances: - - MG1: - type: MaliciousnessGaugeT - model: "ZNewsSys:Acme" - mappings: - "maliciousness(c2)": Client1.maliciousness - "maliciousness(c1)": Client0.maliciousness - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - targetGaugeName: DG1 - targetGaugeType: DiagnosisGaugeT - targetGaugeValue: maliciousness - - DG1: - type: DiagnosisGaugeT - model: "ZNewsSys:Acme" - mappings: - "maliciousness": x - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - reportingPeriod: 10000 - - ATG1: - type: ApacheTopGaugeT - model: "ZNewsSys:Acme" - mappings: - reqServiceRate : s0.reqServiceRate - byteServiceRate : s0.byteServiceRate - numReqsSuccess : conn0.numReqsSuccess - numReqsRedirect : conn0.numReqsRedirect - numReqsClientError : conn0.numReqsClientError - numReqsServerError : conn0.numReqsServerError - pageHit : s0.lastPageHit - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: ~ - # Leave details unspecified (null) to use default value defined at the type-level - targetProbeType : apachetop - comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" - - DioG1: - type: DiskIOGaugeT - model: "ZNewsSys:Acme" - mappings: - transferRate : s0.diskXferRate - readRate : s0.diskReadRate - writeRate : s0.diskWriteRate - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1000 - targetProbeType : diskio - comment: "DioG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LoG0: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s0.load - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG0 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LoG1: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s1.load - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG1 is associated with the component s1 of the System, ZNewsSys, defined as an Acme model" - - FiG1: - type: FidelityGaugeT - model: "ZNewsSys:Acme" - mappings: - fidelity : s0.fidelity - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 2500 - targetProbeType : fidelity - comment: "FiG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LatG1: - type: LatencyGaugeT - model: "ZNewsSys:Acme" - mappings: - "latency(${rainbow.master.location.host})" : conn0.latency - "latency(@{ZNewsSys.s1.deploymentLocation})" : conn1.latency - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1500 - targetProbeType : pingrtt - comment: "LatG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" - - LatRoCG1: - type: LatencyRateGaugeT - model: "ZNewsSys:Acme" - mappings: - "latencyRate(${rainbow.master.location.host})" : conn0.latencyRate - "latencyRate(@{ZNewsSys.s1.deploymentLocation})" : conn1.latencyRate - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1500 - targetProbeType : pingrtt - comment: "LatRoCG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" - - ATG0: - type: ApacheTopGaugeT - model: "ZNewsSys:Acme" - mappings: - reqServiceRate : s0.reqServiceRate - byteServiceRate : s0.byteServiceRate - numReqsSuccess : conn0.numReqsSuccess - numReqsRedirect : conn0.numReqsRedirect - numReqsClientError : conn0.numReqsClientError - numReqsServerError : conn0.numReqsServerError - pageHit : s0.lastPageHit - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - samplingFrequency: ~ - # Leave details unspecified (null) to use default value defined at the type-level - targetProbeType : apachetop - comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" - - LoG3: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s3.load - setupValues: - targetIP: "${customize.system.target.3}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG3 is associated with the component s3 of the System, ZNewsSys, defined as an Acme model" - + EERTG1: + type: ResponseTimeGaugeT + model: "ZNewsSys:Acme" + commands: + "end2endRespTime(${customize.system.target.master})" : Client0.setResponseTime($) + "end2endRespTime(${customize.system.target.bad})" : Client1.setResponseTime($) + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + samplingFrequency: 1000 + targetProbeType : clientproxy@* + comment: "EERTG1 is associated with the client component of the System, ZNewsSys, defined as an Acme model" + + + SEG1: + type: ServerEnablementGaugeT + model: "ZNewsSys:Acme" + commands: + "removeServer(x)": x.deleteServer + "connectServer(x)": "LB0.connectNewServer (Server0, $, $)" + "enableServer(x)": "LB0.enableServer (x, $)" + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + targetProbeType: "enablementprobe@${customize.system.target.lb}" + samplingFrequency: 1000 + mode: new + comment: "This needs to be located on the master because it needs access to the model" + + LoG0: + type: LoadGaugeT + model: "ZNewsSys:Acme" + commands: + load : LB0.setLoad($) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG1 is associated with the component LB0 of the System, ZNewsSys, defined as an Acme model" + + LoG1: + type: LoadGaugeT + model: "ZNewsSys:Acme" + commands: + load : Server0.setLoad($) + setupValues: + targetIP: "${customize.system.target.web0}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG1 is associated with the component LB0 of the System, ZNewsSys, defined as an Acme model" + + LoG2: + type: LoadGaugeT + model: "ZNewsSys:Acme" + commands: + load : Server1.setLoad($) + setupValues: + targetIP: "${customize.system.target.web1}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG1 is associated with the component LB0 of the System, ZNewsSys, defined as an Acme model" + + LoG3: + type: LoadGaugeT + model: "ZNewsSys:Acme" + commands: + load : ServerB0.setLoad($) + setupValues: + targetIP: "${customize.system.target.web2}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG1 is associated with the component LB0 of the System, ZNewsSys, defined as an Acme model" + + +unused-gauge-instances: + + MG1: + type: MaliciousnessGaugeT + model: "ZNewsSys:Acme" + mappings: + "maliciousness(c2)": Client1.maliciousness + "maliciousness(c1)": Client0.maliciousness + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + targetGaugeName: DG1 + targetGaugeType: DiagnosisGaugeT + targetGaugeValue: maliciousness + + DG1: + type: DiagnosisGaugeT + model: "ZNewsSys:Acme" + mappings: + "maliciousness": x + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + reportingPeriod: 10000 + + ATG1: + type: ApacheTopGaugeT + model: "ZNewsSys:Acme" + mappings: + reqServiceRate : s0.reqServiceRate + byteServiceRate : s0.byteServiceRate + numReqsSuccess : conn0.numReqsSuccess + numReqsRedirect : conn0.numReqsRedirect + numReqsClientError : conn0.numReqsClientError + numReqsServerError : conn0.numReqsServerError + pageHit : s0.lastPageHit + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: ~ + # Leave details unspecified (null) to use default value defined at the type-level + targetProbeType : apachetop + comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" + + DioG1: + type: DiskIOGaugeT + model: "ZNewsSys:Acme" + mappings: + transferRate : s0.diskXferRate + readRate : s0.diskReadRate + writeRate : s0.diskWriteRate + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1000 + targetProbeType : diskio + comment: "DioG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LoG0: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s0.load + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG0 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LoG1: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s1.load + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG1 is associated with the component s1 of the System, ZNewsSys, defined as an Acme model" + + FiG1: + type: FidelityGaugeT + model: "ZNewsSys:Acme" + mappings: + fidelity : s0.fidelity + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 2500 + targetProbeType : fidelity + comment: "FiG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LatG1: + type: LatencyGaugeT + model: "ZNewsSys:Acme" + mappings: + "latency(${rainbow.master.location.host})" : conn0.latency + "latency(@{ZNewsSys.s1.deploymentLocation})" : conn1.latency + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1500 + targetProbeType : pingrtt + comment: "LatG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" + + LatRoCG1: + type: LatencyRateGaugeT + model: "ZNewsSys:Acme" + mappings: + "latencyRate(${rainbow.master.location.host})" : conn0.latencyRate + "latencyRate(@{ZNewsSys.s1.deploymentLocation})" : conn1.latencyRate + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1500 + targetProbeType : pingrtt + comment: "LatRoCG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" + + ATG0: + type: ApacheTopGaugeT + model: "ZNewsSys:Acme" + mappings: + reqServiceRate : s0.reqServiceRate + byteServiceRate : s0.byteServiceRate + numReqsSuccess : conn0.numReqsSuccess + numReqsRedirect : conn0.numReqsRedirect + numReqsClientError : conn0.numReqsClientError + numReqsServerError : conn0.numReqsServerError + pageHit : s0.lastPageHit + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + samplingFrequency: ~ + # Leave details unspecified (null) to use default value defined at the type-level + targetProbeType : apachetop + comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" + + LoG3: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s3.load + setupValues: + targetIP: "${customize.system.target.3}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG3 is associated with the component s3 of the System, ZNewsSys, defined as an Acme model" + diff --git a/targets/znews-ss/model/gauges=new.yml b/targets/znews-ss/model/gauges=new.yml index c86ad3019..aeef0e822 100644 --- a/targets/znews-ss/model/gauges=new.yml +++ b/targets/znews-ss/model/gauges=new.yml @@ -1,165 +1,165 @@ -# -# Gauge Type and Gauge Instance Specifications -# - Split gauges by family -# - Need to tie to probes (and operators) -# - -family: - name : DoSFam - defined-in: ZNewsSys.acme - command-type: java - factory: org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory - - gauge-types: - - BlackHoleGaugeT: - commands: - # The commands that the gauge will produce, keyed by some name - # The rhs needs to be an operator defined according to the factory - # for the family. In this case, there must be an operator - # 'setBlackholed' associated with the type 'BlackholerT' in the - # 'DoSFam'. (In the above, this is defined in the factory.) - blockedIPs: "BlackholerT.setBlackholed({String})" - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.BlackholeGauge" - configParams: - targetProbeType: - type: String - default: ~ - # Definition of what kind of probe is expected to report to this gauge - # and what kind of report it is giving - probe-type: - type: blackhole - value-type: regex - regex: (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3},\s*)*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - ThrottleGaugeT: - commands: - throttledIPs: "ThrottlerT.setThrottled({String})" - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.ThrottleGauge" - configParams: - targetProbeType: - type: String - default: ~ - - MaliciousnessGaugeT: - commands: - maliciousness : PotentiallyMaliciousT.setMaliciousness (float) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.EchoGauge" - configParams: - targetGaugeName: - type: String - default: ~ - targetGaugeType: - type: String - default: ~ - targetGaugeValue: - type: String - default: ~ - comment: "EchoGaugeT echos a value reported by another gauge" - - DummyDiagnosisGaugeT: - commands: - maliciousness: PotentiallyMaliciousT.setMaliciousness (float) - captcha: CaptchaHandlerT.setCaptchaResponse (int) - authenticate: CaptchaHandlerT.setAuthenticationResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.DummyDiagnosisGauge" - configParams: - targetProbeList: - type: String - default: ~ - - CaptchaGaugeT: - commands: - enablement : ProxyT.setCaptchaEnabled (boolean) - clientMgmt : CaptchaHandlerT.setCaptchaResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 5000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.CaptchaGauge" - configParams: - targetProbeType: - type: String - default: ~ - - AuthenticationEnablementGaugeT: - commands: - clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 5000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge" - configParams: - targetProbeType: - type: String - default: ~ - - DiagnosisGaugeT: - commands: - maliciousness: PotentiallyMaliciousT.setMaliciousness (float) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.DiagnosisGauge" - configParams: - clients: - type: String - default: "c1=10.5.6.254" - reportingPeriod: - type: long - default: 10000 - comment: "Diagnosis gauge for DoS analysis" +# +# Gauge Type and Gauge Instance Specifications +# - Split gauges by family +# - Need to tie to probes (and operators) +# + +family: + name : DoSFam + defined-in: ZNewsSys.acme + command-type: java + factory: org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory + + gauge-types: + + BlackHoleGaugeT: + commands: + # The commands that the gauge will produce, keyed by some name + # The rhs needs to be an operator defined according to the factory + # for the family. In this case, there must be an operator + # 'setBlackholed' associated with the type 'BlackholerT' in the + # 'DoSFam'. (In the above, this is defined in the factory.) + blockedIPs: "BlackholerT.setBlackholed({String})" + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.BlackholeGauge" + configParams: + targetProbeType: + type: String + default: ~ + # Definition of what kind of probe is expected to report to this gauge + # and what kind of report it is giving + probe-type: + type: blackhole + value-type: regex + regex: (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3},\s*)*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) + + ThrottleGaugeT: + commands: + throttledIPs: "ThrottlerT.setThrottled({String})" + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.ThrottleGauge" + configParams: + targetProbeType: + type: String + default: ~ + + MaliciousnessGaugeT: + commands: + maliciousness : PotentiallyMaliciousT.setMaliciousness (float) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.EchoGauge" + configParams: + targetGaugeName: + type: String + default: ~ + targetGaugeType: + type: String + default: ~ + targetGaugeValue: + type: String + default: ~ + comment: "EchoGaugeT echos a value reported by another gauge" + + DummyDiagnosisGaugeT: + commands: + maliciousness: PotentiallyMaliciousT.setMaliciousness (float) + captcha: CaptchaHandlerT.setCaptchaResponse (int) + authenticate: CaptchaHandlerT.setAuthenticationResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.DummyDiagnosisGauge" + configParams: + targetProbeList: + type: String + default: ~ + + CaptchaGaugeT: + commands: + enablement : ProxyT.setCaptchaEnabled (boolean) + clientMgmt : CaptchaHandlerT.setCaptchaResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 5000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.CaptchaGauge" + configParams: + targetProbeType: + type: String + default: ~ + + AuthenticationEnablementGaugeT: + commands: + clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 5000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge" + configParams: + targetProbeType: + type: String + default: ~ + + DiagnosisGaugeT: + commands: + maliciousness: PotentiallyMaliciousT.setMaliciousness (float) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.DiagnosisGauge" + configParams: + clients: + type: String + default: "c1=10.5.6.254" + reportingPeriod: + type: long + default: 10000 + comment: "Diagnosis gauge for DoS analysis" \ No newline at end of file diff --git a/targets/znews-ss/model/op.map b/targets/znews-ss/model/op.map index 867bb0232..5cf840f9c 100644 --- a/targets/znews-ss/model/op.map +++ b/targets/znews-ss/model/op.map @@ -1,8 +1,8 @@ -setFidelity: changeState -blackhole: changeState -unblackhole: changeState -enableCaptcha: changeState -disableCaptcha: changeState -activateServer: start -deactivateServer: stop - +setFidelity: changeState +blackhole: changeState +unblackhole: changeState +enableCaptcha: changeState +disableCaptcha: changeState +activateServer: start +deactivateServer: stop + diff --git a/targets/znews-ss/rainbow-10.5.6.1.properties b/targets/znews-ss/rainbow-10.5.6.1.properties index cfc220922..f3b58f741 100644 --- a/targets/znews-ss/rainbow-10.5.6.1.properties +++ b/targets/znews-ss/rainbow-10.5.6.1.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.1 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.1 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss/rainbow-10.5.6.3.properties b/targets/znews-ss/rainbow-10.5.6.3.properties index cd2a3a569..1ae1db5fe 100644 --- a/targets/znews-ss/rainbow-10.5.6.3.properties +++ b/targets/znews-ss/rainbow-10.5.6.3.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.3 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.3 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss/rainbow-10.5.6.4.properties b/targets/znews-ss/rainbow-10.5.6.4.properties index dc87c9608..e2ffde51c 100644 --- a/targets/znews-ss/rainbow-10.5.6.4.properties +++ b/targets/znews-ss/rainbow-10.5.6.4.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.4 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.4 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss/rainbow-10.5.6.5.properties b/targets/znews-ss/rainbow-10.5.6.5.properties index f92704d09..e5cf62d61 100644 --- a/targets/znews-ss/rainbow-10.5.6.5.properties +++ b/targets/znews-ss/rainbow-10.5.6.5.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.5 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.5 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss/rainbow-10.5.6.6.properties b/targets/znews-ss/rainbow-10.5.6.6.properties index 9ea44d2bd..7b9c3b575 100644 --- a/targets/znews-ss/rainbow-10.5.6.6.properties +++ b/targets/znews-ss/rainbow-10.5.6.6.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.6 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.6 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss/rainbow.properties b/targets/znews-ss/rainbow.properties index 41966da58..e6581bb5a 100644 --- a/targets/znews-ss/rainbow.properties +++ b/targets/znews-ss/rainbow.properties @@ -1,127 +1,127 @@ -################################################################################ -# Purpose: Common configuration file for the Rainbow infrastructure. -# Properties are loaded by class org.sa.rainbow.Rainbow . -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -### -# Default values for location specific properties, meaning that, if the -# rainbow-.properties file does not specify a value, the default value -# set here is used. - -### Utility mechanism configuration -#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL -logging.level = DEBUG -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log -# (default) -#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" -#logging.max.size = 1024 -#logging.max.backups = 5 - -### Rainbow component customization -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = 127.0.0.1 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.2.2 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.event.service = eseb -eBus Relay - -rainbow.delegate.beaconperiod = 10000 -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory - -### Rainbow models -rainbow.model.number=3 - -# Rainbow Acme model of ZNN -rainbow.model.path_0 = model/ZNewsSys.acme -rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory -rainbow.model.name_0 = ZNewsSys -rainbow.model.saveOnClose_0=true -rainbow.model.saveLocation_0=model/ZNewSys-post.acme - -# Rainbow utility model - keeps current utility along desired utility dimensions -# specified in stitch/utilities.yml -rainbow.model.path_1 = stitch/utilities.yml -rainbow.model.load.class_1=org.sa.rainbow.model.utility.UtilityCommandFactory -rainbow.model.name_1=ZNewsSys - -# Rainbow utility history model - keeps utility history -rainbow.model.load.class_2=org.sa.rainbow.model.utility.UtilityHistoryCommandFactory -rainbow.model.name_2=ZNewsSys -rainbow.model.saveOnClose_2=true -rainbow.model.saveLocation_2=model/uh.csv - - -### Rainbow analyses -rainbow.analyses.size = 2 -# Checks architecture for architectural errors -rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator -# Calculates utility of the system after each change to the arch model -rainbow.analyses_1 = org.sa.rainbow.evaluator.utility.UtilityEvaluator - -#Rainbow adaptation & stitch components -rainbow.adaptation.manager.size = 1 -rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager -rainbow.adaptation.manager.model_0=ZNewsSys:Acme - -rainbow.adaptation.executor.size = 1 -rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.StitchExecutor -rainbow.adaptation.executor.model_0=ZNewsSys:Acme - -rainbow.effector.manager.size = 1 -rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager - - -customize.model.evaluate.period = 2000 -## Translator customization -#- Gauge spec -customize.gauges.path = model/gauges.yml -#- Probe spec -customize.probes.path = system/probes.yml -#- Operator spec as mapping to effector -customize.archop.map.path = model/op.map -#- Effector spec -customize.effectors.path = system/effectors.yml -## Adaptation Manager -#- Directory of Stitch adaptation script -customize.scripts.path = stitch -#- Utilities description file, Strategy evaluation config, and minimum score threshold -customize.utility.path = stitch/utilities.yml -customize.utility.trackStrategy = uSF -customize.utility.score.minimum.threshold = 0.33 -customize.utility.scenario = scenario 1 -#- Whether to enable prediction, ONLY enable if system has predictor probes! -#customize.prediction.enable = false - -## System configuration information -# These properties may be referred to in various files -# in the target (e.g., Acme, gauges, effectors, probes) -# and are replaced by Rainbow with the actual values -customize.system.target.master = ${rainbow.deployment.location} -customize.system.target.lb = 10.5.6.1 -customize.system.target.lb.httpPort = 1081 -customize.system.target.web0 = 10.5.6.3 -customize.system.target.web0.httpPort = 1080 -customize.system.target.web1 = 10.5.6.4 -customize.system.target.web1.httpPort = 1080 -customize.system.target.db = 10.5.6.2 -customize.system.target.web2 = 10.5.6.5 -customize.system.target.web2.httpPort=1080 -customize.system.target.web2.disabled=true -customize.system.target.client1=10.0.2.2 -customize.system.target.client2=10.5.6.6 -customize.system.target.bad=10.5.6.6 +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +logging.level = DEBUG +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = 127.0.0.1 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.2.2 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.event.service = eseb +eBus Relay + +rainbow.delegate.beaconperiod = 10000 +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory + +### Rainbow models +rainbow.model.number=3 + +# Rainbow Acme model of ZNN +rainbow.model.path_0 = model/ZNewsSys.acme +rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory +rainbow.model.name_0 = ZNewsSys +rainbow.model.saveOnClose_0=true +rainbow.model.saveLocation_0=model/ZNewSys-post.acme + +# Rainbow utility model - keeps current utility along desired utility dimensions +# specified in stitch/utilities.yml +rainbow.model.path_1 = stitch/utilities.yml +rainbow.model.load.class_1=org.sa.rainbow.model.utility.UtilityCommandFactory +rainbow.model.name_1=ZNewsSys + +# Rainbow utility history model - keeps utility history +rainbow.model.load.class_2=org.sa.rainbow.model.utility.UtilityHistoryCommandFactory +rainbow.model.name_2=ZNewsSys +rainbow.model.saveOnClose_2=true +rainbow.model.saveLocation_2=model/uh.csv + + +### Rainbow analyses +rainbow.analyses.size = 2 +# Checks architecture for architectural errors +rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator +# Calculates utility of the system after each change to the arch model +rainbow.analyses_1 = org.sa.rainbow.evaluator.utility.UtilityEvaluator + +#Rainbow adaptation & stitch components +rainbow.adaptation.manager.size = 1 +rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager +rainbow.adaptation.manager.model_0=ZNewsSys:Acme + +rainbow.adaptation.executor.size = 1 +rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.StitchExecutor +rainbow.adaptation.executor.model_0=ZNewsSys:Acme + +rainbow.effector.manager.size = 1 +rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager + + +customize.model.evaluate.period = 2000 +## Translator customization +#- Gauge spec +customize.gauges.path = model/gauges.yml +#- Probe spec +customize.probes.path = system/probes.yml +#- Operator spec as mapping to effector +customize.archop.map.path = model/op.map +#- Effector spec +customize.effectors.path = system/effectors.yml +## Adaptation Manager +#- Directory of Stitch adaptation script +customize.scripts.path = stitch +#- Utilities description file, Strategy evaluation config, and minimum score threshold +customize.utility.path = stitch/utilities.yml +customize.utility.trackStrategy = uSF +customize.utility.score.minimum.threshold = 0.33 +customize.utility.scenario = scenario 1 +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# These properties may be referred to in various files +# in the target (e.g., Acme, gauges, effectors, probes) +# and are replaced by Rainbow with the actual values +customize.system.target.master = ${rainbow.deployment.location} +customize.system.target.lb = 10.5.6.1 +customize.system.target.lb.httpPort = 1081 +customize.system.target.web0 = 10.5.6.3 +customize.system.target.web0.httpPort = 1080 +customize.system.target.web1 = 10.5.6.4 +customize.system.target.web1.httpPort = 1080 +customize.system.target.db = 10.5.6.2 +customize.system.target.web2 = 10.5.6.5 +customize.system.target.web2.httpPort=1080 +customize.system.target.web2.disabled=true +customize.system.target.client1=10.0.2.2 +customize.system.target.client2=10.5.6.6 +customize.system.target.bad=10.5.6.6 diff --git a/targets/znews-ss/rainbow.properties-all-in-one-machine b/targets/znews-ss/rainbow.properties-all-in-one-machine index f05013820..349283e56 100644 --- a/targets/znews-ss/rainbow.properties-all-in-one-machine +++ b/targets/znews-ss/rainbow.properties-all-in-one-machine @@ -1,112 +1,112 @@ -################################################################################ -# Purpose: Common configuration file for the Rainbow infrastructure. -# Properties are loaded by class org.sa.rainbow.Rainbow . -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -### -# Default values for location specific properties, meaning that, if the -# rainbow-.properties file does not specify a value, the default value -# set here is used. - -### Utility mechanism configuration -#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL -logging.level = DEBUG -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log -# (default) -#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" -#logging.max.size = 1024 -#logging.max.backups = 5 - -### Rainbow component customization -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = 127.0.0.1 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.2.2 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.event.service = eseb -eBus Relay - -rainbow.delegate.beaconperiod = 10000 -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory - -#Rainbow models -rainbow.model.number=1 -rainbow.model.path_0 = model/ZNewsSys.acme -rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory -rainbow.model.name_0 = ZNewsSys - -#Rainbow analyses -rainbow.analyses.size = 1 -rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator - -#Rainbow adaptation & stitch components -rainbow.adaptation.manager.size = 1 -rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager -rainbow.adaptation.manager.model_0=ZNewsSys:Acme - -rainbow.adaptation.executor.size = 1 -rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.Executor -rainbow.adaptation.executor.model_0=ZNewsSys:Acme - -rainbow.effector.manager.size = 1 -rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager - - -customize.model.evaluate.period = 2000 -## Translator customization -#- Gauge spec -customize.gauges.path = model/gauges.yml -#- Probe spec -customize.probes.path = system/probes.yml -#- Operator spec as mapping to effector -customize.archop.map.path = model/op.map -#- Effector spec -customize.effectors.path = system/effectors.yml -## Adaptation Manager -#- Directory of Stitch adaptation script -customize.scripts.path = stitch -#- Utilities description file, Strategy evaluation config, and minimum score threshold -customize.utility.path = stitch/utilities.yml -customize.utility.trackStrategy = uSF -customize.utility.score.minimum.threshold = 0.33 -customize.utility.scenario = scenario 2 -#- Whether to enable prediction, ONLY enable if system has predictor probes! -#customize.prediction.enable = false - -## System configuration information -# -#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: -#customize.system.sim.path = znewspred/znews-transbw.sim -#- if real target system: -#customize.system.target.0 = ${rainbow.master.location.host} -#customize.system.target.1 = 10.0.2.15 -#customize.system.target.1 = waterfall.able.cs.cmu.edu -#customize.system.target.0 = localhost -#customize.system.target.2 = oracle -#customize.system.target.size = 3 -#customize.system.target.size = 2 -customize.system.target.master = ${rainbow.deployment.location} -customize.system.target.lb = 10.5.6.1 -customize.system.target.lb.httpPort = 1081 -customize.system.target.web0 = 10.5.6.1 -customize.system.target.web0.httpPort = 1080 -customize.system.target.web1 = 10.5.6.1 -customize.system.target.web1.httpPort = 1082 -customize.system.target.db = 10.5.6.1 -#customize.system.target.0 = ${rainbow.deployment.location} -#customize.system.target.1 = 10.5.6.1 -#customize.system.target.size = 2 +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +logging.level = DEBUG +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = 127.0.0.1 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.2.2 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.event.service = eseb +eBus Relay + +rainbow.delegate.beaconperiod = 10000 +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory + +#Rainbow models +rainbow.model.number=1 +rainbow.model.path_0 = model/ZNewsSys.acme +rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory +rainbow.model.name_0 = ZNewsSys + +#Rainbow analyses +rainbow.analyses.size = 1 +rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator + +#Rainbow adaptation & stitch components +rainbow.adaptation.manager.size = 1 +rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager +rainbow.adaptation.manager.model_0=ZNewsSys:Acme + +rainbow.adaptation.executor.size = 1 +rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.Executor +rainbow.adaptation.executor.model_0=ZNewsSys:Acme + +rainbow.effector.manager.size = 1 +rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager + + +customize.model.evaluate.period = 2000 +## Translator customization +#- Gauge spec +customize.gauges.path = model/gauges.yml +#- Probe spec +customize.probes.path = system/probes.yml +#- Operator spec as mapping to effector +customize.archop.map.path = model/op.map +#- Effector spec +customize.effectors.path = system/effectors.yml +## Adaptation Manager +#- Directory of Stitch adaptation script +customize.scripts.path = stitch +#- Utilities description file, Strategy evaluation config, and minimum score threshold +customize.utility.path = stitch/utilities.yml +customize.utility.trackStrategy = uSF +customize.utility.score.minimum.threshold = 0.33 +customize.utility.scenario = scenario 2 +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# +#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: +#customize.system.sim.path = znewspred/znews-transbw.sim +#- if real target system: +#customize.system.target.0 = ${rainbow.master.location.host} +#customize.system.target.1 = 10.0.2.15 +#customize.system.target.1 = waterfall.able.cs.cmu.edu +#customize.system.target.0 = localhost +#customize.system.target.2 = oracle +#customize.system.target.size = 3 +#customize.system.target.size = 2 +customize.system.target.master = ${rainbow.deployment.location} +customize.system.target.lb = 10.5.6.1 +customize.system.target.lb.httpPort = 1081 +customize.system.target.web0 = 10.5.6.1 +customize.system.target.web0.httpPort = 1080 +customize.system.target.web1 = 10.5.6.1 +customize.system.target.web1.httpPort = 1082 +customize.system.target.db = 10.5.6.1 +#customize.system.target.0 = ${rainbow.deployment.location} +#customize.system.target.1 = 10.5.6.1 +#customize.system.target.size = 2 diff --git a/targets/znews-ss/stitch/README.txt b/targets/znews-ss/stitch/README.txt index fe0c94a76..1a5abb8c4 100644 --- a/targets/znews-ss/stitch/README.txt +++ b/targets/znews-ss/stitch/README.txt @@ -1,2 +1,2 @@ -Extension: Stitch scripts must have the extension ".s"; otherwise, the -Adaptation Manager will not know to load it. +Extension: Stitch scripts must have the extension ".s"; otherwise, the +Adaptation Manager will not know to load it. diff --git a/targets/znews-ss/stitch/dosStrategies.s b/targets/znews-ss/stitch/dosStrategies.s index 8afeca081..a9cc18473 100644 --- a/targets/znews-ss/stitch/dosStrategies.s +++ b/targets/znews-ss/stitch/dosStrategies.s @@ -1,104 +1,104 @@ -/* - * Adaptation script for security attacks - */ - -module dos.strategies; -import op "org.sa.rainbow.stitch.lib.*"; -import op "org.sa.rainbow.model.acme.znn.ZNN"; -import lib "dosTactics.s"; -import lib "newssiteTactics.s"; - -//define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); - -define boolean haveMaliciousAndSuspicious = exists c : D.ZNewsClientT in M.components | (c.maliciousness >= M.SUSPICIOUS_THRESHOLD); - -define boolean unhandledMalicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness >= M.MALICIOUS_THRESHOLD) && !((exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.blackholed)) || c.captcha == -1 || c.authenticate == -1)); - -// There are people who are suspicious but haven't been throttled -define boolean unhandledSuspicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness < M.MALICIOUS_THRESHOLD && c.maliciousness > M.SUSPICIOUS_THRESHOLD) && !((exists b : D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.throttled)) || c.captcha == -1 || c.authenticate == -1)); - -// There are clients blackholed that are not malicious -define boolean cUnfairlyPenalizedClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD))); - -// There are clients throttled that are not suspicous -define boolean cUnfairlyThrottledClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSPICOUS_THRESHOLD && c.maliciousness <= M.SUSPICIOUS_THRESHOLD))); - -// We haven't captchaed -define boolean cNotChallenging = exists c : D.ZNewsLBT in M.components | (c.captchaEnabled == false); - -// Non-malicious clients are suffering high response times -define boolean cHiRespTime = exists c : T.ClientT/*,D.ZNewsClientT*/ in M.components | (c.experRespTime > M.MAX_RESPTIME); - -// There is atleast one reserve server available -define boolean serversAvailable = ZNN.availableServices(M,T.ServerT) > 0; - -/* Stop the attack by placing attackers into a blackhole. This strategy is triggered - * by the presence of an attacker and an impact on response time - */ -strategy EliminateStrategy -[ cHiRespTime && (unhandledMalicious || unhandledSuspicious) ] { - t0: (unhandledMalicious || unhandledSuspicious) -> blackholeAttacker() @[5000 /*ms*/] { - t1: (!unhandledMalicious) -> done; - t1a: (unhandledSuspicious) -> throttleSuspicious () @[5000] { - t2a: (default) -> TNULL; // in this case, we have no more steps to take - t2b: (success) -> done; - } - } - t3: (default) -> TNULL; -} - -strategy RestoreStrategy -[cUnfairlyPenalizedClients || cUnfairlyThrottledClients] { - t0: (cUnfairlyPenalizedClients) -> unblackholeAttacker () @[2000 /*ms*/] { - t1 : (!cUnfairlyPenalizedClients) -> done; - t1a: (default) -> TNULL; - } - t2 : (cUnfairlyThrottledClients) -> unthrottle () @[2000] { - t2a: (!cUnfairlyThrottledClients) -> done; - t2b: (default) -> TNULL; - } -} - -strategy Challenge [cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { - t0: (cNotChallenging) -> addCaptcha () @[5000] { - t1: (success) -> done; - t1a: (default) -> TNULL; - } - t2: (!cNotChallenging) -> forceReauthentication () @[5000] { - t3: (success) -> done; - t3a: (default) -> TNULL; - - } -} - - - -strategy DisableChallenges [!haveMaliciousAndSuspicious && !cNotChallenging] { - t0: (!cNotChallenging) -> removeCaptcha () @[1000] { - t1: (cNotChallenging) -> done; - } -} - - -strategy SimpleReduceResponseTime -[cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { - t0: (/*hiLoad*/ cHiRespTime) -> enlistServers(1) @[1000 /*ms*/] { - t1: (!cHiRespTime) -> done; - t2: (cHiRespTime) -> lowerFidelity(2, 100) @[3000 /*ms*/] { - t2a: (!cHiRespTime) -> done; - t2b: (default) -> TNULL; // in this case, we have no more steps to take - } - } -} - -/* This strategy allocates more capacity to counter the impact of a DoS attack. - */ -//strategy IncreaseCapacityStrategy -//[ styleApplies && cHiRespTime && serversAvailable] { -// t0: (/* under attack */ cHiRespTime) -> enlistServer(1) @[1000 /*ms*/] { -// t1: (!cHiRespTime) -> done; -// t1a: (default) -> TNULL; // in this case, we have no more steps to take -// } -//} - - +/* + * Adaptation script for security attacks + */ + +module dos.strategies; +import op "org.sa.rainbow.stitch.lib.*"; +import op "org.sa.rainbow.model.acme.znn.ZNN"; +import lib "dosTactics.s"; +import lib "newssiteTactics.s"; + +//define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); + +define boolean haveMaliciousAndSuspicious = exists c : D.ZNewsClientT in M.components | (c.maliciousness >= M.SUSPICIOUS_THRESHOLD); + +define boolean unhandledMalicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness >= M.MALICIOUS_THRESHOLD) && !((exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.blackholed)) || c.captcha == -1 || c.authenticate == -1)); + +// There are people who are suspicious but haven't been throttled +define boolean unhandledSuspicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness < M.MALICIOUS_THRESHOLD && c.maliciousness > M.SUSPICIOUS_THRESHOLD) && !((exists b : D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.throttled)) || c.captcha == -1 || c.authenticate == -1)); + +// There are clients blackholed that are not malicious +define boolean cUnfairlyPenalizedClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD))); + +// There are clients throttled that are not suspicous +define boolean cUnfairlyThrottledClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSPICOUS_THRESHOLD && c.maliciousness <= M.SUSPICIOUS_THRESHOLD))); + +// We haven't captchaed +define boolean cNotChallenging = exists c : D.ZNewsLBT in M.components | (c.captchaEnabled == false); + +// Non-malicious clients are suffering high response times +define boolean cHiRespTime = exists c : T.ClientT/*,D.ZNewsClientT*/ in M.components | (c.experRespTime > M.MAX_RESPTIME); + +// There is atleast one reserve server available +define boolean serversAvailable = ZNN.availableServices(M,T.ServerT) > 0; + +/* Stop the attack by placing attackers into a blackhole. This strategy is triggered + * by the presence of an attacker and an impact on response time + */ +strategy EliminateStrategy +[ cHiRespTime && (unhandledMalicious || unhandledSuspicious) ] { + t0: (unhandledMalicious || unhandledSuspicious) -> blackholeAttacker() @[5000 /*ms*/] { + t1: (!unhandledMalicious) -> done; + t1a: (unhandledSuspicious) -> throttleSuspicious () @[5000] { + t2a: (default) -> TNULL; // in this case, we have no more steps to take + t2b: (success) -> done; + } + } + t3: (default) -> TNULL; +} + +strategy RestoreStrategy +[cUnfairlyPenalizedClients || cUnfairlyThrottledClients] { + t0: (cUnfairlyPenalizedClients) -> unblackholeAttacker () @[2000 /*ms*/] { + t1 : (!cUnfairlyPenalizedClients) -> done; + t1a: (default) -> TNULL; + } + t2 : (cUnfairlyThrottledClients) -> unthrottle () @[2000] { + t2a: (!cUnfairlyThrottledClients) -> done; + t2b: (default) -> TNULL; + } +} + +strategy Challenge [cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { + t0: (cNotChallenging) -> addCaptcha () @[5000] { + t1: (success) -> done; + t1a: (default) -> TNULL; + } + t2: (!cNotChallenging) -> forceReauthentication () @[5000] { + t3: (success) -> done; + t3a: (default) -> TNULL; + + } +} + + + +strategy DisableChallenges [!haveMaliciousAndSuspicious && !cNotChallenging] { + t0: (!cNotChallenging) -> removeCaptcha () @[1000] { + t1: (cNotChallenging) -> done; + } +} + + +strategy SimpleReduceResponseTime +[cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { + t0: (/*hiLoad*/ cHiRespTime) -> enlistServers(1) @[1000 /*ms*/] { + t1: (!cHiRespTime) -> done; + t2: (cHiRespTime) -> lowerFidelity(2, 100) @[3000 /*ms*/] { + t2a: (!cHiRespTime) -> done; + t2b: (default) -> TNULL; // in this case, we have no more steps to take + } + } +} + +/* This strategy allocates more capacity to counter the impact of a DoS attack. + */ +//strategy IncreaseCapacityStrategy +//[ styleApplies && cHiRespTime && serversAvailable] { +// t0: (/* under attack */ cHiRespTime) -> enlistServer(1) @[1000 /*ms*/] { +// t1: (!cHiRespTime) -> done; +// t1a: (default) -> TNULL; // in this case, we have no more steps to take +// } +//} + + diff --git a/targets/znews-ss/stitch/dosTactics.s b/targets/znews-ss/stitch/dosTactics.s index b2db07c05..c1303bcd3 100644 --- a/targets/znews-ss/stitch/dosTactics.s +++ b/targets/znews-ss/stitch/dosTactics.s @@ -1,160 +1,160 @@ -module dos.strategies; - -import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T, ZNewsDosFam as D} ; -import op "org.sa.rainbow.stitch.lib.*"; - -//-------------------------------------------------------------------------------------------------- -// ! exists c : ClientT in self.components | (c.isMalicious and !c.is_blackholed) -// -// Failing this would cause the strategy to fire -// In the long run, isMalicious could be a float that captures the probability -// that a client is malicious -- in this case, we would have a threshold value -// -// Countermeasure #3: Black Hole the attacker(s) -// Blackholing means replying with ICMP giving reason for Black hole the attacking -// client by redirecting connections from a client -// for some period of time (i.e. black hole the traffic). -// -tactic blackholeAttacker () { - condition { - exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.blackholed))); - - // currently just checking if the client is identified as malicious. - // exists c:D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD; - } - action { - // Find the attacker. Currently, this is done by checking if client is identified as an attacker - // the blackHole() routine re-routes all traffic from a client away from the backed servers - // thereby preventing attackers from consuming ZNN resources. - // - set evilClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD}; - set blackholedClients = M.LB0.blackholed; - for (T.ClientT target : evilClients) { - blackholedClients = Set.add (blackholedClients, target.deploymentLocation); - } - M.setBlackholed (M.LB0, blackholedClients); - } - effect { - // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? - // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true - // if the client is blackholed and false otherwise - forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.blackholed))); - //forall c:T.ClientT in M.components | (c.maliciousness > M.MALICIOUS_THRESHOLD) -> !c.isBlackholed)); - } -} - -tactic unblackholeAttacker () { - condition { - exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.blackholed) && c.maliciousness <= M.MALICIOUS_THRESHOLD); - } - action { - set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.MALICIOUS_THRESHOLD}; - set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.blackholed) > 0}; - for (D.ZNewsLBT l : lbs) { - set blackholedClients = l.blackholed; - for (D.ZNewsClientT c : reformedClients) { - // Curiously, if the unblackhole is only in the op.map and - // not in the the EffectOp class, then the parameters need - // to be paired with their parameter name - // Thus, (...,"client", c.deploymentLocation) here - // compared to blackhole above, which is actually - // a method provided in the EffectOp class - blackholedClients = Set.remove (blackholedClients, c.deploymentLocation); - } - M.setBlackholed (l, blackholedClients); - } - } - effect { - forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD)); - } -} - -tactic throttleSuspicious () { - condition { - exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.throttled))); - } - action { - // Find the attacker. Currently, this is done by checking if client is identified as an attacker - // the blackHole() routine re-routes all traffic from a client away from the backed servers - // thereby preventing attackers from consuming ZNN resources. - // - set suspciousClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.SUSCPICIOUS_THRESHOLD}; - set throttledClients = M.LB0.throttled; - for (T.ClientT target : suspciousClients) { - throttledClients = Set.add (throttledClients, target.deploymentLocation); - } - M.setThrottled (M.LB0, throttledClients); - } - effect { - // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? - // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true - // if the client is blackholed and false otherwise - forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.throttled))); - } -} - -tactic unthrottle () { - condition { - exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.throttled) && c.maliciousness <= M.SUSCPICIOUS_THRESHOLD); - } - action { - set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.SUSCPICIOUS_THRESHOLD}; - set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.throttled) > 0}; - for (D.ZNewsLBT l : lbs) { - set throttledClients = l.throttled; - for (D.ZNewsClientT c : reformedClients) { - throttledClients = Set.remove (throttledClients, c.deploymentLocation); - } - M.setThrottled (l, throttledClients); - } - } - effect { - forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSCPICIOUS_THRESHOLD)); - } -} - -tactic forceReauthentication () { - condition { - true; - } - action { - for (ProxyT lb : M.components) { - M.forceReauthentication (lb); - } - } - effect { - true; - } -} - -tactic addCaptcha () { - condition { - exists lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; - } - action { - set lbs = {select l : D.ZNewsLBT in M.components | !l.captchaEnabled}; - for (D.ZNewsLBT l : lbs) { - M.setCaptchaEnabled (l, true); - } - } - effect { - forall lb:D.ZNewsLBT in M.components | lb.captchaEnabled; - } -} - -tactic removeCaptcha () { - condition { - exists lb:D.ZNewsLBT in M.components | lb.captchaEnabled; - } - action { - set lbs = {select l : D.ZNewsLBT in M.components | l.captchaEnabled}; - for (D.ZNewsLBT l : lbs) { - M.setCaptchaEnabled (l, false); - } - } - effect { - forall lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; - } -} - - +module dos.strategies; + +import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T, ZNewsDosFam as D} ; +import op "org.sa.rainbow.stitch.lib.*"; + +//-------------------------------------------------------------------------------------------------- +// ! exists c : ClientT in self.components | (c.isMalicious and !c.is_blackholed) +// +// Failing this would cause the strategy to fire +// In the long run, isMalicious could be a float that captures the probability +// that a client is malicious -- in this case, we would have a threshold value +// +// Countermeasure #3: Black Hole the attacker(s) +// Blackholing means replying with ICMP giving reason for Black hole the attacking +// client by redirecting connections from a client +// for some period of time (i.e. black hole the traffic). +// +tactic blackholeAttacker () { + condition { + exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.blackholed))); + + // currently just checking if the client is identified as malicious. + // exists c:D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD; + } + action { + // Find the attacker. Currently, this is done by checking if client is identified as an attacker + // the blackHole() routine re-routes all traffic from a client away from the backed servers + // thereby preventing attackers from consuming ZNN resources. + // + set evilClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD}; + set blackholedClients = M.LB0.blackholed; + for (T.ClientT target : evilClients) { + blackholedClients = Set.add (blackholedClients, target.deploymentLocation); + } + M.setBlackholed (M.LB0, blackholedClients); + } + effect { + // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? + // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true + // if the client is blackholed and false otherwise + forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.blackholed))); + //forall c:T.ClientT in M.components | (c.maliciousness > M.MALICIOUS_THRESHOLD) -> !c.isBlackholed)); + } +} + +tactic unblackholeAttacker () { + condition { + exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.blackholed) && c.maliciousness <= M.MALICIOUS_THRESHOLD); + } + action { + set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.MALICIOUS_THRESHOLD}; + set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.blackholed) > 0}; + for (D.ZNewsLBT l : lbs) { + set blackholedClients = l.blackholed; + for (D.ZNewsClientT c : reformedClients) { + // Curiously, if the unblackhole is only in the op.map and + // not in the the EffectOp class, then the parameters need + // to be paired with their parameter name + // Thus, (...,"client", c.deploymentLocation) here + // compared to blackhole above, which is actually + // a method provided in the EffectOp class + blackholedClients = Set.remove (blackholedClients, c.deploymentLocation); + } + M.setBlackholed (l, blackholedClients); + } + } + effect { + forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD)); + } +} + +tactic throttleSuspicious () { + condition { + exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.throttled))); + } + action { + // Find the attacker. Currently, this is done by checking if client is identified as an attacker + // the blackHole() routine re-routes all traffic from a client away from the backed servers + // thereby preventing attackers from consuming ZNN resources. + // + set suspciousClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.SUSCPICIOUS_THRESHOLD}; + set throttledClients = M.LB0.throttled; + for (T.ClientT target : suspciousClients) { + throttledClients = Set.add (throttledClients, target.deploymentLocation); + } + M.setThrottled (M.LB0, throttledClients); + } + effect { + // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? + // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true + // if the client is blackholed and false otherwise + forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.throttled))); + } +} + +tactic unthrottle () { + condition { + exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.throttled) && c.maliciousness <= M.SUSCPICIOUS_THRESHOLD); + } + action { + set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.SUSCPICIOUS_THRESHOLD}; + set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.throttled) > 0}; + for (D.ZNewsLBT l : lbs) { + set throttledClients = l.throttled; + for (D.ZNewsClientT c : reformedClients) { + throttledClients = Set.remove (throttledClients, c.deploymentLocation); + } + M.setThrottled (l, throttledClients); + } + } + effect { + forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSCPICIOUS_THRESHOLD)); + } +} + +tactic forceReauthentication () { + condition { + true; + } + action { + for (ProxyT lb : M.components) { + M.forceReauthentication (lb); + } + } + effect { + true; + } +} + +tactic addCaptcha () { + condition { + exists lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; + } + action { + set lbs = {select l : D.ZNewsLBT in M.components | !l.captchaEnabled}; + for (D.ZNewsLBT l : lbs) { + M.setCaptchaEnabled (l, true); + } + } + effect { + forall lb:D.ZNewsLBT in M.components | lb.captchaEnabled; + } +} + +tactic removeCaptcha () { + condition { + exists lb:D.ZNewsLBT in M.components | lb.captchaEnabled; + } + action { + set lbs = {select l : D.ZNewsLBT in M.components | l.captchaEnabled}; + for (D.ZNewsLBT l : lbs) { + M.setCaptchaEnabled (l, false); + } + } + effect { + forall lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; + } +} + + diff --git a/targets/znews-ss/stitch/newssiteTactics.s b/targets/znews-ss/stitch/newssiteTactics.s index 891770c68..41d6ad58a 100644 --- a/targets/znews-ss/stitch/newssiteTactics.s +++ b/targets/znews-ss/stitch/newssiteTactics.s @@ -1,118 +1,118 @@ -module newssite.tactics; - -import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T}; -import op "org.sa.rainbow.stitch.lib.*"; -import op "org.sa.rainbow.model.acme.znn.ZNN"; - - -/** - * Enlist n free servers into service pool. - * Utility: [v] R; [^] C; [<>] F - */ -tactic enlistServers (int n) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // there should be enough available server resources - ZNN.availableServices(M, T.ServerT) >= n; - } - action { - set servers = Set.randomSubset(ZNN.findServices(M, T.ServerT), n); - for (T.ServerT freeSvr : servers) { - M.enableServer (freeSvr, true); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Deactivate n servers from service pool into free pool. - * Utility: [^] R; [v] C; [<>] F - */ -tactic dischargeServers (int n) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there should be enough servers to discharge - Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; - } - action { - set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; - set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); - for (T.ServerT s : subLowUtilSvrs) { - M.enableServer (s, false); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Lowers fidelity by integral steps for percent of requests. - * Utility: [v] R; [v] C; [v] F - */ -tactic lowerFidelity (int step, float fracReq) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // exists server with fidelity to lower - exists s : T.ServerT in M.components | s.fidelity > step; - } - action { - // retrieve set of servers who still have enough fidelity grade to lower - set servers = { select s : T.ServerT in M.components | s.fidelity > step }; - for (T.ServerT s : servers) { - M.setFidelity(s, s.fidelity - step); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Raises fidelity by integral steps for percent of requests. - * Utility: [^] R; [^] C; [^] F - */ -tactic raiseFidelity (int step, float fracReq) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there exists some client with below low-threshold response time - exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - } - action { - // first find the lowest fidelity set - set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; -/* smarter way of doing things... - int lowestFidelity = M.MAX_FIDELITY_LEVEL; - for (T.ServerT s : servers) { - if (s.fidelity < lowestFidelity) { - lowestFidelity = s.fidelity; - } - } - // find only servers with this lowest fidelity setting, and raise fidelity - servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; -*/ - for (T.ServerT s : servers) { - M.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/* - T5) delayClients(set clients) - utility: [^] R; [v] C; [v] F - T6) blockClients(set clients) - utility: [^] R; [v] C; [v] F -*/ +module newssite.tactics; + +import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T}; +import op "org.sa.rainbow.stitch.lib.*"; +import op "org.sa.rainbow.model.acme.znn.ZNN"; + + +/** + * Enlist n free servers into service pool. + * Utility: [v] R; [^] C; [<>] F + */ +tactic enlistServers (int n) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // there should be enough available server resources + ZNN.availableServices(M, T.ServerT) >= n; + } + action { + set servers = Set.randomSubset(ZNN.findServices(M, T.ServerT), n); + for (T.ServerT freeSvr : servers) { + M.enableServer (freeSvr, true); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Deactivate n servers from service pool into free pool. + * Utility: [^] R; [v] C; [<>] F + */ +tactic dischargeServers (int n) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there should be enough servers to discharge + Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; + } + action { + set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; + set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); + for (T.ServerT s : subLowUtilSvrs) { + M.enableServer (s, false); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Lowers fidelity by integral steps for percent of requests. + * Utility: [v] R; [v] C; [v] F + */ +tactic lowerFidelity (int step, float fracReq) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // exists server with fidelity to lower + exists s : T.ServerT in M.components | s.fidelity > step; + } + action { + // retrieve set of servers who still have enough fidelity grade to lower + set servers = { select s : T.ServerT in M.components | s.fidelity > step }; + for (T.ServerT s : servers) { + M.setFidelity(s, s.fidelity - step); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Raises fidelity by integral steps for percent of requests. + * Utility: [^] R; [^] C; [^] F + */ +tactic raiseFidelity (int step, float fracReq) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there exists some client with below low-threshold response time + exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + } + action { + // first find the lowest fidelity set + set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; +/* smarter way of doing things... + int lowestFidelity = M.MAX_FIDELITY_LEVEL; + for (T.ServerT s : servers) { + if (s.fidelity < lowestFidelity) { + lowestFidelity = s.fidelity; + } + } + // find only servers with this lowest fidelity setting, and raise fidelity + servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; +*/ + for (T.ServerT s : servers) { + M.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/* + T5) delayClients(set clients) + utility: [^] R; [v] C; [v] F + T6) blockClients(set clients) + utility: [^] R; [v] C; [v] F +*/ diff --git a/targets/znews-ss/stitch/old/newssiteStrategies.s b/targets/znews-ss/stitch/old/newssiteStrategies.s index 3eef21719..55f3bf8a9 100644 --- a/targets/znews-ss/stitch/old/newssiteStrategies.s +++ b/targets/znews-ss/stitch/old/newssiteStrategies.s @@ -1,117 +1,117 @@ -/* - * Adaptation script for the News Site example. - */ - -module newssite.strategies; - -import lib "newssiteTactics.s"; - -define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); -define boolean cViolation = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - -define set servers = {select s : T.ServerT in M.components | true}; -define set unhappyClients = {select c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME}; -define int numClients = Set.size({select c : T.ClientT in M.components | true}); -define int numUnhappy = Set.size(unhappyClients); -define float numUnhappyFloat = 1.0*numUnhappy; - -define boolean hiLoad = exists s : T.ServerT in M.components | s.load > M.MAX_UTIL; -define boolean hiRespTime = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; -define boolean lowRespTime = exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - -define float totalCost = Model.sumOverProperty("cost", servers); -define boolean hiCost = totalCost >= M.THRESHOLD_COST; - -define float avgFidelity = Model.sumOverProperty("fidelity", servers) / Set.size(servers); -define boolean lowFi = avgFidelity < M.THRESHOLD_FIDELITY; - -/* This Strategy is simple in that, while it encounters any anomaly in - * experienced response time, it firsts enlists one new server, then lowers - * fidelity one step, and quits - */ -strategy SimpleReduceResponseTime -[ styleApplies && cViolation ] { - t0: (/*hiLoad*/ cViolation) -> enlistServers(1) @[1000 /*ms*/] { - t1: (!cViolation) -> done; - t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[3000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> TNULL; // in this case, we have no more steps to take - } - } -} - -/* This Strategy is smarter in that it looks for a percentage of clients with - * anomalous experienced response time, in which case it enlists a few servers - * in sequence, then lowers fidelity a few steps, then starts delaying Clients - */ -strategy SmarterReduceResponseTime -[ styleApplies && cViolation ] { - define boolean unhappy = numUnhappyFloat/numClients > M.TOLERABLE_PERCENT_UNHAPPY; - - t0: (unhappy) -> enlistServers(1) @[500 /*ms*/] { - t1: (!cViolation) -> done; - t2: (unhappy) -> enlistServers(1) @[2000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (unhappy) -> lowerFidelity(2, 100) @[2000 /*ms*/] { - t2b1: (!cViolation) -> done; - t2b2: (unhappy) -> do[1] t2; - t2b3: (default) -> TNULL; // in this case, we have no more steps to take - } - } - } -} - -/* This Strategy (experimental!) has the sophistication of reducing fidelity - * for a percentage of requests depending on percentage of unhappy clients - */ -strategy SophisticatedReduceResponseTime -[ styleApplies && cViolation && M.SUPPORT_FRACTION_GRADIENT ] { - define boolean unhappy1 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_1; // e.g., 10% - define boolean unhappy2 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_2; // e.g., 25% - define boolean unhappy3 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_3; // e.g., 50% - - t1: (hiLoad) -> enlistServers(2) @[500 /*ms*/] { - t1a: (!cViolation) -> done; - t1b: (default) -> TNULL; - } - t2: (unhappy1) -> lowerFidelity(1, M.FRACTION_GRADIENT_1) @[500 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> do[1] t1; - } - t3: (unhappy2) -> lowerFidelity(2, M.FRACTION_GRADIENT_2) @[500 /*ms*/] { - t3a: (!cViolation) -> done; - t3b: (default) -> do[1] t1; - } - t4: (unhappy3) -> lowerFidelity(4, M.FRACTION_GRADIENT_3) @[500 /*ms*/] { - t4a: (!cViolation) -> done; - t4b: (unhappy3) -> enlistServers(2) @[1000 /*ms*/] { - t4b1: (!cViolation) -> done; - t4b2: (default) -> do[1] t1; - } - t4c: (default) -> do[1] t1; - } -} - -/* This Strategy is triggered by the total server costs rising above acceptable - * threshold; this Strategy reduces the number of active servers - */ -strategy ReduceOverallCost -[ styleApplies && hiCost ] { - t0: (hiCost) -> dischargeServers(1) @[2000 /*ms*/] { - t1: (!hiCost) -> done; - t2: (lowRespTime && hiCost) -> do[2] t0; - t3: (default) -> TNULL; - } -} - -/* This Strategy is triggered by overall fidelity being below acceptable - * threshold; this Strategy raises the fidelity of the servers - */ -strategy ImproveOverallFidelity -[ styleApplies && lowFi ] { - t0: (lowFi) -> raiseFidelity(2, 100) @[800 /*ms*/] { - t1: (!lowFi) -> done; - t2: (lowRespTime && lowFi) -> do[1] t0; - t3: (default) -> TNULL; - } -} +/* + * Adaptation script for the News Site example. + */ + +module newssite.strategies; + +import lib "newssiteTactics.s"; + +define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); +define boolean cViolation = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + +define set servers = {select s : T.ServerT in M.components | true}; +define set unhappyClients = {select c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME}; +define int numClients = Set.size({select c : T.ClientT in M.components | true}); +define int numUnhappy = Set.size(unhappyClients); +define float numUnhappyFloat = 1.0*numUnhappy; + +define boolean hiLoad = exists s : T.ServerT in M.components | s.load > M.MAX_UTIL; +define boolean hiRespTime = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; +define boolean lowRespTime = exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + +define float totalCost = Model.sumOverProperty("cost", servers); +define boolean hiCost = totalCost >= M.THRESHOLD_COST; + +define float avgFidelity = Model.sumOverProperty("fidelity", servers) / Set.size(servers); +define boolean lowFi = avgFidelity < M.THRESHOLD_FIDELITY; + +/* This Strategy is simple in that, while it encounters any anomaly in + * experienced response time, it firsts enlists one new server, then lowers + * fidelity one step, and quits + */ +strategy SimpleReduceResponseTime +[ styleApplies && cViolation ] { + t0: (/*hiLoad*/ cViolation) -> enlistServers(1) @[1000 /*ms*/] { + t1: (!cViolation) -> done; + t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[3000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> TNULL; // in this case, we have no more steps to take + } + } +} + +/* This Strategy is smarter in that it looks for a percentage of clients with + * anomalous experienced response time, in which case it enlists a few servers + * in sequence, then lowers fidelity a few steps, then starts delaying Clients + */ +strategy SmarterReduceResponseTime +[ styleApplies && cViolation ] { + define boolean unhappy = numUnhappyFloat/numClients > M.TOLERABLE_PERCENT_UNHAPPY; + + t0: (unhappy) -> enlistServers(1) @[500 /*ms*/] { + t1: (!cViolation) -> done; + t2: (unhappy) -> enlistServers(1) @[2000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (unhappy) -> lowerFidelity(2, 100) @[2000 /*ms*/] { + t2b1: (!cViolation) -> done; + t2b2: (unhappy) -> do[1] t2; + t2b3: (default) -> TNULL; // in this case, we have no more steps to take + } + } + } +} + +/* This Strategy (experimental!) has the sophistication of reducing fidelity + * for a percentage of requests depending on percentage of unhappy clients + */ +strategy SophisticatedReduceResponseTime +[ styleApplies && cViolation && M.SUPPORT_FRACTION_GRADIENT ] { + define boolean unhappy1 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_1; // e.g., 10% + define boolean unhappy2 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_2; // e.g., 25% + define boolean unhappy3 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_3; // e.g., 50% + + t1: (hiLoad) -> enlistServers(2) @[500 /*ms*/] { + t1a: (!cViolation) -> done; + t1b: (default) -> TNULL; + } + t2: (unhappy1) -> lowerFidelity(1, M.FRACTION_GRADIENT_1) @[500 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> do[1] t1; + } + t3: (unhappy2) -> lowerFidelity(2, M.FRACTION_GRADIENT_2) @[500 /*ms*/] { + t3a: (!cViolation) -> done; + t3b: (default) -> do[1] t1; + } + t4: (unhappy3) -> lowerFidelity(4, M.FRACTION_GRADIENT_3) @[500 /*ms*/] { + t4a: (!cViolation) -> done; + t4b: (unhappy3) -> enlistServers(2) @[1000 /*ms*/] { + t4b1: (!cViolation) -> done; + t4b2: (default) -> do[1] t1; + } + t4c: (default) -> do[1] t1; + } +} + +/* This Strategy is triggered by the total server costs rising above acceptable + * threshold; this Strategy reduces the number of active servers + */ +strategy ReduceOverallCost +[ styleApplies && hiCost ] { + t0: (hiCost) -> dischargeServers(1) @[2000 /*ms*/] { + t1: (!hiCost) -> done; + t2: (lowRespTime && hiCost) -> do[2] t0; + t3: (default) -> TNULL; + } +} + +/* This Strategy is triggered by overall fidelity being below acceptable + * threshold; this Strategy raises the fidelity of the servers + */ +strategy ImproveOverallFidelity +[ styleApplies && lowFi ] { + t0: (lowFi) -> raiseFidelity(2, 100) @[800 /*ms*/] { + t1: (!lowFi) -> done; + t2: (lowRespTime && lowFi) -> do[1] t0; + t3: (default) -> TNULL; + } +} diff --git a/targets/znews-ss/stitch/old/newssiteTactics.s b/targets/znews-ss/stitch/old/newssiteTactics.s index a0efdb740..0684601ef 100644 --- a/targets/znews-ss/stitch/old/newssiteTactics.s +++ b/targets/znews-ss/stitch/old/newssiteTactics.s @@ -1,118 +1,118 @@ -module newssite.tactics; - -import model "ZNewsSys.acme" { ZNewsSys as M, ZNewsFam as T }; -import op "znews1.operator.EffectOp" { EffectOp as S }; -import op "org.sa.rainbow.stitch.lib.*"; - - -/** - * Enlist n free servers into service pool. - * Utility: [v] R; [^] C; [<>] F - */ -tactic enlistServers (int n) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // there should be enough available server resources - Model.availableServices(T.ServerT) >= n; - } - action { - set servers = Set.randomSubset(Model.findServices(T.ServerT), n); - for (T.ServerT freeSvr : servers) { - S.activateServer(freeSvr); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Deactivate n servers from service pool into free pool. - * Utility: [^] R; [v] C; [<>] F - */ -tactic dischargeServers (int n) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there should be enough servers to discharge - Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; - } - action { - set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; - set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); - for (T.ServerT s : subLowUtilSvrs) { - S.deactivateServer(s); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Lowers fidelity by integral steps for percent of requests. - * Utility: [v] R; [v] C; [v] F - */ -tactic lowerFidelity (int step, float fracReq) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // exists server with fidelity to lower - exists s : T.ServerT in M.components | s.fidelity > step; - } - action { - // retrieve set of servers who still have enough fidelity grade to lower - set servers = { select s : T.ServerT in M.components | s.fidelity > step }; - for (T.ServerT s : servers) { - S.setFidelity(s, s.fidelity - step); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Raises fidelity by integral steps for percent of requests. - * Utility: [^] R; [^] C; [^] F - */ -tactic raiseFidelity (int step, float fracReq) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there exists some client with below low-threshold response time - exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - } - action { - // first find the lowest fidelity set - set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; -/* smarter way of doing things... - int lowestFidelity = M.MAX_FIDELITY_LEVEL; - for (T.ServerT s : servers) { - if (s.fidelity < lowestFidelity) { - lowestFidelity = s.fidelity; - } - } - // find only servers with this lowest fidelity setting, and raise fidelity - servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; -*/ - for (T.ServerT s : servers) { - S.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/* - T5) delayClients(set clients) - utility: [^] R; [v] C; [v] F - T6) blockClients(set clients) - utility: [^] R; [v] C; [v] F -*/ +module newssite.tactics; + +import model "ZNewsSys.acme" { ZNewsSys as M, ZNewsFam as T }; +import op "znews1.operator.EffectOp" { EffectOp as S }; +import op "org.sa.rainbow.stitch.lib.*"; + + +/** + * Enlist n free servers into service pool. + * Utility: [v] R; [^] C; [<>] F + */ +tactic enlistServers (int n) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // there should be enough available server resources + Model.availableServices(T.ServerT) >= n; + } + action { + set servers = Set.randomSubset(Model.findServices(T.ServerT), n); + for (T.ServerT freeSvr : servers) { + S.activateServer(freeSvr); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Deactivate n servers from service pool into free pool. + * Utility: [^] R; [v] C; [<>] F + */ +tactic dischargeServers (int n) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there should be enough servers to discharge + Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; + } + action { + set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; + set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); + for (T.ServerT s : subLowUtilSvrs) { + S.deactivateServer(s); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Lowers fidelity by integral steps for percent of requests. + * Utility: [v] R; [v] C; [v] F + */ +tactic lowerFidelity (int step, float fracReq) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // exists server with fidelity to lower + exists s : T.ServerT in M.components | s.fidelity > step; + } + action { + // retrieve set of servers who still have enough fidelity grade to lower + set servers = { select s : T.ServerT in M.components | s.fidelity > step }; + for (T.ServerT s : servers) { + S.setFidelity(s, s.fidelity - step); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Raises fidelity by integral steps for percent of requests. + * Utility: [^] R; [^] C; [^] F + */ +tactic raiseFidelity (int step, float fracReq) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there exists some client with below low-threshold response time + exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + } + action { + // first find the lowest fidelity set + set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; +/* smarter way of doing things... + int lowestFidelity = M.MAX_FIDELITY_LEVEL; + for (T.ServerT s : servers) { + if (s.fidelity < lowestFidelity) { + lowestFidelity = s.fidelity; + } + } + // find only servers with this lowest fidelity setting, and raise fidelity + servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; +*/ + for (T.ServerT s : servers) { + S.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/* + T5) delayClients(set clients) + utility: [^] R; [v] C; [v] F + T6) blockClients(set clients) + utility: [^] R; [v] C; [v] F +*/ diff --git a/targets/znews-ss/stitch/utilities - old.yml b/targets/znews-ss/stitch/utilities - old.yml index ba67ea53a..2cbdfbc12 100644 --- a/targets/znews-ss/stitch/utilities - old.yml +++ b/targets/znews-ss/stitch/utilities - old.yml @@ -1,136 +1,136 @@ -# Created June 30, 2012 (Jeff Gennari) -# -# Utility curves, defined as X:Y pairs, where X is value of the -# dimension and Y is the utility in the range [0,1] - -# DoS utilities. There are three quality dimensions to a DoS attack: -# the response time of clients, the presence of an attacker (currently -# a true/false value), and the cost of adding an additional server. - - # Response time taken directly from existing ZNN example. -utilities: - uG: - label: "Average Response Time to Good Clients" - mapping: "[EAvg]!NormalT.experRespTime" - description: "Good Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" - utility: - 0: 1.00 - 100: 1.00 - 200: 0.99 - 500: 0.90 - 1000: 0.75 - 1500: 0.50 - 2000: 0.25 - 4000: 0.00 - - uB: - label: "Average Response to Malicious Clients" - mapping: "[EAvg]!MaliciousT.experRespTime" - description: "Malicious Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" - utility: - 0: 0.00 - 4000: 0.50 - 30000: 1.00 - - uC: - label: "Average Server Cost" - mapping: "[EAvg]ServerT.cost" - description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers" - utility: - 0: 1.00 - 1: 0.90 - 5: 0.20 - 10: 0.00 - - uSF: - label: "Historical Strategy Failure" - mapping: "[EAvg]Strategy.rateFailure" - description: "Rate of failure, in fraction, of a strategy; utility has no effect if strategy history is not kept" - utility: - 0: 1.00 - 0.5: 0.01 - 1: 0.00 - -# scenario 1: Maintaining acceptable response time to good clients most important -# scenario 2: Eliminating malicious clients is most important -# scenario 3: Keeping costs down is most important - -weights: - scenario 1: - uG: 0.7 - uB: 0.3 - uC: 0.1 - uSF: 0.0 - - scenario 2: - uG: 0.3 - uB: 0.7 - uC: 0.1 - uSF: 0.0 - - scenario 2: - uG: 0.4 - uC: 0.4 - uB: 0.2 - uSF: 0.0 - -vectors: - - # Deny attacker service by putting him/her in a blackhole. This - # should reduce response time for all but the attacker, reduce - # disruption cost to the servers, but increase the cost unit of - # taking the wrong client offline - - # Utility: [v]R; [v]A; (reduce R by 1000 ms, reduce the number - # of attackers by 1 unit) - blackholeAttacker: - uB: +30000 - uG: -1000 - uC: 0 - - unblackholeAttacker: - uB: 0 - uG: 0 - uC: 0 - - # Adding more servers should reduce response time, have no impact on - # the number of attackers, and increase the server cost (by adding - # additional servers). - - # Utility: [v]R; [<>]A; (reduce R by 1000 ms, no change in the - # number of attackers) - enlistServers: - uG: -1000 - uB: -1000 - uC: +1 - - # Utility: [v]R; [<>]A; [^]C (reduce R by 1000 ms, no change in the - # number of attackers) - dischargeServers: - uG: +1000 - uB: +1000 - uC: -1 - - addCaptcha: - uG: -250 - uB: +30000 - uC: +0.5 - - removeCaptcha: - uG: +250 - uB: -30000 - uC: -0.5 - - lowerFidelity: - uG: -500 - uB: -500 - uC: -0.10 -# Utility: [^] R; [^] C; [^] F - raiseFidelity: - uG: +500 - uB: +500 - uC: +0.10 - - - - +# Created June 30, 2012 (Jeff Gennari) +# +# Utility curves, defined as X:Y pairs, where X is value of the +# dimension and Y is the utility in the range [0,1] + +# DoS utilities. There are three quality dimensions to a DoS attack: +# the response time of clients, the presence of an attacker (currently +# a true/false value), and the cost of adding an additional server. + + # Response time taken directly from existing ZNN example. +utilities: + uG: + label: "Average Response Time to Good Clients" + mapping: "[EAvg]!NormalT.experRespTime" + description: "Good Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" + utility: + 0: 1.00 + 100: 1.00 + 200: 0.99 + 500: 0.90 + 1000: 0.75 + 1500: 0.50 + 2000: 0.25 + 4000: 0.00 + + uB: + label: "Average Response to Malicious Clients" + mapping: "[EAvg]!MaliciousT.experRespTime" + description: "Malicious Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" + utility: + 0: 0.00 + 4000: 0.50 + 30000: 1.00 + + uC: + label: "Average Server Cost" + mapping: "[EAvg]ServerT.cost" + description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers" + utility: + 0: 1.00 + 1: 0.90 + 5: 0.20 + 10: 0.00 + + uSF: + label: "Historical Strategy Failure" + mapping: "[EAvg]Strategy.rateFailure" + description: "Rate of failure, in fraction, of a strategy; utility has no effect if strategy history is not kept" + utility: + 0: 1.00 + 0.5: 0.01 + 1: 0.00 + +# scenario 1: Maintaining acceptable response time to good clients most important +# scenario 2: Eliminating malicious clients is most important +# scenario 3: Keeping costs down is most important + +weights: + scenario 1: + uG: 0.7 + uB: 0.3 + uC: 0.1 + uSF: 0.0 + + scenario 2: + uG: 0.3 + uB: 0.7 + uC: 0.1 + uSF: 0.0 + + scenario 2: + uG: 0.4 + uC: 0.4 + uB: 0.2 + uSF: 0.0 + +vectors: + + # Deny attacker service by putting him/her in a blackhole. This + # should reduce response time for all but the attacker, reduce + # disruption cost to the servers, but increase the cost unit of + # taking the wrong client offline + + # Utility: [v]R; [v]A; (reduce R by 1000 ms, reduce the number + # of attackers by 1 unit) + blackholeAttacker: + uB: +30000 + uG: -1000 + uC: 0 + + unblackholeAttacker: + uB: 0 + uG: 0 + uC: 0 + + # Adding more servers should reduce response time, have no impact on + # the number of attackers, and increase the server cost (by adding + # additional servers). + + # Utility: [v]R; [<>]A; (reduce R by 1000 ms, no change in the + # number of attackers) + enlistServers: + uG: -1000 + uB: -1000 + uC: +1 + + # Utility: [v]R; [<>]A; [^]C (reduce R by 1000 ms, no change in the + # number of attackers) + dischargeServers: + uG: +1000 + uB: +1000 + uC: -1 + + addCaptcha: + uG: -250 + uB: +30000 + uC: +0.5 + + removeCaptcha: + uG: +250 + uB: -30000 + uC: -0.5 + + lowerFidelity: + uG: -500 + uB: -500 + uC: -0.10 +# Utility: [^] R; [^] C; [^] F + raiseFidelity: + uG: +500 + uB: +500 + uC: +0.10 + + + + diff --git a/targets/znews-ss/stitch/utilities-orig.yml b/targets/znews-ss/stitch/utilities-orig.yml index 16e009da2..d5ae13f28 100644 --- a/targets/znews-ss/stitch/utilities-orig.yml +++ b/targets/znews-ss/stitch/utilities-orig.yml @@ -1,94 +1,94 @@ -# Created June 30, 2012 (Jeff Gennari) -# -# Utility curves, defined as X:Y pairs, where X is value of the -# dimension and Y is the utility in the range [0,1] - -# DoS utilities. There are three quality dimensions to a DoS attack: -# the response time of clients, the presence of an attacker (currently -# a true/false value), and the cost of adding an additional server. - - # Response time taken directly from existing ZNN example. -utilities: - uR: - label: "Average Response Time" - mapping: "[EAvg]ClientT.experRespTime" - description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" - utility: - 0: 1.00 - 100: 1.00 - 200: 0.99 - 500: 0.90 - 1000: 0.75 - 1500: 0.50 - 2000: 0.25 - 4000: 0.00 - - # Indication of whether an attacker is present in the system. Zero - # attackers makes us happy. One attacker makes us sad. - uA: - label: "Attacker Known" - mapping: "ClientT.maliciousness" - description: "Indicates whether an attacker is connected to the system. Currently, this is a binary value. That is, there is either one attacker or there are no attackers." - utility: - 0: 1.00 - 1: 0.00 - - uSF: - label: "Historical Strategy Failure" - mapping: "[EAvg]Strategy.rateFailure" - description: "Rate of failure, in fraction, of a strategy; utility has no effect if strategy history is not kept" - utility: - 0: 1.00 - 0.5: 0.01 - 1: 0.00 - -# scenario 1: Maintaining acceptable response time most important -# scenario 2: Identifying the attacker most important - -weights: - scenario 1: - uR: 0.7 - uA: 0.3 - uSF: 0.0 - - scenario 2: - uR: 0.7 - uA: 0.3 - uSF: 0.0 - -vectors: - - # Deny attacker service by putting him/her in a blackhole. This - # should reduce response time for all but the attacker, reduce - # disruption cost to the servers, but increase the cost unit of - # taking the wrong client offline - - # Utility: [v]R; [v]A; (reduce R by 1000 ms, reduce the number - # of attackers by 1 unit) - blackholeAttacker: - uR: -1000 - uA: -1 - - unblackholeAttacker: - uR: 0 - uA: -1 - - # Adding more servers should reduce response time, have no impact on - # the number of attackers, and increase the server cost (by adding - # additional servers). - - # Utility: [v]R; [<>]A; (reduce R by 1000 ms, no change in the - # number of attackers) - enlistServers: - uR: -1000 - uA: 0 - - # Utility: [v]R; [<>]A; [^]C (reduce R by 1000 ms, no change in the - # number of attackers) - dischargeServers: - uR: +1000 - uA: 0 - - - - +# Created June 30, 2012 (Jeff Gennari) +# +# Utility curves, defined as X:Y pairs, where X is value of the +# dimension and Y is the utility in the range [0,1] + +# DoS utilities. There are three quality dimensions to a DoS attack: +# the response time of clients, the presence of an attacker (currently +# a true/false value), and the cost of adding an additional server. + + # Response time taken directly from existing ZNN example. +utilities: + uR: + label: "Average Response Time" + mapping: "[EAvg]ClientT.experRespTime" + description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" + utility: + 0: 1.00 + 100: 1.00 + 200: 0.99 + 500: 0.90 + 1000: 0.75 + 1500: 0.50 + 2000: 0.25 + 4000: 0.00 + + # Indication of whether an attacker is present in the system. Zero + # attackers makes us happy. One attacker makes us sad. + uA: + label: "Attacker Known" + mapping: "ClientT.maliciousness" + description: "Indicates whether an attacker is connected to the system. Currently, this is a binary value. That is, there is either one attacker or there are no attackers." + utility: + 0: 1.00 + 1: 0.00 + + uSF: + label: "Historical Strategy Failure" + mapping: "[EAvg]Strategy.rateFailure" + description: "Rate of failure, in fraction, of a strategy; utility has no effect if strategy history is not kept" + utility: + 0: 1.00 + 0.5: 0.01 + 1: 0.00 + +# scenario 1: Maintaining acceptable response time most important +# scenario 2: Identifying the attacker most important + +weights: + scenario 1: + uR: 0.7 + uA: 0.3 + uSF: 0.0 + + scenario 2: + uR: 0.7 + uA: 0.3 + uSF: 0.0 + +vectors: + + # Deny attacker service by putting him/her in a blackhole. This + # should reduce response time for all but the attacker, reduce + # disruption cost to the servers, but increase the cost unit of + # taking the wrong client offline + + # Utility: [v]R; [v]A; (reduce R by 1000 ms, reduce the number + # of attackers by 1 unit) + blackholeAttacker: + uR: -1000 + uA: -1 + + unblackholeAttacker: + uR: 0 + uA: -1 + + # Adding more servers should reduce response time, have no impact on + # the number of attackers, and increase the server cost (by adding + # additional servers). + + # Utility: [v]R; [<>]A; (reduce R by 1000 ms, no change in the + # number of attackers) + enlistServers: + uR: -1000 + uA: 0 + + # Utility: [v]R; [<>]A; [^]C (reduce R by 1000 ms, no change in the + # number of attackers) + dischargeServers: + uR: +1000 + uA: 0 + + + + diff --git a/targets/znews-ss/stitch/utilities.yml b/targets/znews-ss/stitch/utilities.yml index 057e48819..b1afa7129 100644 --- a/targets/znews-ss/stitch/utilities.yml +++ b/targets/znews-ss/stitch/utilities.yml @@ -1,151 +1,151 @@ -# Created October 22nd, 2013 (Javier Camara) -# -# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y -# is the utility in the range [0,1] -# -# History: -# - [JC 2013.10.22] Created file, defined utilities for Dos Attack Demo. -# - [JC 2013.11.1] Added user annoyance to the utility profile. -model: - name: ZNewsSys - type: Acme -utilities: - uR: - label: "Average Response Time" - mapping: "[EAvg]ClientT.experRespTime" - description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" - utility: - 0: 1.00 - 100: 1.00 - 200: 0.99 - 500: 0.90 - 1000: 0.75 - 1500: 0.50 - 2000: 0.25 - 4000: 0.00 - uC: - label: "Average Server Cost" - mapping: "[EXPR]size(/self/components:ServerT[isArchEnabled])" - description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers. Adapted to a 3-server configuration." - utility: - 0: 1.00 - 1: 0.90 - 2: 0.30 - 3: 0.10 - uM: - label: "Malicious Clients" - mapping: "[EXPR](2*size(/self/components:PotentiallyMaliciousT[maliciousness > self.MALICIOUS_THRESHOLD]))/(size(/self/components:PotentiallyMaliciousT)+1)*100" - description: "Percentage of malicious clients." - utility: - 0: 1.00 - 5: 1.00 - 20: 0.80 - 50: 0.40 - 70: 0.00 - uA: - label: "Average User Annoyance" - mapping: "[EAvg]ClientT.annoyance" - description: "Client experienced annoyance level, should be defined as an int property 'ClientT.annoyance' in the architecture, with a range 0-100" - utility: - 0: 1.00 - 100: 0.00 - -# Weighted utility preferences, each set should sum to 1. -# Three scenarios: -# 1.) Priority is given to eliminating malicious clients. -# 2.) Priority is given to optimizing good client experience (both serving them in a timely manner, and minimizing annoyance). -# 3.) Priority is given to keeping cost down. -# Note: Original Weight of uR is now split 50/50% among uR and uA in every scenario. -weights: - scenario 1: - uR: 0.15 - uM: 0.6 - uC: 0.1 - uA: 0.15 - scenario 2: - uR: 0.3 - uM: 0.3 - uC: 0.1 - uA: 0.3 - scenario 3: - uR: 0.2 - uM: 0.2 - uC: 0.4 - uA: 0.2 - -# Tactic quality attribute vectors -# -vectors: -# Utility: [^] R; [<>] M; [v] C; [<>]A -# assume each server will drop response time by 1000 ms and increase cost by 1 unit - enlistServers: - uR: -1000 - uM: 0 - uC: +1.00 - uA: 0 - -# Utility: [^] R; [<>] M; [^] C; [v]A -# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit, increases annoyance of users 5% for low-quality service - lowerFidelity: - uR: -500 - uM: 0 - uC: -0.10 - uA: +5 - -# Utility: [^] R; [^] M; [v] C; [v]A -# assume that adding the captcha reduces response time by 250 ms, reduces level of malicious users by 90%, increases cost 1/2 unit, and increases user annoyance by 50% - addCaptcha: - uR: -250 - uM: -90 - uC: +0.50 - uA: +50 - -# Utility: [^] R; [^] M; [<>] C; [v]A -# assume that forcing users to reauthenticate reduces response time by 250 ms, reduces level of malicious users by 70%, and increases user annoyance by 50% - forceReauthentication: - uR: -250 - uM: -70 - uC: 0.00 - uA: +50 - -# Utility: [^] R; [^] M; [<>] C; [v]A -# assume that blackholing potential attackers reduces response time by 1000 ms, reduces level of malicious users by 100%, and increases user annoyance by 100% - blackholeAttacker: - uR: -1000 - uM: -100 - uC: 0.00 - uA: +50 - -# Utility: [^] R; [<>] M; [<>] C; [v]A -# assume that throttling suspicious clients reduces response time by 500 ms, and increases user annoyance by 50% - throttleSuspicious: - uR: -500 -# uM may need to change if we decide to substitute % of malicious clients by % of malicious user throughput - uM: 0 - uC: 0.00 - uA: +25 - -# Utility: [^] R; [<>] M; [^] C; [^]A -# assume that removing the captcha reduces cost 1/2 unit, and reduces user annoyance by 50% - removeCaptcha: - uR: -500 - uM: 0 - uC: -0.50 - uA: -50 - -# Utility: [<>] R; [<>] M; [<>] C; [^]A -# assume that removing the captcha reduces user annoyance by 100% - unblackholeAttacker: - uR: 0 - uM: 0 - uC: 0.00 - uA: -100 - -# Utility: [<>] R; [<>] M; [<>] C; [^]A -# assume that unthrottling suspicious clients reduces user annoyance by 50% - unthrottle: - uR: 0 - uM: 0 - uC: 0.00 - uA: -50 - +# Created October 22nd, 2013 (Javier Camara) +# +# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y +# is the utility in the range [0,1] +# +# History: +# - [JC 2013.10.22] Created file, defined utilities for Dos Attack Demo. +# - [JC 2013.11.1] Added user annoyance to the utility profile. +model: + name: ZNewsSys + type: Acme +utilities: + uR: + label: "Average Response Time" + mapping: "[EAvg]ClientT.experRespTime" + description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" + utility: + 0: 1.00 + 100: 1.00 + 200: 0.99 + 500: 0.90 + 1000: 0.75 + 1500: 0.50 + 2000: 0.25 + 4000: 0.00 + uC: + label: "Average Server Cost" + mapping: "[EXPR]size(/self/components:ServerT[isArchEnabled])" + description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers. Adapted to a 3-server configuration." + utility: + 0: 1.00 + 1: 0.90 + 2: 0.30 + 3: 0.10 + uM: + label: "Malicious Clients" + mapping: "[EXPR](2*size(/self/components:PotentiallyMaliciousT[maliciousness > self.MALICIOUS_THRESHOLD]))/(size(/self/components:PotentiallyMaliciousT)+1)*100" + description: "Percentage of malicious clients." + utility: + 0: 1.00 + 5: 1.00 + 20: 0.80 + 50: 0.40 + 70: 0.00 + uA: + label: "Average User Annoyance" + mapping: "[EAvg]ClientT.annoyance" + description: "Client experienced annoyance level, should be defined as an int property 'ClientT.annoyance' in the architecture, with a range 0-100" + utility: + 0: 1.00 + 100: 0.00 + +# Weighted utility preferences, each set should sum to 1. +# Three scenarios: +# 1.) Priority is given to eliminating malicious clients. +# 2.) Priority is given to optimizing good client experience (both serving them in a timely manner, and minimizing annoyance). +# 3.) Priority is given to keeping cost down. +# Note: Original Weight of uR is now split 50/50% among uR and uA in every scenario. +weights: + scenario 1: + uR: 0.15 + uM: 0.6 + uC: 0.1 + uA: 0.15 + scenario 2: + uR: 0.3 + uM: 0.3 + uC: 0.1 + uA: 0.3 + scenario 3: + uR: 0.2 + uM: 0.2 + uC: 0.4 + uA: 0.2 + +# Tactic quality attribute vectors +# +vectors: +# Utility: [^] R; [<>] M; [v] C; [<>]A +# assume each server will drop response time by 1000 ms and increase cost by 1 unit + enlistServers: + uR: -1000 + uM: 0 + uC: +1.00 + uA: 0 + +# Utility: [^] R; [<>] M; [^] C; [v]A +# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit, increases annoyance of users 5% for low-quality service + lowerFidelity: + uR: -500 + uM: 0 + uC: -0.10 + uA: +5 + +# Utility: [^] R; [^] M; [v] C; [v]A +# assume that adding the captcha reduces response time by 250 ms, reduces level of malicious users by 90%, increases cost 1/2 unit, and increases user annoyance by 50% + addCaptcha: + uR: -250 + uM: -90 + uC: +0.50 + uA: +50 + +# Utility: [^] R; [^] M; [<>] C; [v]A +# assume that forcing users to reauthenticate reduces response time by 250 ms, reduces level of malicious users by 70%, and increases user annoyance by 50% + forceReauthentication: + uR: -250 + uM: -70 + uC: 0.00 + uA: +50 + +# Utility: [^] R; [^] M; [<>] C; [v]A +# assume that blackholing potential attackers reduces response time by 1000 ms, reduces level of malicious users by 100%, and increases user annoyance by 100% + blackholeAttacker: + uR: -1000 + uM: -100 + uC: 0.00 + uA: +50 + +# Utility: [^] R; [<>] M; [<>] C; [v]A +# assume that throttling suspicious clients reduces response time by 500 ms, and increases user annoyance by 50% + throttleSuspicious: + uR: -500 +# uM may need to change if we decide to substitute % of malicious clients by % of malicious user throughput + uM: 0 + uC: 0.00 + uA: +25 + +# Utility: [^] R; [<>] M; [^] C; [^]A +# assume that removing the captcha reduces cost 1/2 unit, and reduces user annoyance by 50% + removeCaptcha: + uR: -500 + uM: 0 + uC: -0.50 + uA: -50 + +# Utility: [<>] R; [<>] M; [<>] C; [^]A +# assume that removing the captcha reduces user annoyance by 100% + unblackholeAttacker: + uR: 0 + uM: 0 + uC: 0.00 + uA: -100 + +# Utility: [<>] R; [<>] M; [<>] C; [^]A +# assume that unthrottling suspicious clients reduces user annoyance by 50% + unthrottle: + uR: 0 + uM: 0 + uC: 0.00 + uA: -50 + diff --git a/targets/znews-ss/system/debpkgs.txt b/targets/znews-ss/system/debpkgs.txt index 96003b50f..544fb5fca 100644 --- a/targets/znews-ss/system/debpkgs.txt +++ b/targets/znews-ss/system/debpkgs.txt @@ -1,19 +1,19 @@ - -Debian packages required: -* sysstat - iostat, vmstat, etc. - -Nice packages: -* bc - calculator (under section "math") -* ganglia-monitor?? - for the Ganglia monitoring framework - -If compiling own Apache HTTPd 2.0.x, PHP, and MySQL... -Things to have in the system in order to compile/build: -- libncurses5 -- gcc/g++ 4.0 (3.3+ should work) -- pkg-config -- make/automake(1.8)/autoconf -- flex (lex generator) -- gettext -- openssl/libssl-dev -- zlib-dev -- libxml2/libxml2-dev + +Debian packages required: +* sysstat - iostat, vmstat, etc. + +Nice packages: +* bc - calculator (under section "math") +* ganglia-monitor?? - for the Ganglia monitoring framework + +If compiling own Apache HTTPd 2.0.x, PHP, and MySQL... +Things to have in the system in order to compile/build: +- libncurses5 +- gcc/g++ 4.0 (3.3+ should work) +- pkg-config +- make/automake(1.8)/autoconf +- flex (lex generator) +- gettext +- openssl/libssl-dev +- zlib-dev +- libxml2/libxml2-dev diff --git a/targets/znews-ss/system/effectors.yml b/targets/znews-ss/system/effectors.yml index 867fcea56..bad491ebf 100644 --- a/targets/znews-ss/system/effectors.yml +++ b/targets/znews-ss/system/effectors.yml @@ -1,287 +1,287 @@ -# Created January 30, 2007 (Shang-Wen Cheng) -# -# Effector descriptions. -# -# History: -# - [SWC 2007.01.30] Created file, populated ZNews effector descriptions. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# -vars: -# _effectors.commonPath: "${rainbow.path}/system/effectors" -# @ZNN_HOME will be replaced by the rainbow-install script -# _effectors.commonPath: "@ZNN_HOME/effectors" - _effectors.commonPath: "/home/znn/effectors" - - -effector-types: - - blackholeT: - command: "BlackholerT.setBlackholed ($)" - type: script - scriptInfo: - path: "${_effectors.commonPath}/ip-block-mgmt" - argument: "block {0}" - - flushAuthenticationT: - command: "AuthenticationHandlerT.forceReauthentication" - type: script - scriptInfo: - path: "${_effectors.commonPath}/force-reauthentication" - - -effectors: - - blackhole: - effector-type: blackholeT - command: "${customize.system.taret.lb}.setBlackholed ($)" - location: "${customize.system.target.lb}" - - throttle: - location: "${customize.system.target.lb}" - command: setThrottled($) - type: script - scriptInfo: - path: "/home/znn/effectors/ip-throttle-mgmt" - argument: "throttle {0}" - - flushAuthentication-web0: - effector-type: flushAuthenticationT - location: "${cusomize.system.target.web0}" - command: "${customize.system.target.lb}.forceReauthentication()" - - flushAuthentication-web1: - effector-type: flushAuthenticationT - location: "${cusomize.system.target.web1}" - command: "${customize.system.target.lb}.forceReauthentication()" - - flushAuthentication-web2: - effector-type: flushAuthenticationT - location: "${cusomize.system.target.web2}" - command: "${customize.system.target.lb}.forceReauthentication()" - - enableCaptcha-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-lb: - location: "${customize.system.target.lb}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-web2: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - disableCaptcha-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-lb: - location: "${customize.system.target.lb}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-web2: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - setFidelity-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web0.httpPort}" - - setFidelity-web1: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web1.httpPort}" - - setFidelity-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web2.httpPort}" - - enable-server-web0: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web0}, true)" - type: script - scriptInfo: - path : /home/znn/effectors/enable-server - argument : "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - disable-server-web0: - location: "${customize.system.target.lb}" - command: "LB0.enableServer (${customize.system.target.web0}, false)" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - enable-server-web1: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web1}, true)" - type: script - scriptInfo: - path : /home/znn/effectors/enable-server - argument : "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - disable-server-web1: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web1}, false)" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - enable-server-web2: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web2}, true)" - type: script - scriptInfo: - path : /home/znn/effectors/enable-server - argument : "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - disable-server-web2: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web2}, false)" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - delete-server-web0: - location: "${customize.system.target.lb}" - command: "${customize.system.target.web0}.deleteServer ()" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - add-server-web0: - location: "${customize.system.target.lb}" - command: "LB0.connectServer (${customize.system.target.web0})" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - delete-server-web1: - location: "${customize.system.target.lb}" - command: "${customize.system.target.web1}.deleteServer ()" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - add-server-web1: - location: "${customize.system.target.lb}" - command: "LB0.connectServer (${customize.system.target.web1})" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - delete-server-web2: - location: "${customize.system.target.lb}" - command: "${customize.system.target.web2}.deleteServer ()" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - add-server-web2: - location: "${customize.system.target.lb}" - command: "LB0.connectServer (${customize.system.target.web2})" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - -unused-effectors: - unblackhole: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path: "/home/znn/effectors/ip-block-mgmt" - argument: "unblock {clients}" - killDelegate2: -# Causes the designated RainbowDelegate to exit process -# Illustrates effector time-out as well as tests executor execution - location: "${customize.system.target.3}" - type: java - javaInfo: - class : org.sa.rainbow.translator.effectors.KillDelegateEffector - - # test from GUI with , SetFidelity, fidelity=<1|3|5> - - - activateServer1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/turnServer.pl" - argument: "-s on" - deactivateServer1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/turnServer.pl" - argument: "-s off" -# test from GUI with , RandomReject, frequency=<0..?> - randomReject1: - location: "${customize.system.target.2}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/setRandomReject.pl" - argument: "-r {frequency}" - killDelegate1: - location: "${customize.system.target.2}" - type: java - javaInfo: - class : org.sa.rainbow.translator.effectors.KillDelegateEffector +# Created January 30, 2007 (Shang-Wen Cheng) +# +# Effector descriptions. +# +# History: +# - [SWC 2007.01.30] Created file, populated ZNews effector descriptions. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# +vars: +# _effectors.commonPath: "${rainbow.path}/system/effectors" +# @ZNN_HOME will be replaced by the rainbow-install script +# _effectors.commonPath: "@ZNN_HOME/effectors" + _effectors.commonPath: "/home/znn/effectors" + + +effector-types: + + blackholeT: + command: "BlackholerT.setBlackholed ($)" + type: script + scriptInfo: + path: "${_effectors.commonPath}/ip-block-mgmt" + argument: "block {0}" + + flushAuthenticationT: + command: "AuthenticationHandlerT.forceReauthentication" + type: script + scriptInfo: + path: "${_effectors.commonPath}/force-reauthentication" + + +effectors: + + blackhole: + effector-type: blackholeT + command: "${customize.system.taret.lb}.setBlackholed ($)" + location: "${customize.system.target.lb}" + + throttle: + location: "${customize.system.target.lb}" + command: setThrottled($) + type: script + scriptInfo: + path: "/home/znn/effectors/ip-throttle-mgmt" + argument: "throttle {0}" + + flushAuthentication-web0: + effector-type: flushAuthenticationT + location: "${cusomize.system.target.web0}" + command: "${customize.system.target.lb}.forceReauthentication()" + + flushAuthentication-web1: + effector-type: flushAuthenticationT + location: "${cusomize.system.target.web1}" + command: "${customize.system.target.lb}.forceReauthentication()" + + flushAuthentication-web2: + effector-type: flushAuthenticationT + location: "${cusomize.system.target.web2}" + command: "${customize.system.target.lb}.forceReauthentication()" + + enableCaptcha-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-lb: + location: "${customize.system.target.lb}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-web2: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + disableCaptcha-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-lb: + location: "${customize.system.target.lb}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-web2: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + setFidelity-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web0.httpPort}" + + setFidelity-web1: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web1.httpPort}" + + setFidelity-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web2.httpPort}" + + enable-server-web0: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web0}, true)" + type: script + scriptInfo: + path : /home/znn/effectors/enable-server + argument : "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + disable-server-web0: + location: "${customize.system.target.lb}" + command: "LB0.enableServer (${customize.system.target.web0}, false)" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + enable-server-web1: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web1}, true)" + type: script + scriptInfo: + path : /home/znn/effectors/enable-server + argument : "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + disable-server-web1: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web1}, false)" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + enable-server-web2: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web2}, true)" + type: script + scriptInfo: + path : /home/znn/effectors/enable-server + argument : "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + disable-server-web2: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web2}, false)" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + delete-server-web0: + location: "${customize.system.target.lb}" + command: "${customize.system.target.web0}.deleteServer ()" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + add-server-web0: + location: "${customize.system.target.lb}" + command: "LB0.connectServer (${customize.system.target.web0})" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + delete-server-web1: + location: "${customize.system.target.lb}" + command: "${customize.system.target.web1}.deleteServer ()" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + add-server-web1: + location: "${customize.system.target.lb}" + command: "LB0.connectServer (${customize.system.target.web1})" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + delete-server-web2: + location: "${customize.system.target.lb}" + command: "${customize.system.target.web2}.deleteServer ()" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + add-server-web2: + location: "${customize.system.target.lb}" + command: "LB0.connectServer (${customize.system.target.web2})" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + +unused-effectors: + unblackhole: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path: "/home/znn/effectors/ip-block-mgmt" + argument: "unblock {clients}" + killDelegate2: +# Causes the designated RainbowDelegate to exit process +# Illustrates effector time-out as well as tests executor execution + location: "${customize.system.target.3}" + type: java + javaInfo: + class : org.sa.rainbow.translator.effectors.KillDelegateEffector + + # test from GUI with , SetFidelity, fidelity=<1|3|5> + + + activateServer1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/turnServer.pl" + argument: "-s on" + deactivateServer1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/turnServer.pl" + argument: "-s off" +# test from GUI with , RandomReject, frequency=<0..?> + randomReject1: + location: "${customize.system.target.2}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/setRandomReject.pl" + argument: "-r {frequency}" + killDelegate1: + location: "${customize.system.target.2}" + type: java + javaInfo: + class : org.sa.rainbow.translator.effectors.KillDelegateEffector diff --git a/targets/znews-ss/system/effectors/changeFidelity.pl b/targets/znews-ss/system/effectors/changeFidelity.pl index a24df7cef..80123eba4 100644 --- a/targets/znews-ss/system/effectors/changeFidelity.pl +++ b/targets/znews-ss/system/effectors/changeFidelity.pl @@ -1,83 +1,83 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -my $isCygwin = 0; -my $uname; -if ( -e "/bin/uname" ) { - $uname = `/bin/uname`; -} elsif ( -e "/usr/bin/uname" ) { - $uname = `/usr/bin/uname`; -} else { - $uname = "UNKNOWN"; -} -if ($uname =~ /CYGWIN/i) { - $isCygwin = 1; -} - -chomp(my $SCRIPT_DIR = `/usr/bin/dirname "$0"`); -my $APACHE_CONF_DIR = ($isCygwin) ? - "/cygdrive/c/server/Apache2/conf" : - "/etc/apache2"; -my $APACHE_CONF_FILE = ($isCygwin) ? - "httpd.conf" : - "apache2.conf"; -my $APACHE_SITE_DIR = "$APACHE_CONF_DIR/sites-available"; -my $APACHE_SITE_FILE = "z.com"; -my $SOURCE_CONF_DIR = ($isCygwin) ? - "$SCRIPT_DIR/fidelity.conf/cygwin" : - "$SCRIPT_DIR/fidelity.conf/oracle"; - -sub usage() { - print STDERR << "EOF"; - -This effector program changes the webserver fidelity level (1,3,5). - - usage: $0 [option] -l level - - -h : this (help) message - -l level : the new fidelity setting, should be 1, 3, or 5 (0 for original) - -EOF - exit; -} - -# get options -my %opts; -getopts('hl:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{l})); - -my $level = $opts{l}; -usage() if ($level != 0 && $level != 1 && $level != 3 && $level != 5); - -my $fExt = "-f"; -if ($level == 0) { - if ($isCygwin) { - $fExt = ".default"; - } else { - $fExt .= "5"; - } -} else { - $fExt .= $level; -} - -if ($isCygwin) { - - print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; - print `/usr/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; - print "\nGracefully restarting Apache..."; - print `/cygdrive/c/server/Apache2/bin/Apache.exe -w -n "Apache2" -k restart`; - print "\nDone."; - -} else { - - print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; - print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; - print "\nSwapping site to level $level..."; - print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_SITE_FILE$fExt $APACHE_SITE_DIR/$APACHE_SITE_FILE`; - print "\nGracefully restarting Apache..."; - print `/etc/init.d/apache2 reload`; - print "\nDone."; - -} +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +my $isCygwin = 0; +my $uname; +if ( -e "/bin/uname" ) { + $uname = `/bin/uname`; +} elsif ( -e "/usr/bin/uname" ) { + $uname = `/usr/bin/uname`; +} else { + $uname = "UNKNOWN"; +} +if ($uname =~ /CYGWIN/i) { + $isCygwin = 1; +} + +chomp(my $SCRIPT_DIR = `/usr/bin/dirname "$0"`); +my $APACHE_CONF_DIR = ($isCygwin) ? + "/cygdrive/c/server/Apache2/conf" : + "/etc/apache2"; +my $APACHE_CONF_FILE = ($isCygwin) ? + "httpd.conf" : + "apache2.conf"; +my $APACHE_SITE_DIR = "$APACHE_CONF_DIR/sites-available"; +my $APACHE_SITE_FILE = "z.com"; +my $SOURCE_CONF_DIR = ($isCygwin) ? + "$SCRIPT_DIR/fidelity.conf/cygwin" : + "$SCRIPT_DIR/fidelity.conf/oracle"; + +sub usage() { + print STDERR << "EOF"; + +This effector program changes the webserver fidelity level (1,3,5). + + usage: $0 [option] -l level + + -h : this (help) message + -l level : the new fidelity setting, should be 1, 3, or 5 (0 for original) + +EOF + exit; +} + +# get options +my %opts; +getopts('hl:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{l})); + +my $level = $opts{l}; +usage() if ($level != 0 && $level != 1 && $level != 3 && $level != 5); + +my $fExt = "-f"; +if ($level == 0) { + if ($isCygwin) { + $fExt = ".default"; + } else { + $fExt .= "5"; + } +} else { + $fExt .= $level; +} + +if ($isCygwin) { + + print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; + print `/usr/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; + print "\nGracefully restarting Apache..."; + print `/cygdrive/c/server/Apache2/bin/Apache.exe -w -n "Apache2" -k restart`; + print "\nDone."; + +} else { + + print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; + print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; + print "\nSwapping site to level $level..."; + print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_SITE_FILE$fExt $APACHE_SITE_DIR/$APACHE_SITE_FILE`; + print "\nGracefully restarting Apache..."; + print `/etc/init.d/apache2 reload`; + print "\nDone."; + +} diff --git a/targets/znews-ss/system/effectors/dummyBlackhole.pl b/targets/znews-ss/system/effectors/dummyBlackhole.pl index 0a9e46e42..81ed3be30 100644 --- a/targets/znews-ss/system/effectors/dummyBlackhole.pl +++ b/targets/znews-ss/system/effectors/dummyBlackhole.pl @@ -1,24 +1,24 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -sub usage () { - print STDERR << "EOF"; - -This effector program is a dummy blackholer. - - usege: $0 [option] -i IP - - -i IP: the IP address that should be blackholed - -EOF - exit; -} - -#get options -my %opts; -getopts ('i:',\%opts) or usage (); -usage () if (!defined($opts{i})); -my $IP = $opts{i} -print "Blackholing $IP...\n"; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +sub usage () { + print STDERR << "EOF"; + +This effector program is a dummy blackholer. + + usege: $0 [option] -i IP + + -i IP: the IP address that should be blackholed + +EOF + exit; +} + +#get options +my %opts; +getopts ('i:',\%opts) or usage (); +usage () if (!defined($opts{i})); +my $IP = $opts{i} +print "Blackholing $IP...\n"; diff --git a/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf b/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf index 4adbba299..5b13550db 100644 --- a/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf +++ b/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf @@ -1,967 +1,967 @@ -### Fidelity-5 Conf file -## - full featured -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -AddType application/x-httpd-php .php - -# configure the path to php.ini -PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.php index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -AddType text/html .shtml -AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-5 Conf file +## - full featured +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +AddType application/x-httpd-php .php + +# configure the path to php.ini +PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.php index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +AddType text/html .shtml +AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 b/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 index 95dd86268..6907bc89d 100644 --- a/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 +++ b/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 @@ -1,974 +1,974 @@ -### Fidelity-1 Conf file -## - reduced timeout from 300 to 30 sec -## - reduced max keep alive reqs from 100 to 10 -## - threads per child reduced from 250 to 10 -## - set an upper limit of max requests per child to 5 -## - excluded user dir function -## - excluded modules dav, imap, rewrite, userdir -## - reduced Directory Options to indexes & symlink only -## - reduced AllowOverride to None -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 30 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 10 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 10 -MaxRequestsPerChild 5 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -#LoadModule cgi_module modules/mod_cgi.so -#LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -#LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -#LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -#LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -#AddType application/x-httpd-php .php - -# configure the path to php.ini -#PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www1" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options Indexes SymLinksIfOwnerMatch - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride None - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -#UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - -# -# Options Indexes -# AllowOverride None -# Order allow,deny -# Allow from all -# -# -# SetHandler type-map -# -# -# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 -# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 -# - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# -# -# AllowOverride None -# Options None -# Order allow,deny -# Allow from all -# - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -#AddType application/x-compress .Z -#AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# -# -# Include conf/ssl.conf -# - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-1 Conf file +## - reduced timeout from 300 to 30 sec +## - reduced max keep alive reqs from 100 to 10 +## - threads per child reduced from 250 to 10 +## - set an upper limit of max requests per child to 5 +## - excluded user dir function +## - excluded modules dav, imap, rewrite, userdir +## - reduced Directory Options to indexes & symlink only +## - reduced AllowOverride to None +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 30 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 10 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 10 +MaxRequestsPerChild 5 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule cgi_module modules/mod_cgi.so +#LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +#LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +#LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +#LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +#AddType application/x-httpd-php .php + +# configure the path to php.ini +#PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www1" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options Indexes SymLinksIfOwnerMatch + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride None + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +#UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + +# +# Options Indexes +# AllowOverride None +# Order allow,deny +# Allow from all +# +# +# SetHandler type-map +# +# +# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 +# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 +# + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +# +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +# + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +#AddType application/x-compress .Z +#AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# +# +# Include conf/ssl.conf +# + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 b/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 index 7fd0f402b..eaab99348 100644 --- a/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 +++ b/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 @@ -1,971 +1,971 @@ -### Fidelity-3 Conf file -## - excluded CGI handling -## - excluded PHP module -## - excluded SSI -## - excluded compression type -## - excluded server manual -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -#LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -#AddType application/x-httpd-php .php - -# configure the path to php.ini -#PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www3" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - -# -# Options Indexes -# AllowOverride None -# Order allow,deny -# Allow from all -# -# -# SetHandler type-map -# -# -# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 -# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 -# - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# -# -# AllowOverride None -# Options None -# Order allow,deny -# Allow from all -# - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -#AddType application/x-compress .Z -#AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-3 Conf file +## - excluded CGI handling +## - excluded PHP module +## - excluded SSI +## - excluded compression type +## - excluded server manual +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +#AddType application/x-httpd-php .php + +# configure the path to php.ini +#PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www3" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + +# +# Options Indexes +# AllowOverride None +# Order allow,deny +# Allow from all +# +# +# SetHandler type-map +# +# +# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 +# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 +# + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +# +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +# + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +#AddType application/x-compress .Z +#AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 b/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 index 4adbba299..5b13550db 100644 --- a/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 +++ b/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 @@ -1,967 +1,967 @@ -### Fidelity-5 Conf file -## - full featured -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -AddType application/x-httpd-php .php - -# configure the path to php.ini -PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.php index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -AddType text/html .shtml -AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-5 Conf file +## - full featured +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +AddType application/x-httpd-php .php + +# configure the path to php.ini +PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.php index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +AddType text/html .shtml +AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf.default b/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf.default index 20dd3c11d..ff8505b79 100644 --- a/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf.default +++ b/targets/znews-ss/system/effectors/fidelity.conf/cygwin/httpd.conf.default @@ -1,952 +1,952 @@ -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -#LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -#LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin admin@able.cs.cmu.edu - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/Apache2/htdocs" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options Indexes FollowSymLinks - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride None - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +#LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +#LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin admin@able.cs.cmu.edu + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/Apache2/htdocs" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options Indexes FollowSymLinks + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride None + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# diff --git a/targets/znews-ss/system/effectors/setRandomReject.pl b/targets/znews-ss/system/effectors/setRandomReject.pl index 5d6b91697..58f70c7b0 100644 --- a/targets/znews-ss/system/effectors/setRandomReject.pl +++ b/targets/znews-ss/system/effectors/setRandomReject.pl @@ -1,35 +1,35 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -my $APACHE_WWW_DIR = "/home/owen/project/rainbow/delegate/targets/znews1-d/system/webpages/www5"; - -sub usage() { - print STDERR << "EOF"; - -This effector program affects random reject frequency (0 or mod over seconds). - - usage: $0 [option] -r [0|modval] - - -h : this (help) message - -r 0|mod : the modulus value for request rejection (0 for NO reject) - -EOF - exit; -} - -# get options -my %opts; -getopts('hr:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{r})); - -my $modVal = $opts{r}; -usage() if ($modVal < 0 && $modVal > 10); - -my $file = "reject.mod"; -print "Setting reject modulus value to $modVal..."; -open(FOUT, ">$APACHE_WWW_DIR/$file"); -print FOUT $modVal; -close(FOUT); -print "\nDone."; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +my $APACHE_WWW_DIR = "/home/owen/project/rainbow/delegate/targets/znews1-d/system/webpages/www5"; + +sub usage() { + print STDERR << "EOF"; + +This effector program affects random reject frequency (0 or mod over seconds). + + usage: $0 [option] -r [0|modval] + + -h : this (help) message + -r 0|mod : the modulus value for request rejection (0 for NO reject) + +EOF + exit; +} + +# get options +my %opts; +getopts('hr:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{r})); + +my $modVal = $opts{r}; +usage() if ($modVal < 0 && $modVal > 10); + +my $file = "reject.mod"; +print "Setting reject modulus value to $modVal..."; +open(FOUT, ">$APACHE_WWW_DIR/$file"); +print FOUT $modVal; +close(FOUT); +print "\nDone."; diff --git a/targets/znews-ss/system/effectors/turnServer.pl b/targets/znews-ss/system/effectors/turnServer.pl index 8cc10dd33..9d46f681e 100644 --- a/targets/znews-ss/system/effectors/turnServer.pl +++ b/targets/znews-ss/system/effectors/turnServer.pl @@ -1,36 +1,36 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; -use IO::Handle; - -sub usage() { - print STDERR << "EOF"; - -This effector program turns the webserver on or off - - usage: $0 [option] -s on|off - - -h : this (help) message - -s on|off : on or off to start/stop webserver - -EOF - exit; -} - -# get options -my %opts; -getopts('hs:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{s})); - -my $switch = $opts{s}; -usage() if ($switch ne "on" && $switch ne "off"); - -if ($switch eq "on") { - print "\nStarting Apache..."; - print `/etc/init.d/apache2 start`; -} else { - print "\nStopping Apache..."; - print `/etc/init.d/apache2 stop`; -} -print "\nDone."; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; +use IO::Handle; + +sub usage() { + print STDERR << "EOF"; + +This effector program turns the webserver on or off + + usage: $0 [option] -s on|off + + -h : this (help) message + -s on|off : on or off to start/stop webserver + +EOF + exit; +} + +# get options +my %opts; +getopts('hs:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{s})); + +my $switch = $opts{s}; +usage() if ($switch ne "on" && $switch ne "off"); + +if ($switch eq "on") { + print "\nStarting Apache..."; + print `/etc/init.d/apache2 start`; +} else { + print "\nStopping Apache..."; + print `/etc/init.d/apache2 stop`; +} +print "\nDone."; diff --git a/targets/znews-ss/system/probes.yml b/targets/znews-ss/system/probes.yml index 61a8b3267..2f49faef5 100644 --- a/targets/znews-ss/system/probes.yml +++ b/targets/znews-ss/system/probes.yml @@ -1,220 +1,220 @@ -# -# Probe descriptions. -# -# History: -# - [SWC 2007.03.18] Created file, populated new probe descriptions. -# - [SWC 2007.04.09] Added array of host names as arguments to PingRTTProbe. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# - [SWC 2007.04.11] Added ClientProxyProbe -# -vars: -# _probes.commonPath: "${rainbow.path}/system/probes" - _probes.commonPath: /home/znn/rainbow/org.sa.rainbow.sdk.znews/targets/znews-ss/system/probes/ -probes: - - ClientProbe: - alias: client - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ClientProbe - period: 2000 - args.length: 1 - args.0: /home/znn/sw-bin/httpd-lb-2.4.2/logs/access_log - - EnablementProbe: - alias: enablementprobe - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ServerEnablementProbe - period: 2000 - args.length: 1 - args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/balanced.conf - - DummyMaliciousnessProbe: - alias: dummymaliciousness - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.DummyProbe - period: 2000 - args.length: 1 - args.0: /home/znn/maliciousness - - BlackholeProbe: - alias: blackhole - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.BlackholeProbe - period: 2000 - args.length: 1 - args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/blocked.conf - - ThrottleProbe: - alias: throttle - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ThrottleProbe - period: 2000 - args.length: 1 - args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/security.conf - - CaptchaProbe: - alias: captchaprobe - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.CaptchaProbe - period: 2000 - args.length: 1 - args.0: /tmp/znn-wrapper-1080 -# args.0: /home/znn/lb0/sw/httpd-2.4.2/conf/captcha.on - - AuthenticationProbe: - alias: authenticationprobe - location: "${customize.system.target.web0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.AuthenticationProbe - period: 2000 - args.length: 1 - args.0: /tmp/znn-wrapper-auth-1080 - - ClientProxyProbe0: - alias: clientproxy - location: "${customize.system.target.master}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe - period: 2000 - args.length: 1 - args.0: "http://${customize.system.target.lb}:1081/news.php" - - ClientProxyProbe1: - alias: clientproxy - location: "${customize.system.target.bad}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe - period: 2000 - args.length: 1 - args.0: "http://${customize.system.target.lb}:1081/news.php" - - FidelityProbe1: - alias: fidelity - location: "${customize.system.target.web0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.FidelityProbe - period: 2000 - args.length: 1 - args.0: "/tmp/znn-fidelity-${customize.system.target.web0.httpPort}" - - LoadProbe0: - alias: load - location: "${customize.system.target.lb}" - type: script - scriptInfo: - mode: continual - path: "${_probes.commonPath}/loadProbe.pl" - argument: "-o load.out" - - LoadProbe1: - alias: load - location: "${customize.system.target.web0}" - type: script - scriptInfo: - mode: continual - path: "${_probes.commonPath}/loadProbe.pl" - argument: "-o load.out" - - LoadProbe2: - alias: load - location: "${customize.system.target.web1}" - type: script - scriptInfo: - mode: continual - path: "${_probes.commonPath}/loadProbe.pl" - argument: "-o load.out" - - LoadProbe3: - alias: load - location: "${customize.system.target.web2}" - type: script - scriptInfo: - mode: continual - path: "${_probes.commonPath}/loadProbe.pl" - argument: "-o load.out" - -unused-probes: - ApacheTopProbe1: - alias: apachetop - location: "${customize.system.target.web0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/apachetopProbe.pl" - argument: "-k -s" - DiskIOProbe1: - alias: diskio - location: "${customize.system.target.web0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/diskIOProbe.pl" - argument: "-k -s" - PingRTTProbe1: - alias: pingrtt - location: "${customize.system.target.web0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.PingRTTProbe -# sample period in milliseconds - period: 1500 - args.length: 1 - args.0: "${rainbow.master.location.host}" -# args.1: "${customize.system.target.2}" - LoadProbe1: - alias: load - location: "${customize.system.target.web0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" - NullProbe0: - alias: NIL - location: "${customize.system.target.0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.probes.NullProbe - ApacheTopProbe0: - alias: apachetop - location: "${customize.system.target.0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/apachetopProbe.pl" - argument: "-k -s" - LoadProbe0: - alias: load - location: "${customize.system.target.0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" - PingRTTProbe3: - alias: pingrtt - location: "${customize.system.target.3}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znews.probes.PingRTTProbe - period: 1500 - args.length: 1 - args.0: "${rainbow.master.location.host}" - LoadProbe3: - alias: load - location: "${customize.system.target.3}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" +# +# Probe descriptions. +# +# History: +# - [SWC 2007.03.18] Created file, populated new probe descriptions. +# - [SWC 2007.04.09] Added array of host names as arguments to PingRTTProbe. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# - [SWC 2007.04.11] Added ClientProxyProbe +# +vars: +# _probes.commonPath: "${rainbow.path}/system/probes" + _probes.commonPath: /home/znn/rainbow/org.sa.rainbow.sdk.znews/targets/znews-ss/system/probes/ +probes: + + ClientProbe: + alias: client + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ClientProbe + period: 2000 + args.length: 1 + args.0: /home/znn/sw-bin/httpd-lb-2.4.2/logs/access_log + + EnablementProbe: + alias: enablementprobe + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ServerEnablementProbe + period: 2000 + args.length: 1 + args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/balanced.conf + + DummyMaliciousnessProbe: + alias: dummymaliciousness + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.DummyProbe + period: 2000 + args.length: 1 + args.0: /home/znn/maliciousness + + BlackholeProbe: + alias: blackhole + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.BlackholeProbe + period: 2000 + args.length: 1 + args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/blocked.conf + + ThrottleProbe: + alias: throttle + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ThrottleProbe + period: 2000 + args.length: 1 + args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/security.conf + + CaptchaProbe: + alias: captchaprobe + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.CaptchaProbe + period: 2000 + args.length: 1 + args.0: /tmp/znn-wrapper-1080 +# args.0: /home/znn/lb0/sw/httpd-2.4.2/conf/captcha.on + + AuthenticationProbe: + alias: authenticationprobe + location: "${customize.system.target.web0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.AuthenticationProbe + period: 2000 + args.length: 1 + args.0: /tmp/znn-wrapper-auth-1080 + + ClientProxyProbe0: + alias: clientproxy + location: "${customize.system.target.master}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe + period: 2000 + args.length: 1 + args.0: "http://${customize.system.target.lb}:1081/news.php" + + ClientProxyProbe1: + alias: clientproxy + location: "${customize.system.target.bad}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe + period: 2000 + args.length: 1 + args.0: "http://${customize.system.target.lb}:1081/news.php" + + FidelityProbe1: + alias: fidelity + location: "${customize.system.target.web0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.FidelityProbe + period: 2000 + args.length: 1 + args.0: "/tmp/znn-fidelity-${customize.system.target.web0.httpPort}" + + LoadProbe0: + alias: load + location: "${customize.system.target.lb}" + type: script + scriptInfo: + mode: continual + path: "${_probes.commonPath}/loadProbe.pl" + argument: "-o load.out" + + LoadProbe1: + alias: load + location: "${customize.system.target.web0}" + type: script + scriptInfo: + mode: continual + path: "${_probes.commonPath}/loadProbe.pl" + argument: "-o load.out" + + LoadProbe2: + alias: load + location: "${customize.system.target.web1}" + type: script + scriptInfo: + mode: continual + path: "${_probes.commonPath}/loadProbe.pl" + argument: "-o load.out" + + LoadProbe3: + alias: load + location: "${customize.system.target.web2}" + type: script + scriptInfo: + mode: continual + path: "${_probes.commonPath}/loadProbe.pl" + argument: "-o load.out" + +unused-probes: + ApacheTopProbe1: + alias: apachetop + location: "${customize.system.target.web0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/apachetopProbe.pl" + argument: "-k -s" + DiskIOProbe1: + alias: diskio + location: "${customize.system.target.web0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/diskIOProbe.pl" + argument: "-k -s" + PingRTTProbe1: + alias: pingrtt + location: "${customize.system.target.web0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.PingRTTProbe +# sample period in milliseconds + period: 1500 + args.length: 1 + args.0: "${rainbow.master.location.host}" +# args.1: "${customize.system.target.2}" + LoadProbe1: + alias: load + location: "${customize.system.target.web0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" + NullProbe0: + alias: NIL + location: "${customize.system.target.0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.probes.NullProbe + ApacheTopProbe0: + alias: apachetop + location: "${customize.system.target.0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/apachetopProbe.pl" + argument: "-k -s" + LoadProbe0: + alias: load + location: "${customize.system.target.0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" + PingRTTProbe3: + alias: pingrtt + location: "${customize.system.target.3}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znews.probes.PingRTTProbe + period: 1500 + args.length: 1 + args.0: "${rainbow.master.location.host}" + LoadProbe3: + alias: load + location: "${customize.system.target.3}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" diff --git a/targets/znews-ss/system/probes/apachetopProbe.pl b/targets/znews-ss/system/probes/apachetopProbe.pl index 79ba71042..9f8989f04 100644 --- a/targets/znews-ss/system/probes/apachetopProbe.pl +++ b/targets/znews-ss/system/probes/apachetopProbe.pl @@ -1,90 +1,90 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 5000; # 5 sec delay -my $APACHETOP_LOG = "../../log/apachetop.log"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -if (! -e $APACHETOP_LOG) { # create empty file - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line,$sendBeacon); -while (!shouldTerminate($sock)) { - $sendBeacon = 1; - while ($line = ) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - $sendBeacon = 0; - } - if ($sendBeacon) { # announce something to be alive - announce($ALIAS, "\n", [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 5000; # 5 sec delay +my $APACHETOP_LOG = "../../log/apachetop.log"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +if (! -e $APACHETOP_LOG) { # create empty file + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line,$sendBeacon); +while (!shouldTerminate($sock)) { + $sendBeacon = 1; + while ($line = ) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + $sendBeacon = 0; + } + if ($sendBeacon) { # announce something to be alive + announce($ALIAS, "\n", [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss/system/probes/cygwin/apachetopProbe-single.pl b/targets/znews-ss/system/probes/cygwin/apachetopProbe-single.pl index 966358241..762a0686a 100644 --- a/targets/znews-ss/system/probes/cygwin/apachetopProbe-single.pl +++ b/targets/znews-ss/system/probes/cygwin/apachetopProbe-single.pl @@ -1,98 +1,98 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 10; -my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; -my $APACHETOP_LOG = "apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# fork to the apachetop program -my $pid = fork(); -if ($pid == 0) { ### child process - if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); - } - exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; - exit(0); -} - -### parent process - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line); -while (!shouldTerminate($sock)) { - $line = ; - if (defined($line)) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 10; +my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; +my $APACHETOP_LOG = "apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# fork to the apachetop program +my $pid = fork(); +if ($pid == 0) { ### child process + if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); + } + exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; + exit(0); +} + +### parent process + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line); +while (!shouldTerminate($sock)) { + $line = ; + if (defined($line)) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss/system/probes/cygwin/apachetopProbe.pl b/targets/znews-ss/system/probes/cygwin/apachetopProbe.pl index 79ba71042..9f8989f04 100644 --- a/targets/znews-ss/system/probes/cygwin/apachetopProbe.pl +++ b/targets/znews-ss/system/probes/cygwin/apachetopProbe.pl @@ -1,90 +1,90 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 5000; # 5 sec delay -my $APACHETOP_LOG = "../../log/apachetop.log"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -if (! -e $APACHETOP_LOG) { # create empty file - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line,$sendBeacon); -while (!shouldTerminate($sock)) { - $sendBeacon = 1; - while ($line = ) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - $sendBeacon = 0; - } - if ($sendBeacon) { # announce something to be alive - announce($ALIAS, "\n", [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 5000; # 5 sec delay +my $APACHETOP_LOG = "../../log/apachetop.log"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +if (! -e $APACHETOP_LOG) { # create empty file + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line,$sendBeacon); +while (!shouldTerminate($sock)) { + $sendBeacon = 1; + while ($line = ) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + $sendBeacon = 0; + } + if ($sendBeacon) { # announce something to be alive + announce($ALIAS, "\n", [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss/system/probes/cygwin/fidelityProbe.pl b/targets/znews-ss/system/probes/cygwin/fidelityProbe.pl index 21dc6255d..abb411a4d 100644 --- a/targets/znews-ss/system/probes/cygwin/fidelityProbe.pl +++ b/targets/znews-ss/system/probes/cygwin/fidelityProbe.pl @@ -1,100 +1,100 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "fidelity"; -my $NAME = "FidelityProbe"; -my $DELAY = 1000; -my $REPEATEVERY = 5; -my $APACHE_CONF_DIR = "/cygdrive/c/server/Apache2/conf"; -my $APACHE_CONF_FILE = "httpd.conf"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current server fidelity (1,3,5) to Probe Relay file/socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic server fidelity info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub determineFidelity () { - my $fid = 0; - - open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); - my $firstLine = ; # read the first line - if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { - $fid = $1; - } - close(FIN); - - return $fid; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -my $repeatCnt = $REPEATEVERY; -my $savedFidelity = 0; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # compute new fidelity status - my $fidelity = determineFidelity(); - if ($fidelity != $savedFidelity || $repeatCnt == 0) { - $savedFidelity = $fidelity; #store new fidelity - my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - - if ($repeatCnt == 0) { - $repeatCnt = $REPEATEVERY; - } - } else { - $repeatCnt--; - } -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "fidelity"; +my $NAME = "FidelityProbe"; +my $DELAY = 1000; +my $REPEATEVERY = 5; +my $APACHE_CONF_DIR = "/cygdrive/c/server/Apache2/conf"; +my $APACHE_CONF_FILE = "httpd.conf"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current server fidelity (1,3,5) to Probe Relay file/socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic server fidelity info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub determineFidelity () { + my $fid = 0; + + open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); + my $firstLine = ; # read the first line + if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { + $fid = $1; + } + close(FIN); + + return $fid; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +my $repeatCnt = $REPEATEVERY; +my $savedFidelity = 0; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # compute new fidelity status + my $fidelity = determineFidelity(); + if ($fidelity != $savedFidelity || $repeatCnt == 0) { + $savedFidelity = $fidelity; #store new fidelity + my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + + if ($repeatCnt == 0) { + $repeatCnt = $REPEATEVERY; + } + } else { + $repeatCnt--; + } +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss/system/probes/cygwin/loadProbe.pl b/targets/znews-ss/system/probes/cygwin/loadProbe.pl index b50e32b17..0ff60debb 100644 --- a/targets/znews-ss/system/probes/cygwin/loadProbe.pl +++ b/targets/znews-ss/system/probes/cygwin/loadProbe.pl @@ -1,98 +1,98 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "load"; -my $NAME = "LoadProbe"; -my $DELAY = 1000; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current CPU usage to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic CPU usage info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub cpuTime () { - my ($user, $nice, $sys, $idle); - - local(*FIN); - open(FIN, ") { - chomp; - if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/o) { - ($user, $nice, $sys, $idle) = ($1, $2, $3, $4); - last; - } - } - close(FIN); - return ($user, $nice, $sys, $idle); -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# save current cpu ticks -my($userSv, $niceSv, $sysSv, $idleSv) = cpuTime(); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # retrieve new cpu ticks - my ($userN, $niceN, $sysN, $idleN) = cpuTime(); - # compute delta cpu ticks - my ($user, $nice, $sys, $idle) = - ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv); - # store the new saved ticks - ($userSv, $niceSv, $sysSv, $idleSv) = ($userN, $niceN, $sysN, $idleN); - my $total = $user + $nice + $sys + $idle; - my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), - $user/$total, $nice/$total, $sys/$total, $idle/$total); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "load"; +my $NAME = "LoadProbe"; +my $DELAY = 1000; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current CPU usage to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic CPU usage info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub cpuTime () { + my ($user, $nice, $sys, $idle); + + local(*FIN); + open(FIN, ") { + chomp; + if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/o) { + ($user, $nice, $sys, $idle) = ($1, $2, $3, $4); + last; + } + } + close(FIN); + return ($user, $nice, $sys, $idle); +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# save current cpu ticks +my($userSv, $niceSv, $sysSv, $idleSv) = cpuTime(); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # retrieve new cpu ticks + my ($userN, $niceN, $sysN, $idleN) = cpuTime(); + # compute delta cpu ticks + my ($user, $nice, $sys, $idle) = + ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv); + # store the new saved ticks + ($userSv, $niceSv, $sysSv, $idleSv) = ($userN, $niceN, $sysN, $idleN); + my $total = $user + $nice + $sys + $idle; + my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), + $user/$total, $nice/$total, $sys/$total, $idle/$total); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss/system/probes/cygwin/probe-cygwin.bat b/targets/znews-ss/system/probes/cygwin/probe-cygwin.bat index 4f192949d..b912671dd 100644 --- a/targets/znews-ss/system/probes/cygwin/probe-cygwin.bat +++ b/targets/znews-ss/system/probes/cygwin/probe-cygwin.bat @@ -1,8 +1,8 @@ -@echo off - -C: -chdir C:\server\cygwin\bin -set DEMO_MODE=%1 -set DEMO_TITLE=%2 - -bash --login -i +@echo off + +C: +chdir C:\server\cygwin\bin +set DEMO_MODE=%1 +set DEMO_TITLE=%2 + +bash --login -i diff --git a/targets/znews-ss/system/probes/cygwin/runApachetop.pl b/targets/znews-ss/system/probes/cygwin/runApachetop.pl index aca341ab9..0970d810f 100644 --- a/targets/znews-ss/system/probes/cygwin/runApachetop.pl +++ b/targets/znews-ss/system/probes/cygwin/runApachetop.pl @@ -1,16 +1,16 @@ -#!/usr/bin/perl -w - -use strict; - -############################# -my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; -my $APACHETOP_LOG = "/cygdrive/c/server/rainbow/oracle/targets/znews1/log/apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - -if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; +#!/usr/bin/perl -w + +use strict; + +############################# +my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; +my $APACHETOP_LOG = "/cygdrive/c/server/rainbow/oracle/targets/znews1/log/apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + +if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; diff --git a/targets/znews-ss/system/probes/diskIOProbe-diskstats.pl b/targets/znews-ss/system/probes/diskIOProbe-diskstats.pl index e4a1e3ba5..a40e58938 100644 --- a/targets/znews-ss/system/probes/diskIOProbe-diskstats.pl +++ b/targets/znews-ss/system/probes/diskIOProbe-diskstats.pl @@ -1,125 +1,125 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "diskio"; -my $NAME = "DiskIOProbe"; -my $DELAY = 4000; -############################# - -# Determine diskstats format -my $statfile; -my $uname = `uname -a`; -if ($uname =~ /Linux\s+(.+?)\s+(\d+[.]\d+)/) { - if ($2 eq "2.6") { - $statfile = "/proc/diskstats"; -# } elsif ($2 <= 2.5) { -# $statfile = "/proc/partitions"; # granularity of info more coarse - } -} else { - print "Linux version unsupported for diskstat access! Unable to continue probing\n"; - exit -1; -} - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current accumulated Disk IO to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic Disk IO info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub diskUsage () { - my ($MINOR, $FIRST, $TMIO) = (2, 4, 14); # index to stat entry - my (@accumStat) = (0,0,0,0,0,0,0,0,0,0,0); - my (@dstat); #$rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio - - open(FIN, "< $statfile"); - while () { - chomp; - @dstat = split(/\s+/); # blank zeroth element due to space(s) in beginning - if ($dstat[$MINOR] == 0 && $dstat[$TMIO] > 0) { # accum reading from device - for my $i ($FIRST..$#dstat) { - $accumStat[$i-$FIRST] += $dstat[$i]; - } - #print "Accumulated @accumStat\n"; - } - } - close(FIN); - return @accumStat; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# zero out disk IO stats -my($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) - = (0,0,0,0,0,0,0,0,0,0,0); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - # retrieve new disk IO stats - my ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN) = diskUsage(); - # compute delta stats for all except 9th and 10th - my ($rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio) = - ($rcmpN-$rcmpS, $rmrgN-$rmrgS, $rsectN-$rsectS, $rmsN-$rmsS, $wcmpN-$wcmpS, - $wmrgN-$wmrgS, $wsectN-$wsectS, $wmsN-$wmsS, $curioN, $curmsN, $tmioN-$tmioS); - # store the new saved ticks - ($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) = - ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN); - # each sector is 512 bytes as of kernel 2.4, so divide 2 to get kb - #print "D: $rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio\n" if ($doPrint); - my $kbRead = $rsect/2.0; - my $kbRps = ($rms == 0) ? 0 : ($kbRead / $rms) * 1000; # sec = 1000 ms - my $kbWritten = $wsect/2.0; - my $kbWps = ($wms == 0) ? 0 : ($kbWritten / $wms) * 1000; - my $tps = ($rms+$wms == 0) ? 0 : ($rcmp+$wcmp)/($rms+$wms) * 1000; - my $rpt = sprintf("[%s] %9.2f %9.2f %9.2f %9d %9d %9d %9d %9d\n", "".localtime(), - $tps, $kbRps, $kbWps, $kbRead, $kbWritten, $curio, $curms, $tmio); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "diskio"; +my $NAME = "DiskIOProbe"; +my $DELAY = 4000; +############################# + +# Determine diskstats format +my $statfile; +my $uname = `uname -a`; +if ($uname =~ /Linux\s+(.+?)\s+(\d+[.]\d+)/) { + if ($2 eq "2.6") { + $statfile = "/proc/diskstats"; +# } elsif ($2 <= 2.5) { +# $statfile = "/proc/partitions"; # granularity of info more coarse + } +} else { + print "Linux version unsupported for diskstat access! Unable to continue probing\n"; + exit -1; +} + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current accumulated Disk IO to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic Disk IO info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub diskUsage () { + my ($MINOR, $FIRST, $TMIO) = (2, 4, 14); # index to stat entry + my (@accumStat) = (0,0,0,0,0,0,0,0,0,0,0); + my (@dstat); #$rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio + + open(FIN, "< $statfile"); + while () { + chomp; + @dstat = split(/\s+/); # blank zeroth element due to space(s) in beginning + if ($dstat[$MINOR] == 0 && $dstat[$TMIO] > 0) { # accum reading from device + for my $i ($FIRST..$#dstat) { + $accumStat[$i-$FIRST] += $dstat[$i]; + } + #print "Accumulated @accumStat\n"; + } + } + close(FIN); + return @accumStat; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# zero out disk IO stats +my($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) + = (0,0,0,0,0,0,0,0,0,0,0); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + # retrieve new disk IO stats + my ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN) = diskUsage(); + # compute delta stats for all except 9th and 10th + my ($rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio) = + ($rcmpN-$rcmpS, $rmrgN-$rmrgS, $rsectN-$rsectS, $rmsN-$rmsS, $wcmpN-$wcmpS, + $wmrgN-$wmrgS, $wsectN-$wsectS, $wmsN-$wmsS, $curioN, $curmsN, $tmioN-$tmioS); + # store the new saved ticks + ($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) = + ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN); + # each sector is 512 bytes as of kernel 2.4, so divide 2 to get kb + #print "D: $rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio\n" if ($doPrint); + my $kbRead = $rsect/2.0; + my $kbRps = ($rms == 0) ? 0 : ($kbRead / $rms) * 1000; # sec = 1000 ms + my $kbWritten = $wsect/2.0; + my $kbWps = ($wms == 0) ? 0 : ($kbWritten / $wms) * 1000; + my $tps = ($rms+$wms == 0) ? 0 : ($rcmp+$wcmp)/($rms+$wms) * 1000; + my $rpt = sprintf("[%s] %9.2f %9.2f %9.2f %9d %9d %9d %9d %9d\n", "".localtime(), + $tps, $kbRps, $kbWps, $kbRead, $kbWritten, $curio, $curms, $tmio); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss/system/probes/diskIOProbe.pl b/targets/znews-ss/system/probes/diskIOProbe.pl index ec3391891..fe4b002b3 100644 --- a/targets/znews-ss/system/probes/diskIOProbe.pl +++ b/targets/znews-ss/system/probes/diskIOProbe.pl @@ -1,101 +1,101 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "diskio"; -my $NAME = "DiskIOProbe"; -my $DELAY = 5000; -############################# - -# Determine diskstats format -my $IOSTAT = "/usr/bin/iostat"; -if (! -e $IOSTAT) { - print "No iostat found, please install the sysstat package to continue!\n"; - exit -1; -} -my $IOSTAT_ARGS = "-k " . ($DELAY/1000); # period, with indefinite ouput - -sub usage() { - print STDERR << "EOF"; - -This program dumps periodic Disk IO status to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic Disk IO info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# init disk IO stats vars -my($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); -my($isInitial, $cntCycle) = (1, 0); -open(FIN, "$IOSTAT $IOSTAT_ARGS |") - || die "Can't fork $IOSTAT: $!"; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - # retrieve new disk IO stats - while () { - chomp; - if (/^Device:/i) { - ++$cntCycle; - if ($isInitial && $cntCycle > 1) { # no longer initial - print "Filtered initial round!\n" if ($doPrint); - $isInitial = 0; - } - } - if (!$isInitial && - /^(\w+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/) { - ($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB) = ($1, $2, $3, $4, $5, $6); - last; - } - } - my $rpt = sprintf("[%s] %s %.2f %.2f %.2f %d %d\n", "".localtime(), - $dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -close(FIN) || die "Bad $IOSTAT: $! $?"; -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "diskio"; +my $NAME = "DiskIOProbe"; +my $DELAY = 5000; +############################# + +# Determine diskstats format +my $IOSTAT = "/usr/bin/iostat"; +if (! -e $IOSTAT) { + print "No iostat found, please install the sysstat package to continue!\n"; + exit -1; +} +my $IOSTAT_ARGS = "-k " . ($DELAY/1000); # period, with indefinite ouput + +sub usage() { + print STDERR << "EOF"; + +This program dumps periodic Disk IO status to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic Disk IO info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# init disk IO stats vars +my($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); +my($isInitial, $cntCycle) = (1, 0); +open(FIN, "$IOSTAT $IOSTAT_ARGS |") + || die "Can't fork $IOSTAT: $!"; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + # retrieve new disk IO stats + while () { + chomp; + if (/^Device:/i) { + ++$cntCycle; + if ($isInitial && $cntCycle > 1) { # no longer initial + print "Filtered initial round!\n" if ($doPrint); + $isInitial = 0; + } + } + if (!$isInitial && + /^(\w+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/) { + ($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB) = ($1, $2, $3, $4, $5, $6); + last; + } + } + my $rpt = sprintf("[%s] %s %.2f %.2f %.2f %d %d\n", "".localtime(), + $dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +close(FIN) || die "Bad $IOSTAT: $! $?"; +cleanup($sock, [$fout]); diff --git a/targets/znews-ss/system/probes/fidelityProbe.pl b/targets/znews-ss/system/probes/fidelityProbe.pl index d5a8214ff..d22e3f086 100644 --- a/targets/znews-ss/system/probes/fidelityProbe.pl +++ b/targets/znews-ss/system/probes/fidelityProbe.pl @@ -1,100 +1,100 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "fidelity"; -my $NAME = "FidelityProbe"; -my $DELAY = 1000; -my $REPEATEVERY = 5; -my $APACHE_CONF_DIR = "/etc/apache2"; -my $APACHE_CONF_FILE = "apache2.conf"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current server fidelity (1,3,5) to Probe Relay file/socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic server fidelity info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub determineFidelity () { - my $fid = 0; - - open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); - my $firstLine = ; # read the first line - if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { - $fid = $1; - } - close(FIN); - - return $fid; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -my $repeatCnt = $REPEATEVERY; -my $savedFidelity = 0; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # compute new fidelity status - my $fidelity = determineFidelity(); - if ($fidelity != $savedFidelity || $repeatCnt == 0) { - $savedFidelity = $fidelity; #store new fidelity - my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - - if ($repeatCnt == 0) { - $repeatCnt = $REPEATEVERY; - } - } else { - $repeatCnt--; - } -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "fidelity"; +my $NAME = "FidelityProbe"; +my $DELAY = 1000; +my $REPEATEVERY = 5; +my $APACHE_CONF_DIR = "/etc/apache2"; +my $APACHE_CONF_FILE = "apache2.conf"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current server fidelity (1,3,5) to Probe Relay file/socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic server fidelity info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub determineFidelity () { + my $fid = 0; + + open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); + my $firstLine = ; # read the first line + if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { + $fid = $1; + } + close(FIN); + + return $fid; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +my $repeatCnt = $REPEATEVERY; +my $savedFidelity = 0; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # compute new fidelity status + my $fidelity = determineFidelity(); + if ($fidelity != $savedFidelity || $repeatCnt == 0) { + $savedFidelity = $fidelity; #store new fidelity + my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + + if ($repeatCnt == 0) { + $repeatCnt = $REPEATEVERY; + } + } else { + $repeatCnt--; + } +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss/system/probes/iostat.h b/targets/znews-ss/system/probes/iostat.h index 14abd66ec..644e9af0a 100644 --- a/targets/znews-ss/system/probes/iostat.h +++ b/targets/znews-ss/system/probes/iostat.h @@ -1,116 +1,116 @@ -/* - * iostat: report CPU and I/O statistics - * (C) 1999-2004 by Sebastien Godard - */ - -#ifndef _IOSTAT_H -#define _IOSTAT_H - -#include "common.h" - -#define MAX_NAME_LEN 72 - -#define D_CPU_ONLY 0x001 -#define D_DISK_ONLY 0x002 -#define D_TIMESTAMP 0x004 -#define D_EXTENDED 0x008 -#define D_PART_ALL 0x010 -#define D_KILOBYTES 0x020 -#define F_HAS_SYSFS 0x040 -#define F_OLD_KERNEL 0x080 -#define D_UNFILTERED 0x100 -/* 0x100000:0x800000 -> reserved (cf. common.h) */ - -#define DISPLAY_CPU_ONLY(m) (((m) & D_CPU_ONLY) == D_CPU_ONLY) -#define DISPLAY_DISK_ONLY(m) (((m) & D_DISK_ONLY) == D_DISK_ONLY) -#define DISPLAY_TIMESTAMP(m) (((m) & D_TIMESTAMP) == D_TIMESTAMP) -#define DISPLAY_EXTENDED(m) (((m) & D_EXTENDED) == D_EXTENDED) -#define DISPLAY_PART_ALL(m) (((m) & D_PART_ALL) == D_PART_ALL) -#define DISPLAY_KILOBYTES(m) (((m) & D_KILOBYTES) == D_KILOBYTES) -#define HAS_SYSFS(m) (((m) & F_HAS_SYSFS) == F_HAS_SYSFS) -#define HAS_OLD_KERNEL(m) (((m) & F_OLD_KERNEL) == F_OLD_KERNEL) -#define DISPLAY_UNFILTERED(m) (((m) & D_UNFILTERED) == D_UNFILTERED) - -#define DT_DEVICE 0 -#define DT_PARTITION 1 - - -struct comm_stats { - unsigned long uptime; - unsigned long uptime0; - unsigned long cpu_iowait; - unsigned long cpu_idle; - unsigned int cpu_user; - unsigned int cpu_nice; - unsigned int cpu_system; -}; - -#define COMM_STATS_SIZE (sizeof(struct comm_stats)) - -/* - * Structures for I/O stats. - * The number of structures allocated corresponds to the number of devices - * present in the system, plus a preallocation number to handle those - * that can be registered dynamically. - * The number of devices is found by using /sys filesystem (if mounted), - * or the number of "disk_io:" entries in /proc/stat (2.4 kernels), - * else the default value is 4 (for old kernels, which maintained stats - * for the first four devices in /proc/stat). - * For each io_stats structure allocated corresponds a io_hdr_stats structure. - * A io_stats structure is considered as unused or "free" (containing no stats - * for a particular device) if the 'major' field of the io_hdr_stats - * structure is set to 0. - */ -struct io_stats { - /* # of read operations issued to the device */ - unsigned int rd_ios __attribute__ ((aligned (8))); - /* # of read requests merged */ - unsigned int rd_merges __attribute__ ((packed)); - /* # of sectors read */ - unsigned int rd_sectors __attribute__ ((packed)); - /* Time of read requests in queue */ - unsigned int rd_ticks __attribute__ ((packed)); - /* # of write operations issued to the device */ - unsigned int wr_ios __attribute__ ((packed)); - /* # of write requests merged */ - unsigned int wr_merges __attribute__ ((packed)); - /* # of sectors written */ - unsigned int wr_sectors __attribute__ ((packed)); - /* Time of write requests in queue */ - unsigned int wr_ticks __attribute__ ((packed)); - /* # of I/Os in progress */ - unsigned int ios_pgr __attribute__ ((packed)); - /* # of ticks total (for this device) for I/O */ - unsigned int tot_ticks __attribute__ ((packed)); - /* # of ticks requests spent in queue */ - unsigned int rq_ticks __attribute__ ((packed)); - /* # of I/O done since last reboot */ - unsigned int dk_drive __attribute__ ((packed)); - /* # of blocks read */ - unsigned int dk_drive_rblk __attribute__ ((packed)); - /* # of blocks written */ - unsigned int dk_drive_wblk __attribute__ ((packed)); -}; - -#define IO_STATS_SIZE (sizeof(struct io_stats)) - -struct io_hdr_stats { - unsigned int active __attribute__ ((aligned (8))); - unsigned int major __attribute__ ((packed)); - unsigned int index __attribute__ ((packed)); - char name[MAX_NAME_LEN] __attribute__ ((packed)); -}; - -#define IO_HDR_STATS_SIZE (sizeof(struct io_hdr_stats)) - -/* List of devices entered on the command line */ -struct io_dlist { - /* Indicate whether its partitions are to be displayed or not */ - int disp_part __attribute__ ((aligned (8))); - /* Device name */ - char dev_name[MAX_NAME_LEN] __attribute__ ((packed)); -}; - -#define IO_DLIST_SIZE (sizeof(struct io_dlist)) - -#endif /* _IOSTAT_H */ +/* + * iostat: report CPU and I/O statistics + * (C) 1999-2004 by Sebastien Godard + */ + +#ifndef _IOSTAT_H +#define _IOSTAT_H + +#include "common.h" + +#define MAX_NAME_LEN 72 + +#define D_CPU_ONLY 0x001 +#define D_DISK_ONLY 0x002 +#define D_TIMESTAMP 0x004 +#define D_EXTENDED 0x008 +#define D_PART_ALL 0x010 +#define D_KILOBYTES 0x020 +#define F_HAS_SYSFS 0x040 +#define F_OLD_KERNEL 0x080 +#define D_UNFILTERED 0x100 +/* 0x100000:0x800000 -> reserved (cf. common.h) */ + +#define DISPLAY_CPU_ONLY(m) (((m) & D_CPU_ONLY) == D_CPU_ONLY) +#define DISPLAY_DISK_ONLY(m) (((m) & D_DISK_ONLY) == D_DISK_ONLY) +#define DISPLAY_TIMESTAMP(m) (((m) & D_TIMESTAMP) == D_TIMESTAMP) +#define DISPLAY_EXTENDED(m) (((m) & D_EXTENDED) == D_EXTENDED) +#define DISPLAY_PART_ALL(m) (((m) & D_PART_ALL) == D_PART_ALL) +#define DISPLAY_KILOBYTES(m) (((m) & D_KILOBYTES) == D_KILOBYTES) +#define HAS_SYSFS(m) (((m) & F_HAS_SYSFS) == F_HAS_SYSFS) +#define HAS_OLD_KERNEL(m) (((m) & F_OLD_KERNEL) == F_OLD_KERNEL) +#define DISPLAY_UNFILTERED(m) (((m) & D_UNFILTERED) == D_UNFILTERED) + +#define DT_DEVICE 0 +#define DT_PARTITION 1 + + +struct comm_stats { + unsigned long uptime; + unsigned long uptime0; + unsigned long cpu_iowait; + unsigned long cpu_idle; + unsigned int cpu_user; + unsigned int cpu_nice; + unsigned int cpu_system; +}; + +#define COMM_STATS_SIZE (sizeof(struct comm_stats)) + +/* + * Structures for I/O stats. + * The number of structures allocated corresponds to the number of devices + * present in the system, plus a preallocation number to handle those + * that can be registered dynamically. + * The number of devices is found by using /sys filesystem (if mounted), + * or the number of "disk_io:" entries in /proc/stat (2.4 kernels), + * else the default value is 4 (for old kernels, which maintained stats + * for the first four devices in /proc/stat). + * For each io_stats structure allocated corresponds a io_hdr_stats structure. + * A io_stats structure is considered as unused or "free" (containing no stats + * for a particular device) if the 'major' field of the io_hdr_stats + * structure is set to 0. + */ +struct io_stats { + /* # of read operations issued to the device */ + unsigned int rd_ios __attribute__ ((aligned (8))); + /* # of read requests merged */ + unsigned int rd_merges __attribute__ ((packed)); + /* # of sectors read */ + unsigned int rd_sectors __attribute__ ((packed)); + /* Time of read requests in queue */ + unsigned int rd_ticks __attribute__ ((packed)); + /* # of write operations issued to the device */ + unsigned int wr_ios __attribute__ ((packed)); + /* # of write requests merged */ + unsigned int wr_merges __attribute__ ((packed)); + /* # of sectors written */ + unsigned int wr_sectors __attribute__ ((packed)); + /* Time of write requests in queue */ + unsigned int wr_ticks __attribute__ ((packed)); + /* # of I/Os in progress */ + unsigned int ios_pgr __attribute__ ((packed)); + /* # of ticks total (for this device) for I/O */ + unsigned int tot_ticks __attribute__ ((packed)); + /* # of ticks requests spent in queue */ + unsigned int rq_ticks __attribute__ ((packed)); + /* # of I/O done since last reboot */ + unsigned int dk_drive __attribute__ ((packed)); + /* # of blocks read */ + unsigned int dk_drive_rblk __attribute__ ((packed)); + /* # of blocks written */ + unsigned int dk_drive_wblk __attribute__ ((packed)); +}; + +#define IO_STATS_SIZE (sizeof(struct io_stats)) + +struct io_hdr_stats { + unsigned int active __attribute__ ((aligned (8))); + unsigned int major __attribute__ ((packed)); + unsigned int index __attribute__ ((packed)); + char name[MAX_NAME_LEN] __attribute__ ((packed)); +}; + +#define IO_HDR_STATS_SIZE (sizeof(struct io_hdr_stats)) + +/* List of devices entered on the command line */ +struct io_dlist { + /* Indicate whether its partitions are to be displayed or not */ + int disp_part __attribute__ ((aligned (8))); + /* Device name */ + char dev_name[MAX_NAME_LEN] __attribute__ ((packed)); +}; + +#define IO_DLIST_SIZE (sizeof(struct io_dlist)) + +#endif /* _IOSTAT_H */ diff --git a/targets/znews-ss/system/probes/iostats.txt b/targets/znews-ss/system/probes/iostats.txt index 612dc5511..ba75611ea 100644 --- a/targets/znews-ss/system/probes/iostats.txt +++ b/targets/znews-ss/system/probes/iostats.txt @@ -1,151 +1,151 @@ -I/O statistics fields ---------------- - -Based on kernel version 2.6.20. Page generated on 2007-02-07 22:05 EST -Last modified Sep 30, 2003 - -Since 2.4.20 (and some versions before, with patches), and 2.5.45, -more extensive disk statistics have been introduced to help measure disk -activity. Tools such as sar and iostat typically interpret these and do -the work for you, but in case you are interested in creating your own -tools, the fields are explained here. - -In 2.4 now, the information is found as additional fields in -/proc/partitions. In 2.6, the same information is found in two -places: one is in the file /proc/diskstats, and the other is within -the sysfs file system, which must be mounted in order to obtain -the information. Throughout this document we'll assume that sysfs -is mounted on /sys, although of course it may be mounted anywhere. -Both /proc/diskstats and sysfs use the same source for the information -and so should not differ. - -Here are examples of these different formats: - -2.4: - 3 0 39082680 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 3 1 9221278 hda1 35486 0 35496 38030 0 0 0 0 0 38030 38030 - - -2.6 sysfs: - 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 35486 38030 38030 38030 - -2.6 diskstats: - 3 0 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 3 1 hda1 35486 38030 38030 38030 - -On 2.4 you might execute "grep 'hda ' /proc/partitions". On 2.6, you have -a choice of "cat /sys/block/hda/stat" or "grep 'hda ' /proc/diskstats". -The advantage of one over the other is that the sysfs choice works well -if you are watching a known, small set of disks. /proc/diskstats may -be a better choice if you are watching a large number of disks because -you'll avoid the overhead of 50, 100, or 500 or more opens/closes with -each snapshot of your disk statistics. - -In 2.4, the statistics fields are those after the device name. In -the above example, the first field of statistics would be 446216. -By contrast, in 2.6 if you look at /sys/block/hda/stat, you'll -find just the eleven fields, beginning with 446216. If you look at -/proc/diskstats, the eleven fields will be preceded by the major and -minor device numbers, and device name. Each of these formats provide -eleven fields of statistics, each meaning exactly the same things. -All fields except field 9 are cumulative since boot. Field 9 should -go to zero as I/Os complete; all others only increase. Yes, these are -32 bit unsigned numbers, and on a very busy or long-lived system they -may wrap. Applications should be prepared to deal with that; unless -your observations are measured in large numbers of minutes or hours, -they should not wrap twice before you notice them. - -Each set of stats only applies to the indicated device; if you want -system-wide stats you'll have to find all the devices and sum them all up. - -Field 1 -- # of reads issued - This is the total number of reads completed successfully. -Field 2 -- # of reads merged, field 6 -- # of writes merged - Reads and writes which are adjacent to each other may be merged for - efficiency. Thus two 4K reads may become one 8K read before it is - ultimately handed to the disk, and so it will be counted (and queued) - as only one I/O. This field lets you know how often this was done. -Field 3 -- # of sectors read - This is the total number of sectors read successfully. -Field 4 -- # of milliseconds spent reading - This is the total number of milliseconds spent by all reads (as - measured from __make_request() to end_that_request_last()). -Field 5 -- # of writes completed - This is the total number of writes completed successfully. -Field 7 -- # of sectors written - This is the total number of sectors written successfully. -Field 8 -- # of milliseconds spent writing - This is the total number of milliseconds spent by all writes (as - measured from __make_request() to end_that_request_last()). -Field 9 -- # of I/Os currently in progress - The only field that should go to zero. Incremented as requests are - given to appropriate request_queue_t and decremented as they finish. -Field 10 -- # of milliseconds spent doing I/Os - This field is increases so long as field 9 is nonzero. -Field 11 -- weighted # of milliseconds spent doing I/Os - This field is incremented at each I/O start, I/O completion, I/O - merge, or read of these stats by the number of I/Os in progress - (field 9) times the number of milliseconds spent doing I/O since the - last update of this field. This can provide an easy measure of both - I/O completion time and the backlog that may be accumulating. - - -To avoid introducing performance bottlenecks, no locks are held while -modifying these counters. This implies that minor inaccuracies may be -introduced when changes collide, so (for instance) adding up all the -read I/Os issued per partition should equal those made to the disks ... -but due to the lack of locking it may only be very close. - -In 2.6, there are counters for each cpu, which made the lack of locking -almost a non-issue. When the statistics are read, the per-cpu counters -are summed (possibly overflowing the unsigned 32-bit variable they are -summed to) and the result given to the user. There is no convenient -user interface for accessing the per-cpu counters themselves. - -Disks vs Partitions -------------------- - -There were significant changes between 2.4 and 2.6 in the I/O subsystem. -As a result, some statistic information disappeared. The translation from -a disk address relative to a partition to the disk address relative to -the host disk happens much earlier. All merges and timings now happen -at the disk level rather than at both the disk and partition level as -in 2.4. Consequently, you'll see a different statistics output on 2.6 for -partitions from that for disks. There are only *four* fields available -for partitions on 2.6 machines. This is reflected in the examples above. - -Field 1 -- # of reads issued - This is the total number of reads issued to this partition. -Field 2 -- # of sectors read - This is the total number of sectors requested to be read from this - partition. -Field 3 -- # of writes issued - This is the total number of writes issued to this partition. -Field 4 -- # of sectors written - This is the total number of sectors requested to be written to - this partition. - -Note that since the address is translated to a disk-relative one, and no -record of the partition-relative address is kept, the subsequent success -or failure of the read cannot be attributed to the partition. In other -words, the number of reads for partitions is counted slightly before time -of queuing for partitions, and at completion for whole disks. This is -a subtle distinction that is probably uninteresting for most cases. - -Additional notes ----------------- - -In 2.6, sysfs is not mounted by default. If your distribution of -Linux hasn't added it already, here's the line you'll want to add to -your /etc/fstab: - -none /sys sysfs defaults 0 0 - - -In 2.6, all disk statistics were removed from /proc/stat. In 2.4, they -appear in both /proc/partitions and /proc/stat, although the ones in -/proc/stat take a very different format from those in /proc/partitions -(see proc(5), if your system has it.) - --- ricklind[AT]us.ibm[DOT]com +I/O statistics fields +--------------- + +Based on kernel version 2.6.20. Page generated on 2007-02-07 22:05 EST +Last modified Sep 30, 2003 + +Since 2.4.20 (and some versions before, with patches), and 2.5.45, +more extensive disk statistics have been introduced to help measure disk +activity. Tools such as sar and iostat typically interpret these and do +the work for you, but in case you are interested in creating your own +tools, the fields are explained here. + +In 2.4 now, the information is found as additional fields in +/proc/partitions. In 2.6, the same information is found in two +places: one is in the file /proc/diskstats, and the other is within +the sysfs file system, which must be mounted in order to obtain +the information. Throughout this document we'll assume that sysfs +is mounted on /sys, although of course it may be mounted anywhere. +Both /proc/diskstats and sysfs use the same source for the information +and so should not differ. + +Here are examples of these different formats: + +2.4: + 3 0 39082680 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 3 1 9221278 hda1 35486 0 35496 38030 0 0 0 0 0 38030 38030 + + +2.6 sysfs: + 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 35486 38030 38030 38030 + +2.6 diskstats: + 3 0 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 3 1 hda1 35486 38030 38030 38030 + +On 2.4 you might execute "grep 'hda ' /proc/partitions". On 2.6, you have +a choice of "cat /sys/block/hda/stat" or "grep 'hda ' /proc/diskstats". +The advantage of one over the other is that the sysfs choice works well +if you are watching a known, small set of disks. /proc/diskstats may +be a better choice if you are watching a large number of disks because +you'll avoid the overhead of 50, 100, or 500 or more opens/closes with +each snapshot of your disk statistics. + +In 2.4, the statistics fields are those after the device name. In +the above example, the first field of statistics would be 446216. +By contrast, in 2.6 if you look at /sys/block/hda/stat, you'll +find just the eleven fields, beginning with 446216. If you look at +/proc/diskstats, the eleven fields will be preceded by the major and +minor device numbers, and device name. Each of these formats provide +eleven fields of statistics, each meaning exactly the same things. +All fields except field 9 are cumulative since boot. Field 9 should +go to zero as I/Os complete; all others only increase. Yes, these are +32 bit unsigned numbers, and on a very busy or long-lived system they +may wrap. Applications should be prepared to deal with that; unless +your observations are measured in large numbers of minutes or hours, +they should not wrap twice before you notice them. + +Each set of stats only applies to the indicated device; if you want +system-wide stats you'll have to find all the devices and sum them all up. + +Field 1 -- # of reads issued + This is the total number of reads completed successfully. +Field 2 -- # of reads merged, field 6 -- # of writes merged + Reads and writes which are adjacent to each other may be merged for + efficiency. Thus two 4K reads may become one 8K read before it is + ultimately handed to the disk, and so it will be counted (and queued) + as only one I/O. This field lets you know how often this was done. +Field 3 -- # of sectors read + This is the total number of sectors read successfully. +Field 4 -- # of milliseconds spent reading + This is the total number of milliseconds spent by all reads (as + measured from __make_request() to end_that_request_last()). +Field 5 -- # of writes completed + This is the total number of writes completed successfully. +Field 7 -- # of sectors written + This is the total number of sectors written successfully. +Field 8 -- # of milliseconds spent writing + This is the total number of milliseconds spent by all writes (as + measured from __make_request() to end_that_request_last()). +Field 9 -- # of I/Os currently in progress + The only field that should go to zero. Incremented as requests are + given to appropriate request_queue_t and decremented as they finish. +Field 10 -- # of milliseconds spent doing I/Os + This field is increases so long as field 9 is nonzero. +Field 11 -- weighted # of milliseconds spent doing I/Os + This field is incremented at each I/O start, I/O completion, I/O + merge, or read of these stats by the number of I/Os in progress + (field 9) times the number of milliseconds spent doing I/O since the + last update of this field. This can provide an easy measure of both + I/O completion time and the backlog that may be accumulating. + + +To avoid introducing performance bottlenecks, no locks are held while +modifying these counters. This implies that minor inaccuracies may be +introduced when changes collide, so (for instance) adding up all the +read I/Os issued per partition should equal those made to the disks ... +but due to the lack of locking it may only be very close. + +In 2.6, there are counters for each cpu, which made the lack of locking +almost a non-issue. When the statistics are read, the per-cpu counters +are summed (possibly overflowing the unsigned 32-bit variable they are +summed to) and the result given to the user. There is no convenient +user interface for accessing the per-cpu counters themselves. + +Disks vs Partitions +------------------- + +There were significant changes between 2.4 and 2.6 in the I/O subsystem. +As a result, some statistic information disappeared. The translation from +a disk address relative to a partition to the disk address relative to +the host disk happens much earlier. All merges and timings now happen +at the disk level rather than at both the disk and partition level as +in 2.4. Consequently, you'll see a different statistics output on 2.6 for +partitions from that for disks. There are only *four* fields available +for partitions on 2.6 machines. This is reflected in the examples above. + +Field 1 -- # of reads issued + This is the total number of reads issued to this partition. +Field 2 -- # of sectors read + This is the total number of sectors requested to be read from this + partition. +Field 3 -- # of writes issued + This is the total number of writes issued to this partition. +Field 4 -- # of sectors written + This is the total number of sectors requested to be written to + this partition. + +Note that since the address is translated to a disk-relative one, and no +record of the partition-relative address is kept, the subsequent success +or failure of the read cannot be attributed to the partition. In other +words, the number of reads for partitions is counted slightly before time +of queuing for partitions, and at completion for whole disks. This is +a subtle distinction that is probably uninteresting for most cases. + +Additional notes +---------------- + +In 2.6, sysfs is not mounted by default. If your distribution of +Linux hasn't added it already, here's the line you'll want to add to +your /etc/fstab: + +none /sys sysfs defaults 0 0 + + +In 2.6, all disk statistics were removed from /proc/stat. In 2.4, they +appear in both /proc/partitions and /proc/stat, although the ones in +/proc/stat take a very different format from those in /proc/partitions +(see proc(5), if your system has it.) + +-- ricklind[AT]us.ibm[DOT]com diff --git a/targets/znews-ss/system/probes/loadProbe.pl b/targets/znews-ss/system/probes/loadProbe.pl index 7f2e12dc8..3b648fd9c 100644 --- a/targets/znews-ss/system/probes/loadProbe.pl +++ b/targets/znews-ss/system/probes/loadProbe.pl @@ -1,101 +1,101 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "load"; -my $NAME = "LoadProbe"; -my $DELAY = 2500; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current CPU usage to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic CPU usage info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub cpuTime () { - my ($user, $nice, $sys, $idle, $iowait); - - local(*FIN); - open(FIN, ") { - chomp; - if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(\s+(\d+))?/o) { - ($user, $nice, $sys, $idle, $iowait) = ($1, $2, $3, $4, $6); - if (!defined($iowait)) { - $iowait = 0; - } - last; - } - } - close(FIN); - return ($user, $nice, $sys, $idle, $iowait); -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# save current cpu ticks -my($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = cpuTime(); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # retrieve new cpu ticks - my ($userN, $niceN, $sysN, $idleN, $iowaitN) = cpuTime(); - # compute delta cpu ticks - my ($user, $nice, $sys, $idle, $iowait) = - ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv, $iowaitN - $iowaitSv); - # store the new saved ticks - ($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = ($userN, $niceN, $sysN, $idleN, $iowaitN); - my $total = $user + $nice + $sys + $idle + $iowait; - my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), - $user/$total, $nice/$total, $sys/$total, $idle/$total, $iowait/$total); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "load"; +my $NAME = "LoadProbe"; +my $DELAY = 2500; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current CPU usage to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic CPU usage info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub cpuTime () { + my ($user, $nice, $sys, $idle, $iowait); + + local(*FIN); + open(FIN, ") { + chomp; + if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(\s+(\d+))?/o) { + ($user, $nice, $sys, $idle, $iowait) = ($1, $2, $3, $4, $6); + if (!defined($iowait)) { + $iowait = 0; + } + last; + } + } + close(FIN); + return ($user, $nice, $sys, $idle, $iowait); +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# save current cpu ticks +my($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = cpuTime(); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # retrieve new cpu ticks + my ($userN, $niceN, $sysN, $idleN, $iowaitN) = cpuTime(); + # compute delta cpu ticks + my ($user, $nice, $sys, $idle, $iowait) = + ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv, $iowaitN - $iowaitSv); + # store the new saved ticks + ($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = ($userN, $niceN, $sysN, $idleN, $iowaitN); + my $total = $user + $nice + $sys + $idle + $iowait; + my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), + $user/$total, $nice/$total, $sys/$total, $idle/$total, $iowait/$total); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss/system/probes/runApachetop.pl b/targets/znews-ss/system/probes/runApachetop.pl index 2d9a80a4d..741ee43f6 100644 --- a/targets/znews-ss/system/probes/runApachetop.pl +++ b/targets/znews-ss/system/probes/runApachetop.pl @@ -1,16 +1,16 @@ -#!/usr/bin/perl -w - -use strict; - -############################# -my $APACHE_LOG = "/var/log/apache2/access-delegate.log"; -my $APACHETOP_LOG = "../../log/apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - -if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; +#!/usr/bin/perl -w + +use strict; + +############################# +my $APACHE_LOG = "/var/log/apache2/access-delegate.log"; +my $APACHETOP_LOG = "../../log/apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + +if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; diff --git a/targets/znews-ss/system/webpages/www1/index.html b/targets/znews-ss/system/webpages/www1/index.html index 050159b89..4ec9f5304 100644 --- a/targets/znews-ss/system/webpages/www1/index.html +++ b/targets/znews-ss/system/webpages/www1/index.html @@ -1,46 +1,46 @@ - - -Somewhere Over the Rainbow - - -

Z.com News - Hello World! (Low-fidelity Settings)

- -We apologize for this text-only content, as we are currently swamped with visitors. Thank you for your patience as we work hard to serve your requests. (This file is a little over 3 KB.) -

-SYDNEY, Australia (Reuters) -- In death as in life, iconic TV naturalist Steve Irwin captivated millions worldwide and clogged the Internet as fans from Guam to Glasgow reacted with disbelief to news "The Crocodile Hunter" was dead. -

-Some Web sites groaned to a halt within hours of the first reports Monday that Irwin had been killed by a stingray's barb through his chest in a freak diving accident off Australia's northeast coast. -

-Web measurement company Hitwise said Irwin's death was the biggest news event read by Australians on the Internet since two Australian miners were trapped by a mine collapse in southern Tasmania state in late April. -

-"We noticed that the Web site www.crocodilehunter.com increased in popularity quite substantially. It became the number one entertainment personality Web site in Australia yesterday and in the United States it also became the third most popular," Hitwise Asia-Pacific marketing director James Borg told Reuters. -

-Australian news Web sites struggled to keep up with demand. -

-The Australian Broadcasting Corp.'s site (www.abc.com.au) had to temporarily shut down, posting a notice Monday that it was experiencing higher than normal traffic. -

-It resumed soon after in a low-bandwidth format to cope with hundreds of thousands of hits. -

-Newspaper Web sites also wobbled but kept up with demand. -

-A spokesman for The Sydney Morning Herald's site, www.smh.com.au, said it had experienced a "huge" 40 percent spike in page impressions compared with the previous week's average weekday number of about 500,000. -

-There was also a 70 percent jump in visitors to its pages, the spokesman said. -

-That pattern was mirrored around the world, with Irwin's death leading major news Web sites such as CNN.com and U.S. and British newspaper Web sites, as well as swamping their most viewed and most emailed categories. -

-Web logs and Internet feedback pages were also awash with postings from shocked readers from around the world, many of them from Americans charmed by Irwin's quirky style and his typically Australian catchphrase of "crikey." -

-Irwin first found fame in the United States before his "Crocodile Hunter" documentaries on U.S.-based television company Discovery Communications' Animal Planet attracted a global audience of 200 million -- 10 times Australia's population. -

-"Crikey!, I miss him so much," Tina Treece from Pittsburgh, Pennsylvania, posted on CNN.com's feedback page CNN Exchange. -

-The site had contributions from readers in Guam, Romania, Thailand, France, Scotland, India, New Zealand, Canada, Brunei, Britain, Malaysia, Denmark and the Netherlands. -

-Many faced the problem of explaining to their children how one of their favorite TV characters had died. -

-"Why did it have to be Steve Irwin?" 11-year-old Daniel told Australian Associated Press. -

-Copyright 2006 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed. - - + + +Somewhere Over the Rainbow + + +

Z.com News - Hello World! (Low-fidelity Settings)

+ +We apologize for this text-only content, as we are currently swamped with visitors. Thank you for your patience as we work hard to serve your requests. (This file is a little over 3 KB.) +

+SYDNEY, Australia (Reuters) -- In death as in life, iconic TV naturalist Steve Irwin captivated millions worldwide and clogged the Internet as fans from Guam to Glasgow reacted with disbelief to news "The Crocodile Hunter" was dead. +

+Some Web sites groaned to a halt within hours of the first reports Monday that Irwin had been killed by a stingray's barb through his chest in a freak diving accident off Australia's northeast coast. +

+Web measurement company Hitwise said Irwin's death was the biggest news event read by Australians on the Internet since two Australian miners were trapped by a mine collapse in southern Tasmania state in late April. +

+"We noticed that the Web site www.crocodilehunter.com increased in popularity quite substantially. It became the number one entertainment personality Web site in Australia yesterday and in the United States it also became the third most popular," Hitwise Asia-Pacific marketing director James Borg told Reuters. +

+Australian news Web sites struggled to keep up with demand. +

+The Australian Broadcasting Corp.'s site (www.abc.com.au) had to temporarily shut down, posting a notice Monday that it was experiencing higher than normal traffic. +

+It resumed soon after in a low-bandwidth format to cope with hundreds of thousands of hits. +

+Newspaper Web sites also wobbled but kept up with demand. +

+A spokesman for The Sydney Morning Herald's site, www.smh.com.au, said it had experienced a "huge" 40 percent spike in page impressions compared with the previous week's average weekday number of about 500,000. +

+There was also a 70 percent jump in visitors to its pages, the spokesman said. +

+That pattern was mirrored around the world, with Irwin's death leading major news Web sites such as CNN.com and U.S. and British newspaper Web sites, as well as swamping their most viewed and most emailed categories. +

+Web logs and Internet feedback pages were also awash with postings from shocked readers from around the world, many of them from Americans charmed by Irwin's quirky style and his typically Australian catchphrase of "crikey." +

+Irwin first found fame in the United States before his "Crocodile Hunter" documentaries on U.S.-based television company Discovery Communications' Animal Planet attracted a global audience of 200 million -- 10 times Australia's population. +

+"Crikey!, I miss him so much," Tina Treece from Pittsburgh, Pennsylvania, posted on CNN.com's feedback page CNN Exchange. +

+The site had contributions from readers in Guam, Romania, Thailand, France, Scotland, India, New Zealand, Canada, Brunei, Britain, Malaysia, Denmark and the Netherlands. +

+Many faced the problem of explaining to their children how one of their favorite TV characters had died. +

+"Why did it have to be Steve Irwin?" 11-year-old Daniel told Australian Associated Press. +

+Copyright 2006 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed. + + diff --git a/targets/znews-ss/system/webpages/www3/index.html b/targets/znews-ss/system/webpages/www3/index.html index d5801caa4..dee934b7c 100644 --- a/targets/znews-ss/system/webpages/www3/index.html +++ b/targets/znews-ss/system/webpages/www3/index.html @@ -1,11 +1,11 @@ - - -Somewhere Over the Rainbow - - -

Z.com News - Hello World! (Medium-fidelity Settings)

-This file contains an 800x600 pixel image. The total size of this file is approximately 53K. -
- - + + +Somewhere Over the Rainbow + + +

Z.com News - Hello World! (Medium-fidelity Settings)

+This file contains an 800x600 pixel image. The total size of this file is approximately 53K. +
+ + \ No newline at end of file diff --git a/targets/znews-ss/system/webpages/www5/cgi-bin/computePi.pl b/targets/znews-ss/system/webpages/www5/cgi-bin/computePi.pl index 6871ac9b4..235516a09 100644 --- a/targets/znews-ss/system/webpages/www5/cgi-bin/computePi.pl +++ b/targets/znews-ss/system/webpages/www5/cgi-bin/computePi.pl @@ -1,118 +1,118 @@ -#!/usr/bin/perl - -use strict; -use Carp; -use Math::BigFloat; -use Class::Struct qw(struct); -use Data::Dumper; - -# With due homage to Mathsoft's site: -# http://www.mathsoft.com/asolve/constant/pi/pi.html - -# Set the global precision. Faster than passing it everywhichwhere. -my $precision = @ARGV>0?$ARGV[0]:512; - -# Set the iteration count. -my $maxIterations = @ARGV>1?$ARGV[1]:10; - -# Set the verbose debugging flag. -my $debugVerbose = 0; - -# Constants: -my $_1 = Math::BigFloat->new(1); -my $_2 = Math::BigFloat->new(2); -my $_3 = Math::BigFloat->new(3); -my $_4 = Math::BigFloat->new(4); -my $_6 = Math::BigFloat->new(6); -my $_8 = Math::BigFloat->new(8); -my $_239 = Math::BigFloat->new(239); -my $_half = Math::BigFloat->new(0.5); -my $_fifth = Math::BigFloat->new(0.2); -my $_25th = Math::BigFloat->new(0.04); -my $_239th = inv($_239); -my $_57121th = inv($_239*$_239); - - -# Utility methods: -sub div { - my $a = shift; - my $b = shift; - return new Math::BigFloat $a->copy()->fdiv($b,$precision); -} -sub inv { # Inverse (1/x) function. - my $a = shift; - return new Math::BigFloat $_1->copy()->fdiv($a,$precision); -} -sub root2 { - my $self = shift; - return new Math::BigFloat $self->copy()->fsqrt($precision); -} -sub root4 { - my $self = shift; - return root2(root2($self)); -} -sub pow4 { - my $self = shift; - my $square = round($self*$self); - return round($square*$square); -} -sub round { - my $self = shift; - return new Math::BigFloat $self->copy()->fround($precision); -} - -# Method 4: - -# This uses Ramanujan's elliptic integral-based technique to -# compute Pi monstrously quickly. -# -# This algorithm is neat, since it is quartically convergent - -# that means that the error goes as 4^(-iteration_count). -# -# In other words, one more step = four times the # of correct digits. - -sub RamanujanEI { - if (@_) { - my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. - - my $z_4_term = root4($_1 - pow4($z)); - my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); - - my $z_next_plus_1 = $z_next + $_1; - - my $a_next = pow4($z_next_plus_1) * $a - - $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); - $a_next = round($a_next); - return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; - - } else { # Seed the recurrence - my $a = $_6-$_4*root2($_2); - return [ $a, root2($_2)-$_1, $_8, inv($a)]; - } -} - - - -###################################################################### -# -# Main routine: -# -# - -my $iterResult = RamanujanEI(); -for (my $i=1; $i<$maxIterations; $i++) { - $iterResult = RamanujanEI($iterResult); -} -my $piValue = ${$iterResult}[-1]; -my $piStr = "" . $piValue; - -my $CHUNK = 32; -my $i = $CHUNK + 1; -print "Content-type: text/plain\r\n"; -print "Content-length: 570\r\n\r\n"; -print "Pi_512 :=\n"; -print " " . substr($piValue, 0, $i) . "\n"; -for (; $i < length($piValue) ; $i+=$CHUNK) { - print " " . substr($piValue, $i, $CHUNK) . "\n"; -} - +#!/usr/bin/perl + +use strict; +use Carp; +use Math::BigFloat; +use Class::Struct qw(struct); +use Data::Dumper; + +# With due homage to Mathsoft's site: +# http://www.mathsoft.com/asolve/constant/pi/pi.html + +# Set the global precision. Faster than passing it everywhichwhere. +my $precision = @ARGV>0?$ARGV[0]:512; + +# Set the iteration count. +my $maxIterations = @ARGV>1?$ARGV[1]:10; + +# Set the verbose debugging flag. +my $debugVerbose = 0; + +# Constants: +my $_1 = Math::BigFloat->new(1); +my $_2 = Math::BigFloat->new(2); +my $_3 = Math::BigFloat->new(3); +my $_4 = Math::BigFloat->new(4); +my $_6 = Math::BigFloat->new(6); +my $_8 = Math::BigFloat->new(8); +my $_239 = Math::BigFloat->new(239); +my $_half = Math::BigFloat->new(0.5); +my $_fifth = Math::BigFloat->new(0.2); +my $_25th = Math::BigFloat->new(0.04); +my $_239th = inv($_239); +my $_57121th = inv($_239*$_239); + + +# Utility methods: +sub div { + my $a = shift; + my $b = shift; + return new Math::BigFloat $a->copy()->fdiv($b,$precision); +} +sub inv { # Inverse (1/x) function. + my $a = shift; + return new Math::BigFloat $_1->copy()->fdiv($a,$precision); +} +sub root2 { + my $self = shift; + return new Math::BigFloat $self->copy()->fsqrt($precision); +} +sub root4 { + my $self = shift; + return root2(root2($self)); +} +sub pow4 { + my $self = shift; + my $square = round($self*$self); + return round($square*$square); +} +sub round { + my $self = shift; + return new Math::BigFloat $self->copy()->fround($precision); +} + +# Method 4: + +# This uses Ramanujan's elliptic integral-based technique to +# compute Pi monstrously quickly. +# +# This algorithm is neat, since it is quartically convergent - +# that means that the error goes as 4^(-iteration_count). +# +# In other words, one more step = four times the # of correct digits. + +sub RamanujanEI { + if (@_) { + my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. + + my $z_4_term = root4($_1 - pow4($z)); + my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); + + my $z_next_plus_1 = $z_next + $_1; + + my $a_next = pow4($z_next_plus_1) * $a - + $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); + $a_next = round($a_next); + return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; + + } else { # Seed the recurrence + my $a = $_6-$_4*root2($_2); + return [ $a, root2($_2)-$_1, $_8, inv($a)]; + } +} + + + +###################################################################### +# +# Main routine: +# +# + +my $iterResult = RamanujanEI(); +for (my $i=1; $i<$maxIterations; $i++) { + $iterResult = RamanujanEI($iterResult); +} +my $piValue = ${$iterResult}[-1]; +my $piStr = "" . $piValue; + +my $CHUNK = 32; +my $i = $CHUNK + 1; +print "Content-type: text/plain\r\n"; +print "Content-length: 570\r\n\r\n"; +print "Pi_512 :=\n"; +print " " . substr($piValue, 0, $i) . "\n"; +for (; $i < length($piValue) ; $i+=$CHUNK) { + print " " . substr($piValue, $i, $CHUNK) . "\n"; +} + diff --git a/targets/znews-ss/system/webpages/www5/cgi-bin/piComputeLib.pl b/targets/znews-ss/system/webpages/www5/cgi-bin/piComputeLib.pl index c14fe9400..23ce98e01 100644 --- a/targets/znews-ss/system/webpages/www5/cgi-bin/piComputeLib.pl +++ b/targets/znews-ss/system/webpages/www5/cgi-bin/piComputeLib.pl @@ -1,233 +1,233 @@ -#!/usr/bin/perl - -#map$x+=(-1)**$_*4/(2*$_+1),0..1e6;die$x - -use strict; -use Carp; -use Math::BigFloat; -use Class::Struct qw(struct); -use Data::Dumper; - -# With due homage to Mathsoft's site: -# http://www.mathsoft.com/asolve/constant/pi/pi.html - -# Set the global precision. Faster than passing it everywhichwhere. -my $precision = @ARGV>0?$ARGV[0]:10; - -# Set the iteration count. -my $maxIterations = @ARGV>1?$ARGV[1]:10; - -# Set the verbose debugging flag. -my $debugVerbose = 0; - -# Constants: -my $_1 = Math::BigFloat->new(1); -my $_2 = Math::BigFloat->new(2); -my $_3 = Math::BigFloat->new(3); -my $_4 = Math::BigFloat->new(4); -my $_6 = Math::BigFloat->new(6); -my $_8 = Math::BigFloat->new(8); -my $_239 = Math::BigFloat->new(239); -my $_half = Math::BigFloat->new(0.5); -my $_fifth = Math::BigFloat->new(0.2); -my $_25th = Math::BigFloat->new(0.04); -my $_239th = inv($_239); -my $_57121th = inv($_239*$_239); - - -# Utility methods: -sub div { - my $a = shift; - my $b = shift; - return new Math::BigFloat $a->copy()->fdiv($b,$precision); -} -sub inv { # Inverse (1/x) function. - my $a = shift; - return new Math::BigFloat $_1->copy()->fdiv($a,$precision); -} -sub root2 { - my $self = shift; - return new Math::BigFloat $self->copy()->fsqrt($precision); -} -sub root4 { - my $self = shift; - return root2(root2($self)); -} -sub pow4 { - my $self = shift; - my $square = round($self*$self); - return round($square*$square); -} -sub round { - my $self = shift; - return new Math::BigFloat $self->copy()->fround($precision); -} - - -# Method 1: - -# This gives Archimedes' approximation, -# 3+10/71 < Pi < 3+1/7 -# ...on the 4th iteration. - -sub BorchardtPfaff { - if (@_) { - my ($a,$b) = @{shift()}; # Retrieve the last iteration. - my $a_next = div( $_2*$a*$b, $a+$b ); - my $b_next = root2($a_next*$b); - return [ round($a_next), round($b_next) ]; - } else { # Seed the recurrence - return [ $_2*root2($_3), $_3 ]; - } -} - -# Method 2: - -# This uses Borwein's AGM method to compute Pi very quickly. -# The 'AGM' is short for the iterated arithmetic-geometric mean; -# which was looked at by Lagrange and Gauss way back in 1799. -# We basically look at the tuple [a,b] which holds the arithmetic -# and geometric means of the previous iteration: -# a[n+1] = (a[n] + b[n])/2 // Arithmetic mean -# b[n+1] = sqrt(a[n] * b[n]) // Geometric mean -# -# This algorithm is neat, since it is quadratically convergent - -# that means that the error goes as 2^(-iteration_count). -# -# In other words, one more step = twice the # of correct digits. - -sub BorweinAGM { - if (@_) { - my ($a,$b,$pi) = @{shift()}; # Retrieve the last iteration. - - my $sqrt_a = root2($a); - my $inv_sqrt_a = inv($sqrt_a); - my $b_plus_1 = $b+$_1; - - my $a_next = $_half * ($sqrt_a+$inv_sqrt_a); - my $b_next = div( $b*$sqrt_a+$inv_sqrt_a , $b_plus_1 ); - my $pi_next = $pi*div( $a_next+$_1 , $b_next+$_1 ); - return [ round($a_next), round($b_next), round($pi_next) ]; - - } else { # Seed the recurrence - my $a0 = root2($_2); - my $pi0 = $_2+root2($_2); - my $b1 = root2($a0); # = root4($_2) - my $a1 = $_half * ($b1 + inv($b1)); - - return [ round($a1), round($b1), round($pi0 * div($a1 + $_1, $b1 + $_1)) ]; - } -} - -# Method 3: - -# The arctangent approximation, as determined by Machin (1706). -# Pi = 4(4 * arctan(1/5) - arctan(1/239)), -# ...where arctan(x) = sum( (-1)^k/(2*k+1)*x^(2*k+1), x=0..infinity). - -sub ArctanPi { - if (@_) { - my ($k, $atan5, $atan239, $denom5, $denom239, $pi) = @{shift()}; # Retrieve the last iteration. - - $k++; - my $parity=$k & 1; - $denom5 = $denom5 * $_25th; - - my $inv_2_k_plus_1='Math::BigFloat'->new(2*$k+1); - - my $term5 = div($denom5, $inv_2_k_plus_1 ); - $denom239 = $denom239 * $_57121th; - - my $term239 = div($denom239, $inv_2_k_plus_1 ); - $atan5 = $parity ? $atan5 - $term5 : $atan5 + $term5; - $atan239 = $parity ? $atan239 - $term239 : $atan239 + $term239; - my $pi = $_4*($_4*$atan5 - $atan239); - - return [ $k, round($atan5), round($atan239), - round($denom5), round($denom239), round($pi) ]; - } else { # Seed the recurrence - my ($k, $atan5, $atan239) = (0, $_fifth, $_239th); - return [ $k, $atan5, $atan239, $atan5, $atan239, $_4*($_4*$atan5 - $atan239)]; - } -} - -# Method 4: - -# This uses Ramanujan's elliptic integral-based technique to -# compute Pi monstrously quickly. -# -# This algorithm is neat, since it is quartically convergent - -# that means that the error goes as 4^(-iteration_count). -# -# In other words, one more step = four times the # of correct digits. - -sub RamanujanEI { - if (@_) { - my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. - - my $z_4_term = root4($_1 - pow4($z)); - my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); - - my $z_next_plus_1 = $z_next + $_1; - - my $a_next = pow4($z_next_plus_1) * $a - - $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); - $a_next = round($a_next); - return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; - - } else { # Seed the recurrence - my $a = $_6-$_4*root2($_2); - return [ $a, root2($_2)-$_1, $_8, inv($a)]; - } -} - - - -###################################################################### -# -# Main routine: -# -# - -my $methods = ["BorchardtPfaff", "ArctanPi", "BorweinAGM", "RamanujanEI" ]; - -my $longestMethodLen=0; -foreach my $method (@{$methods}) { - $longestMethodLen = length($method) if length($method) > $longestMethodLen; -} - -my $pis = [ BorchardtPfaff(), ArctanPi(), BorweinAGM(), RamanujanEI() ]; - -for (my $i=0; $i<$maxIterations; $i++) { - print "Iteration $i:\n"; - if (!$debugVerbose) { - for (my $j=0; $j<@{$methods}; $j++) { - - # The following piece of line noise is equivalent to the - # STL C++, " - - # piValue = pis[j].last(); - - # ", if the declaration for pis is: - - # std::vector > pis; - # - - my $methodName = ${$methods}[$j]; - my $piValue = ${${$pis}[$j]}[-1]; - print ${$methods}[$j] . ": " . - ' ' x ($longestMethodLen - length($methodName)) . - $piValue . "\n"; - } - print "\n"; - } - print(Dumper($pis)) if $debugVerbose; - - last if $i+1 == $maxIterations; - - $pis = [ BorchardtPfaff(${$pis}[0]), - ArctanPi(${$pis}[1]), - BorweinAGM(${$pis}[2]), - RamanujanEI(${$pis}[3]) ]; -} - +#!/usr/bin/perl + +#map$x+=(-1)**$_*4/(2*$_+1),0..1e6;die$x + +use strict; +use Carp; +use Math::BigFloat; +use Class::Struct qw(struct); +use Data::Dumper; + +# With due homage to Mathsoft's site: +# http://www.mathsoft.com/asolve/constant/pi/pi.html + +# Set the global precision. Faster than passing it everywhichwhere. +my $precision = @ARGV>0?$ARGV[0]:10; + +# Set the iteration count. +my $maxIterations = @ARGV>1?$ARGV[1]:10; + +# Set the verbose debugging flag. +my $debugVerbose = 0; + +# Constants: +my $_1 = Math::BigFloat->new(1); +my $_2 = Math::BigFloat->new(2); +my $_3 = Math::BigFloat->new(3); +my $_4 = Math::BigFloat->new(4); +my $_6 = Math::BigFloat->new(6); +my $_8 = Math::BigFloat->new(8); +my $_239 = Math::BigFloat->new(239); +my $_half = Math::BigFloat->new(0.5); +my $_fifth = Math::BigFloat->new(0.2); +my $_25th = Math::BigFloat->new(0.04); +my $_239th = inv($_239); +my $_57121th = inv($_239*$_239); + + +# Utility methods: +sub div { + my $a = shift; + my $b = shift; + return new Math::BigFloat $a->copy()->fdiv($b,$precision); +} +sub inv { # Inverse (1/x) function. + my $a = shift; + return new Math::BigFloat $_1->copy()->fdiv($a,$precision); +} +sub root2 { + my $self = shift; + return new Math::BigFloat $self->copy()->fsqrt($precision); +} +sub root4 { + my $self = shift; + return root2(root2($self)); +} +sub pow4 { + my $self = shift; + my $square = round($self*$self); + return round($square*$square); +} +sub round { + my $self = shift; + return new Math::BigFloat $self->copy()->fround($precision); +} + + +# Method 1: + +# This gives Archimedes' approximation, +# 3+10/71 < Pi < 3+1/7 +# ...on the 4th iteration. + +sub BorchardtPfaff { + if (@_) { + my ($a,$b) = @{shift()}; # Retrieve the last iteration. + my $a_next = div( $_2*$a*$b, $a+$b ); + my $b_next = root2($a_next*$b); + return [ round($a_next), round($b_next) ]; + } else { # Seed the recurrence + return [ $_2*root2($_3), $_3 ]; + } +} + +# Method 2: + +# This uses Borwein's AGM method to compute Pi very quickly. +# The 'AGM' is short for the iterated arithmetic-geometric mean; +# which was looked at by Lagrange and Gauss way back in 1799. +# We basically look at the tuple [a,b] which holds the arithmetic +# and geometric means of the previous iteration: +# a[n+1] = (a[n] + b[n])/2 // Arithmetic mean +# b[n+1] = sqrt(a[n] * b[n]) // Geometric mean +# +# This algorithm is neat, since it is quadratically convergent - +# that means that the error goes as 2^(-iteration_count). +# +# In other words, one more step = twice the # of correct digits. + +sub BorweinAGM { + if (@_) { + my ($a,$b,$pi) = @{shift()}; # Retrieve the last iteration. + + my $sqrt_a = root2($a); + my $inv_sqrt_a = inv($sqrt_a); + my $b_plus_1 = $b+$_1; + + my $a_next = $_half * ($sqrt_a+$inv_sqrt_a); + my $b_next = div( $b*$sqrt_a+$inv_sqrt_a , $b_plus_1 ); + my $pi_next = $pi*div( $a_next+$_1 , $b_next+$_1 ); + return [ round($a_next), round($b_next), round($pi_next) ]; + + } else { # Seed the recurrence + my $a0 = root2($_2); + my $pi0 = $_2+root2($_2); + my $b1 = root2($a0); # = root4($_2) + my $a1 = $_half * ($b1 + inv($b1)); + + return [ round($a1), round($b1), round($pi0 * div($a1 + $_1, $b1 + $_1)) ]; + } +} + +# Method 3: + +# The arctangent approximation, as determined by Machin (1706). +# Pi = 4(4 * arctan(1/5) - arctan(1/239)), +# ...where arctan(x) = sum( (-1)^k/(2*k+1)*x^(2*k+1), x=0..infinity). + +sub ArctanPi { + if (@_) { + my ($k, $atan5, $atan239, $denom5, $denom239, $pi) = @{shift()}; # Retrieve the last iteration. + + $k++; + my $parity=$k & 1; + $denom5 = $denom5 * $_25th; + + my $inv_2_k_plus_1='Math::BigFloat'->new(2*$k+1); + + my $term5 = div($denom5, $inv_2_k_plus_1 ); + $denom239 = $denom239 * $_57121th; + + my $term239 = div($denom239, $inv_2_k_plus_1 ); + $atan5 = $parity ? $atan5 - $term5 : $atan5 + $term5; + $atan239 = $parity ? $atan239 - $term239 : $atan239 + $term239; + my $pi = $_4*($_4*$atan5 - $atan239); + + return [ $k, round($atan5), round($atan239), + round($denom5), round($denom239), round($pi) ]; + } else { # Seed the recurrence + my ($k, $atan5, $atan239) = (0, $_fifth, $_239th); + return [ $k, $atan5, $atan239, $atan5, $atan239, $_4*($_4*$atan5 - $atan239)]; + } +} + +# Method 4: + +# This uses Ramanujan's elliptic integral-based technique to +# compute Pi monstrously quickly. +# +# This algorithm is neat, since it is quartically convergent - +# that means that the error goes as 4^(-iteration_count). +# +# In other words, one more step = four times the # of correct digits. + +sub RamanujanEI { + if (@_) { + my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. + + my $z_4_term = root4($_1 - pow4($z)); + my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); + + my $z_next_plus_1 = $z_next + $_1; + + my $a_next = pow4($z_next_plus_1) * $a - + $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); + $a_next = round($a_next); + return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; + + } else { # Seed the recurrence + my $a = $_6-$_4*root2($_2); + return [ $a, root2($_2)-$_1, $_8, inv($a)]; + } +} + + + +###################################################################### +# +# Main routine: +# +# + +my $methods = ["BorchardtPfaff", "ArctanPi", "BorweinAGM", "RamanujanEI" ]; + +my $longestMethodLen=0; +foreach my $method (@{$methods}) { + $longestMethodLen = length($method) if length($method) > $longestMethodLen; +} + +my $pis = [ BorchardtPfaff(), ArctanPi(), BorweinAGM(), RamanujanEI() ]; + +for (my $i=0; $i<$maxIterations; $i++) { + print "Iteration $i:\n"; + if (!$debugVerbose) { + for (my $j=0; $j<@{$methods}; $j++) { + + # The following piece of line noise is equivalent to the + # STL C++, " + + # piValue = pis[j].last(); + + # ", if the declaration for pis is: + + # std::vector > pis; + # + + my $methodName = ${$methods}[$j]; + my $piValue = ${${$pis}[$j]}[-1]; + print ${$methods}[$j] . ": " . + ' ' x ($longestMethodLen - length($methodName)) . + $piValue . "\n"; + } + print "\n"; + } + print(Dumper($pis)) if $debugVerbose; + + last if $i+1 == $maxIterations; + + $pis = [ BorchardtPfaff(${$pis}[0]), + ArctanPi(${$pis}[1]), + BorweinAGM(${$pis}[2]), + RamanujanEI(${$pis}[3]) ]; +} + diff --git a/targets/znews-ss/system/webpages/www5/index.php b/targets/znews-ss/system/webpages/www5/index.php index 6c66bd469..b3b52ea5e 100644 --- a/targets/znews-ss/system/webpages/www5/index.php +++ b/targets/znews-ss/system/webpages/www5/index.php @@ -1,84 +1,84 @@ - 1 && time()%$content == 0) { - echo << - -Please come back... - - -I (the server) am swamped right now!!
-Please kindly come back in a couple of minutes.
-Sorry for the inconvenience, and thanks for understanding! - - -REJECT; - exit(); -} - -/* -$mysql_url = ''; -$mysql_user = ''; -$mysql_password = ''; -$mysql_db = ''; - -$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) - or die('Could not connect: ' . mysql_error()); - -$mydb = mysql_select_db($mysql_db, $link); -if(!$mydb) { - die('Could not select Test database: ' . mysql_error()); -} - -// Performing SQL query -$query = "SELECT COUNT(*) FROM cur"; -$result = mysql_query($query, $link) - or die('Query COUNT failed: ' . mysql_error()); -$row = mysql_fetch_row($result); -if ($row != false) { - $numItems = $row[0]; -} - -$idx = rand(1, $numItems); -$query = "SELECT cur_text FROM cur LIMIT $idx,1"; -$result = mysql_query($query, $link) - or die('Query item $idx failed: ' . mysql_error()); -$row = mysql_fetch_row($result); -if($row != false) { - $text = $row[0]; -} -*/ -$idx = 0; -$text = ""; - -echo << - -Somewhere Over the Rainbow - - - -

Z.com News - Hello World! (High-fidelity Settings)

-This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. - - - - -END - -?> + 1 && time()%$content == 0) { + echo << + +Please come back... + + +I (the server) am swamped right now!!
+Please kindly come back in a couple of minutes.
+Sorry for the inconvenience, and thanks for understanding! + + +REJECT; + exit(); +} + +/* +$mysql_url = ''; +$mysql_user = ''; +$mysql_password = ''; +$mysql_db = ''; + +$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) + or die('Could not connect: ' . mysql_error()); + +$mydb = mysql_select_db($mysql_db, $link); +if(!$mydb) { + die('Could not select Test database: ' . mysql_error()); +} + +// Performing SQL query +$query = "SELECT COUNT(*) FROM cur"; +$result = mysql_query($query, $link) + or die('Query COUNT failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if ($row != false) { + $numItems = $row[0]; +} + +$idx = rand(1, $numItems); +$query = "SELECT cur_text FROM cur LIMIT $idx,1"; +$result = mysql_query($query, $link) + or die('Query item $idx failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if($row != false) { + $text = $row[0]; +} +*/ +$idx = 0; +$text = ""; + +echo << + +Somewhere Over the Rainbow + + + +

Z.com News - Hello World! (High-fidelity Settings)

+This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. + + + + +END + +?> diff --git a/targets/znews-ss_2/log/topic/effectorBus.log b/targets/znews-ss_2/log/topic/effectorBus.log index a70dc671f..51df60945 100644 --- a/targets/znews-ss_2/log/topic/effectorBus.log +++ b/targets/znews-ss_2/log/topic/effectorBus.log @@ -1 +1 @@ -{location=10.0.2.15, name=blackhole, msg-created=1347630591011, action=EXECUTE, channel=topic/effectorBus, msg-sent=1347630591011, argument_size=1, argument_0=client=10.0.2.2} +{location=10.0.2.15, name=blackhole, msg-created=1347630591011, action=EXECUTE, channel=topic/effectorBus, msg-sent=1347630591011, argument_size=1, argument_0=client=10.0.2.2} diff --git a/targets/znews-ss_2/log/topic/gaugeBus.log b/targets/znews-ss_2/log/topic/gaugeBus.log index 92bf5ae39..90ece3525 100644 --- a/targets/znews-ss_2/log/topic/gaugeBus.log +++ b/targets/znews-ss_2/log/topic/gaugeBus.log @@ -1,191 +1,191 @@ -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiagnosisGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness::x, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=DG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=DiagnosisGaugeT} -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.End2EndRespTimeGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=end2endRespTime(delegate.oracle)::c0.experRespTime, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=EERTG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=ResponseTimeGaugeT} -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.EchoGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness(c1)::c0.maliciousness, setupParam_size=3, mapping_1=maliciousness(c2)::c1.maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357101, action=CREATE, gaugeName=EG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630357101, gaugeType=MaliciousnessGaugeT} -{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.2, mapping_0=load::s0.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357102, action=CREATE, gaugeName=LoG0, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357102, gaugeType=LoadGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357187, action=REPORT_CREATED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630357187, gaugeType=DiagnosisGaugeT} -{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357189, action=REPORT_CREATED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630357189, gaugeType=ResponseTimeGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357191, action=REPORT_CREATED, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630357191, gaugeType=MaliciousnessGaugeT} -{uid=LoadGaugeT0914094557193@10.0.2.2, beaconPer=20000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357193, action=REPORT_CREATED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630357193, gaugeType=LoadGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630377197, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630377197} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630387192, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387192} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630387194, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387194} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630387196, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387196} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630397201, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630397201} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630417198, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417198} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630417200, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417200} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630417202, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417202} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630417205, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417205} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630437209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630437209} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630447204, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447204} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630447206, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447206} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630447209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447209} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=DiagnosisGaugeT} -{uid=LoadGaugeT0914094557193@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=LoadGaugeT} -{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454372, action=REPORT_CONFIGURED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630454372, gaugeType=ResponseTimeGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.ApacheTopGauge, mapping_6=reqServiceRate::s0.reqServiceRate, setupParam_2=beaconPeriod:long=20000, mapping_5=pageHit::s0.lastPageHit, setupParam_1=targetIP=10.0.2.15, mapping_4=numReqsSuccess::conn0.numReqsSuccess, mapping_0=byteServiceRate::s0.byteServiceRate, mapping_3=numReqsServerError::conn0.numReqsServerError, mapping_2=numReqsRedirect::conn0.numReqsRedirect, setupParam_size=3, mapping_1=numReqsClientError::conn0.numReqsClientError, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454668, action=CREATE, gaugeName=ATG1, mapping_size=7, channel=topic/gaugeBus, msg-sent=1347630454668, gaugeType=ApacheTopGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiskIOGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=readRate::s0.diskReadRate, mapping_2=writeRate::s0.diskWriteRate, setupParam_size=3, mapping_1=transferRate::s0.diskXferRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454669, action=CREATE, gaugeName=DioG1, mapping_size=3, channel=topic/gaugeBus, msg-sent=1347630454669, gaugeType=DiskIOGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.FidelityGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.15, mapping_0=fidelity::s0.fidelity, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=FiG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=FidelityGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latency(10.0.2.2)::conn0.latency, setupParam_size=3, mapping_1=latency(phoenix)::conn1.latency, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=LatG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=LatencyGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latencyRate(10.0.2.2)::conn0.latencyRate, setupParam_size=3, mapping_1=latencyRate(phoenix)::conn1.latencyRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454671, action=CREATE, gaugeName=LatRoCG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454671, gaugeType=LatencyRateGaugeT} -{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=load::s1.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454672, action=CREATE, gaugeName=LoG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454672, gaugeType=LoadGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630457213, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630457213} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630459410, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630459410, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460095, action=CONFIGURE, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460095, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460154, action=REPORT_CONFIGURED, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460154, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464412, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630464412, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464467, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464467, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464471, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469414, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630469414, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469510, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469510, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469511, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469511, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474415, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630474415, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474420, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.10000000000000002, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474420, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474421, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474421, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630477215, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477215} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630477217, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477217} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630477223, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477223} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479417, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630479418, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479492, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479492, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479493, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630479518, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630479518} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484419, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630484419, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484508, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484508, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484509, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484509, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489421, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630489421, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494423, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630494423, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494437, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494437, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494438, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494438, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630497221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630497221} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499425, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630499425, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499449, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499449, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499450, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499450, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504427, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630504427, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504459, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504460, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504460, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630507221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507221} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630507229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507229} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509429, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630509429, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509470, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509471, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630509530, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630509530} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514430, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630514431, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514481, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514482, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630517225, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630517225} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519433, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630519433, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524435, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630524435, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524504, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524505, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524505, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529437, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630529437, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534438, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630534438, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630537227, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537227} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630537229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537229} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630537235, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537235} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539441, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630539441, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630539542, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630539542} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544443, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630544443, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544547, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544548, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544548, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549446, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630549446, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554448, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630554449, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554470, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554471, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630557233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630557233} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559451, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630559451, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564453, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630564453, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630567233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567233} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630567241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567241} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569456, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630569456, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630569557, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630569557} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574458, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630574458, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574516, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574516, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574517, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574517, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630577237, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630577237} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579460, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630579460, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584463, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630584463, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589465, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630589465, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630594467, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630594467, value_size=2, gaugeType=DiagnosisGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630597239, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597239} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630597241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597241} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630597247, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597247} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599469, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630599469, value_size=2, gaugeType=DiagnosisGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630599570, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630599570} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604470, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630604470, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609473, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630609473, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614475, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630614475, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614481, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614482, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630617245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630617245} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619477, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630619477, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619493, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619494, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619494, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624478, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630624478, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630627245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627245} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630627253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627253} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629481, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630629481, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629511, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629511, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629512, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629512, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630629581, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630629581} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634483, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630634483, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634520, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634520, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634521, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634521, gaugeType=MaliciousnessGaugeT} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630637249, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630637249} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639485, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630639485, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639530, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639530, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639531, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639531, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644487, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630644487, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649490, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630649490, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649547, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649548, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654492, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630654492, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630657251, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657251} -{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630657253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657253} -{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630657259, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657259} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659495, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630659495, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659564, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659565, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659565, gaugeType=MaliciousnessGaugeT} -{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630659596, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630659596} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665048, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630665048, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} -{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670050, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630670050, value_size=2, gaugeType=DiagnosisGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} -{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiagnosisGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness::x, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=DG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=DiagnosisGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.End2EndRespTimeGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=end2endRespTime(delegate.oracle)::c0.experRespTime, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357100, action=CREATE, gaugeName=EERTG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357100, gaugeType=ResponseTimeGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.EchoGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.2, mapping_0=maliciousness(c1)::c0.maliciousness, setupParam_size=3, mapping_1=maliciousness(c2)::c1.maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357101, action=CREATE, gaugeName=EG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630357101, gaugeType=MaliciousnessGaugeT} +{location=10.0.2.2, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.2, mapping_0=load::s0.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357102, action=CREATE, gaugeName=LoG0, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630357102, gaugeType=LoadGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357187, action=REPORT_CREATED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630357187, gaugeType=DiagnosisGaugeT} +{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357189, action=REPORT_CREATED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630357189, gaugeType=ResponseTimeGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, beaconPer=30000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357191, action=REPORT_CREATED, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630357191, gaugeType=MaliciousnessGaugeT} +{uid=LoadGaugeT0914094557193@10.0.2.2, beaconPer=20000, modelName=ZNewsSys, modelType=Acme, msg-created=1347630357193, action=REPORT_CREATED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630357193, gaugeType=LoadGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630377197, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630377197} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630387192, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387192} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630387194, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387194} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630387196, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630387196} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630397201, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630397201} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630417198, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417198} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630417200, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417200} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630417202, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417202} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630417205, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630417205} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630437209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630437209} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630447204, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447204} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630447206, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447206} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630447209, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630447209} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=DiagnosisGaugeT} +{uid=LoadGaugeT0914094557193@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454371, action=REPORT_CONFIGURED, gaugeName=LoG0, channel=topic/gaugeBus, msg-sent=1347630454371, gaugeType=LoadGaugeT} +{uid=ResponseTimeGaugeT0914094557188@10.0.2.2, configParam_size=0, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454372, action=REPORT_CONFIGURED, gaugeName=EERTG1, channel=topic/gaugeBus, msg-sent=1347630454372, gaugeType=ResponseTimeGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.ApacheTopGauge, mapping_6=reqServiceRate::s0.reqServiceRate, setupParam_2=beaconPeriod:long=20000, mapping_5=pageHit::s0.lastPageHit, setupParam_1=targetIP=10.0.2.15, mapping_4=numReqsSuccess::conn0.numReqsSuccess, mapping_0=byteServiceRate::s0.byteServiceRate, mapping_3=numReqsServerError::conn0.numReqsServerError, mapping_2=numReqsRedirect::conn0.numReqsRedirect, setupParam_size=3, mapping_1=numReqsClientError::conn0.numReqsClientError, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454668, action=CREATE, gaugeName=ATG1, mapping_size=7, channel=topic/gaugeBus, msg-sent=1347630454668, gaugeType=ApacheTopGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.DiskIOGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=readRate::s0.diskReadRate, mapping_2=writeRate::s0.diskWriteRate, setupParam_size=3, mapping_1=transferRate::s0.diskXferRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454669, action=CREATE, gaugeName=DioG1, mapping_size=3, channel=topic/gaugeBus, msg-sent=1347630454669, gaugeType=DiskIOGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.FidelityGauge, setupParam_2=beaconPeriod:long=30000, setupParam_1=targetIP=10.0.2.15, mapping_0=fidelity::s0.fidelity, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=FiG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=FidelityGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latency(10.0.2.2)::conn0.latency, setupParam_size=3, mapping_1=latency(phoenix)::conn1.latency, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454670, action=CREATE, gaugeName=LatG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454670, gaugeType=LatencyGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=latencyRate(10.0.2.2)::conn0.latencyRate, setupParam_size=3, mapping_1=latencyRate(phoenix)::conn1.latencyRate, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454671, action=CREATE, gaugeName=LatRoCG1, mapping_size=2, channel=topic/gaugeBus, msg-sent=1347630454671, gaugeType=LatencyRateGaugeT} +{location=10.0.2.15, setupParam_0=javaClass=org.sa.rainbow.translator.gauges.CpuLoadGauge, setupParam_2=beaconPeriod:long=20000, setupParam_1=targetIP=10.0.2.15, mapping_0=load::s1.load, setupParam_size=3, modelName=ZNewsSys, modelType=Acme, msg-created=1347630454672, action=CREATE, gaugeName=LoG1, mapping_size=1, channel=topic/gaugeBus, msg-sent=1347630454672, gaugeType=LoadGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630457213, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630457213} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630459410, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630459410, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460095, action=CONFIGURE, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460095, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, configParam_size=5, configParam_4=targetGaugeValue=maliciousness, modelName=ZNewsSys, modelType=Acme, msg-created=1347630460154, action=REPORT_CONFIGURED, configParam_1=maliciousness(c2)=0.0, gaugeName=EG1, configParam_0=maliciousness(c1)=0.0, configParam_3=targetGaugeType=DiagnosisGaugeT, configParam_2=targetGaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630460154, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464412, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630464412, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464467, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464467, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630464471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630464471, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469414, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630469414, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469510, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469510, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630469511, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630469511, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474415, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630474415, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474420, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.10000000000000002, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474420, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630474421, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630474421, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630477215, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477215} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630477217, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477217} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630477223, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630477223} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479417, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630479418, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479492, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479492, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630479493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630479493, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630479518, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630479518} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484419, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630484419, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484508, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484508, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630484509, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630484509, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489421, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630489421, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630489426, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630489426, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494423, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630494423, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494437, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494437, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630494438, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630494438, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630497221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630497221} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499425, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630499425, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499449, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499449, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630499450, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630499450, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504427, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630504427, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504459, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630504460, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630504460, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630507221, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507221} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630507229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630507229} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509429, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630509429, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509470, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630509471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630509471, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630509530, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630509530} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514430, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630514431, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514481, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630514482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630514482, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630517225, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630517225} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519433, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630519433, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630519493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630519493, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524435, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630524435, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524504, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630524505, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630524505, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529437, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630529437, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630529515, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630529515, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534438, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630534438, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630534524, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630534524, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630537227, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537227} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630537229, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537229} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630537235, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630537235} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539441, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630539441, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630539535, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630539535, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630539542, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630539542} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544443, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630544443, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544547, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630544548, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630544548, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549446, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630549446, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630549459, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630549459, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554448, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630554449, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554470, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554470, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630554471, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630554471, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630557233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630557233} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559451, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630559451, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630559482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630559482, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564453, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630564453, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630564493, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630564493, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630567233, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567233} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630567241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630567241} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569456, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630569456, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630569504, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630569504, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630569557, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630569557} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574458, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630574458, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574516, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574516, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630574517, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630574517, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630577237, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630577237} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579460, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630579460, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630579529, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630579529, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584463, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630584463, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630584540, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630584540, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589465, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630589465, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630589552, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630589552, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630594467, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630594467, value_size=2, gaugeType=DiagnosisGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630597239, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597239} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630597241, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597241} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630597247, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630597247} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599469, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630599469, value_size=2, gaugeType=DiagnosisGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630599570, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630599570} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599683, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599683, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630599686, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630599686, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604470, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630604470, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630604564, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630604564, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609473, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630609473, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630609574, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630609574, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614475, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630614475, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614481, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614481, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630614482, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630614482, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630617245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630617245} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619477, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630619477, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619493, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619493, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630619494, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630619494, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624478, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630624478, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630624503, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630624503, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630627245, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627245} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630627253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630627253} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629481, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630629481, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629511, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629511, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630629512, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630629512, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630629581, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630629581} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634483, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630634483, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634520, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634520, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630634521, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630634521, gaugeType=MaliciousnessGaugeT} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630637249, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630637249} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639485, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630639485, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639530, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639530, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630639531, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630639531, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644487, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630644487, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630644539, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630644539, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649490, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630649490, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649547, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630649547, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630649548, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654492, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630654492, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630654555, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630654555, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=MaliciousnessGaugeT0914094557191@10.0.2.2, msg-created=1347630657251, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657251} +{beaconPer=20000, uid=LoadGaugeT0914094557193@10.0.2.2, msg-created=1347630657253, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657253} +{beaconPer=30000, uid=ResponseTimeGaugeT0914094557188@10.0.2.2, msg-created=1347630657259, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630657259} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659495, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630659495, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659564, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659564, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630659565, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630659565, gaugeType=MaliciousnessGaugeT} +{beaconPer=30000, uid=DiagnosisGaugeT0914094557185@10.0.2.2, msg-created=1347630659596, action=BEACON, channel=topic/gaugeBus, msg-sent=1347630659596} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665048, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630665048, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630665073, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630665073, gaugeType=MaliciousnessGaugeT} +{uid=DiagnosisGaugeT0914094557185@10.0.2.2, value_0=maliciousness:c1.maliciousness=0.1, value_1=maliciousness:c2.maliciousness=0.9, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670050, action=REPORT_MULTIVALUES, gaugeName=DG1, channel=topic/gaugeBus, msg-sent=1347630670050, value_size=2, gaugeType=DiagnosisGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c1):ZNewsSys.c0.maliciousness=0.1, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} +{uid=MaliciousnessGaugeT0914094557191@10.0.2.2, modelName=ZNewsSys, modelType=Acme, msg-created=1347630670082, value=maliciousness(c2):ZNewsSys.c1.maliciousness=0.9, action=REPORT_VALUE, gaugeName=EG1, channel=topic/gaugeBus, msg-sent=1347630670082, gaugeType=MaliciousnessGaugeT} diff --git a/targets/znews-ss_2/log/topic/rainbowHealth.log b/targets/znews-ss_2/log/topic/rainbowHealth.log index 33931f7a8..23bde129f 100644 --- a/targets/znews-ss_2/log/topic/rainbowHealth.log +++ b/targets/znews-ss_2/log/topic/rainbowHealth.log @@ -1,102 +1,102 @@ -{msg-created=1347630325763, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325773, txt=EventServiceManager initialized!} -{msg-created=1347630325789, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325789, txt=T[topic/rainbowHealth] +listener Oracle@10.0.2.2} -{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/rainbowHealth] +listener SystemDelegate@10.0.2.2} -{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/effectorBus] +listener SystemDelegate@10.0.2.2} -{msg-created=1347630351995, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351995, txt=T[topic/gaugeBus] +listener GaugeCoordinator@10.0.2.2} -{msg-created=1347630351996, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351996, txt=T[topic/rainbowHealth] +listener ModelManager@10.0.2.2} -{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/rainbowHealth] +listener del1} -{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/effectorBus] +listener del1} -{msg-created=1347630352014, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352014, txt=T[topic/gaugeBus] +listener ApacheTopGaugeT@10.0.2.2} -{msg-created=1347630352018, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352018, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT@10.0.2.2} -{msg-created=1347630352020, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352020, txt=T[topic/gaugeBus] +listener DiskIOGaugeT@10.0.2.2} -{msg-created=1347630352021, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352021, txt=T[topic/gaugeBus] +listener FidelityGaugeT@10.0.2.2} -{msg-created=1347630352022, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352022, txt=T[topic/gaugeBus] +listener LatencyGaugeT@10.0.2.2} -{msg-created=1347630352024, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352024, txt=T[topic/gaugeBus] +listener LatencyRateGaugeT@10.0.2.2} -{msg-created=1347630352025, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352025, txt=T[topic/gaugeBus] +listener LoadGaugeT@10.0.2.2} -{msg-created=1347630352026, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352026, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT@10.0.2.2} -{msg-created=1347630352031, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352031, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT@10.0.2.2} -{beaconPer=5000, id=del1, location=10.0.2.2, cloudT=DELEGATE, msg-created=1347630357039, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630357039} -{id=del1, location=10.0.2.2, msg-created=1347630357099, action=START, channel=topic/rainbowHealth, msg-sent=1347630357099} -{msg-created=1347630357187, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357187, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT0914094557185@10.0.2.2} -{msg-created=1347630357188, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357188, txt=G[DiagnosisGaugeT0914094557185@10.0.2.2] G - Diagnosis started.} -{msg-created=1347630357189, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357189, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} -{msg-created=1347630357190, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=T[topic/probeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} -{msg-created=1347630357190, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=G[ResponseTimeGaugeT0914094557188@10.0.2.2] G - End-End Resp Time started.} -{msg-created=1347630357191, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357191, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} -{msg-created=1347630357192, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} -{msg-created=1347630357192, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=G[MaliciousnessGaugeT0914094557191@10.0.2.2] G - Maliciousness started.} -{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/gaugeBus] +listener LoadGaugeT0914094557193@10.0.2.2} -{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/probeBus] +listener LoadGaugeT0914094557193@10.0.2.2} -{msg-created=1347630357193, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357194, txt=G[LoadGaugeT0914094557193@10.0.2.2] G - CPU Load started.} -{id=del1, msg-created=1347630362096, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630362096} -{id=del1, msg-created=1347630367196, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630367196} -{id=del1, msg-created=1347630372296, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630372296} -{id=del1, msg-created=1347630377297, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630377297} -{id=del1, msg-created=1347630382298, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630382298} -{id=del1, msg-created=1347630387299, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630387299} -{id=del1, msg-created=1347630392300, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630392300} -{id=del1, msg-created=1347630397301, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630397301} -{id=del1, msg-created=1347630402302, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630402302} -{id=del1, msg-created=1347630407303, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630407303} -{id=del1, msg-created=1347630412304, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630412304} -{id=del1, msg-created=1347630417305, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630417305} -{id=del1, msg-created=1347630422306, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630422306} -{id=del1, msg-created=1347630427307, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630427307} -{id=del1, msg-created=1347630432308, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630432308} -{id=del1, msg-created=1347630437309, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630437309} -{id=del1, msg-created=1347630442310, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630442310} -{id=del1, msg-created=1347630447311, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630447311} -{id=del1, msg-created=1347630452312, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630452312} -{location=10.0.2.2, msg-created=1347630454176, action=START_PROBES, channel=topic/rainbowHealth, msg-sent=1347630454176} -{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/rainbowHealth] +listener ProbeBusRelay@10.0.2.2} -{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/probeBus] +listener ProbeBusRelay@10.0.2.2} -{beaconPer=0, id=ProbeBusRelay@10.0.2.2, location=10.0.2.2, cloudT=PB_RELAY, msg-created=1347630454321, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630454321} -{msg-created=1347630454322, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454322, txt=[PBR] Rainbow Runtime - Probe Bus Relay started.} -{msg-created=1347630454370, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454370, txt=[PBR] IProbe ClientProxyProbe0@10.0.2.2:clientproxy added!} -{beaconPer=0, id=ClientProxyProbe0@10.0.2.2, probeK=JAVA, alias=clientproxy, location=10.0.2.2, cloudT=PROBE, msg-created=1347630454370, action=REPORT_CREATED, svcName=ClientProxyProbe0, channel=topic/rainbowHealth, msg-sent=1347630454370} -{id=del1, location=10.0.2.15, msg-created=1347630454667, action=START, channel=topic/rainbowHealth, msg-sent=1347630454667} -{id=del1, msg-created=1347630457373, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630457373} -{id=del1, location=10.0.2.15, msg-created=1347630459775, action=START, channel=topic/rainbowHealth, msg-sent=1347630459775} -{id=del1, msg-created=1347630462374, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630462374} -{id=del1, msg-created=1347630467375, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630467375} -{id=del1, msg-created=1347630472376, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630472376} -{id=del1, msg-created=1347630477377, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630477377} -{id=del1, msg-created=1347630482378, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630482378} -{id=del1, msg-created=1347630487379, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630487379} -{id=del1, msg-created=1347630492380, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630492380} -{id=del1, msg-created=1347630497381, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630497381} -{id=del1, msg-created=1347630502382, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630502382} -{id=del1, msg-created=1347630507383, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630507383} -{id=del1, msg-created=1347630512384, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630512384} -{id=del1, msg-created=1347630517385, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630517385} -{id=del1, msg-created=1347630522386, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630522386} -{id=del1, msg-created=1347630527387, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630527387} -{id=del1, msg-created=1347630532388, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630532388} -{id=del1, msg-created=1347630537389, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630537389} -{id=del1, msg-created=1347630542390, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630542390} -{id=del1, msg-created=1347630547391, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630547391} -{id=del1, msg-created=1347630552392, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630552392} -{id=del1, msg-created=1347630557393, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630557393} -{id=del1, msg-created=1347630562394, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630562394} -{id=del1, msg-created=1347630567395, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630567395} -{id=del1, msg-created=1347630572396, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630572396} -{id=del1, msg-created=1347630577397, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630577397} -{id=del1, msg-created=1347630582398, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630582398} -{id=del1, msg-created=1347630587399, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630587399} -{id=del1, msg-created=1347630592400, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630592400} -{id=del1, msg-created=1347630597401, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630597401} -{id=del1, msg-created=1347630602402, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630602402} -{id=del1, msg-created=1347630607403, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630607403} -{id=del1, msg-created=1347630612404, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630612404} -{id=del1, msg-created=1347630617405, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630617405} -{id=del1, msg-created=1347630622406, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630622406} -{id=del1, msg-created=1347630627407, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630627407} -{id=del1, msg-created=1347630632408, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630632408} -{id=del1, msg-created=1347630637409, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630637409} -{id=del1, msg-created=1347630642410, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630642410} -{id=del1, msg-created=1347630647411, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630647411} -{id=del1, msg-created=1347630652412, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630652412} -{id=del1, msg-created=1347630657413, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630657413} -{id=del1, msg-created=1347630662414, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630662414} -{id=del1, msg-created=1347630667415, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630667415} -{id=del1, msg-created=1347630672416, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630672416} +{msg-created=1347630325763, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325773, txt=EventServiceManager initialized!} +{msg-created=1347630325789, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325789, txt=T[topic/rainbowHealth] +listener Oracle@10.0.2.2} +{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/rainbowHealth] +listener SystemDelegate@10.0.2.2} +{msg-created=1347630325794, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630325794, txt=T[topic/effectorBus] +listener SystemDelegate@10.0.2.2} +{msg-created=1347630351995, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351995, txt=T[topic/gaugeBus] +listener GaugeCoordinator@10.0.2.2} +{msg-created=1347630351996, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630351996, txt=T[topic/rainbowHealth] +listener ModelManager@10.0.2.2} +{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/rainbowHealth] +listener del1} +{msg-created=1347630352010, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352010, txt=T[topic/effectorBus] +listener del1} +{msg-created=1347630352014, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352014, txt=T[topic/gaugeBus] +listener ApacheTopGaugeT@10.0.2.2} +{msg-created=1347630352018, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352018, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT@10.0.2.2} +{msg-created=1347630352020, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352020, txt=T[topic/gaugeBus] +listener DiskIOGaugeT@10.0.2.2} +{msg-created=1347630352021, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352021, txt=T[topic/gaugeBus] +listener FidelityGaugeT@10.0.2.2} +{msg-created=1347630352022, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352022, txt=T[topic/gaugeBus] +listener LatencyGaugeT@10.0.2.2} +{msg-created=1347630352024, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352024, txt=T[topic/gaugeBus] +listener LatencyRateGaugeT@10.0.2.2} +{msg-created=1347630352025, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352025, txt=T[topic/gaugeBus] +listener LoadGaugeT@10.0.2.2} +{msg-created=1347630352026, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352026, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT@10.0.2.2} +{msg-created=1347630352031, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630352031, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT@10.0.2.2} +{beaconPer=5000, id=del1, location=10.0.2.2, cloudT=DELEGATE, msg-created=1347630357039, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630357039} +{id=del1, location=10.0.2.2, msg-created=1347630357099, action=START, channel=topic/rainbowHealth, msg-sent=1347630357099} +{msg-created=1347630357187, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357187, txt=T[topic/gaugeBus] +listener DiagnosisGaugeT0914094557185@10.0.2.2} +{msg-created=1347630357188, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357188, txt=G[DiagnosisGaugeT0914094557185@10.0.2.2] G - Diagnosis started.} +{msg-created=1347630357189, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357189, txt=T[topic/gaugeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} +{msg-created=1347630357190, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=T[topic/probeBus] +listener ResponseTimeGaugeT0914094557188@10.0.2.2} +{msg-created=1347630357190, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357190, txt=G[ResponseTimeGaugeT0914094557188@10.0.2.2] G - End-End Resp Time started.} +{msg-created=1347630357191, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357191, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} +{msg-created=1347630357192, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=T[topic/gaugeBus] +listener MaliciousnessGaugeT0914094557191@10.0.2.2} +{msg-created=1347630357192, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357192, txt=G[MaliciousnessGaugeT0914094557191@10.0.2.2] G - Maliciousness started.} +{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/gaugeBus] +listener LoadGaugeT0914094557193@10.0.2.2} +{msg-created=1347630357193, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630357193, txt=T[topic/probeBus] +listener LoadGaugeT0914094557193@10.0.2.2} +{msg-created=1347630357193, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630357194, txt=G[LoadGaugeT0914094557193@10.0.2.2] G - CPU Load started.} +{id=del1, msg-created=1347630362096, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630362096} +{id=del1, msg-created=1347630367196, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630367196} +{id=del1, msg-created=1347630372296, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630372296} +{id=del1, msg-created=1347630377297, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630377297} +{id=del1, msg-created=1347630382298, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630382298} +{id=del1, msg-created=1347630387299, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630387299} +{id=del1, msg-created=1347630392300, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630392300} +{id=del1, msg-created=1347630397301, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630397301} +{id=del1, msg-created=1347630402302, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630402302} +{id=del1, msg-created=1347630407303, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630407303} +{id=del1, msg-created=1347630412304, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630412304} +{id=del1, msg-created=1347630417305, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630417305} +{id=del1, msg-created=1347630422306, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630422306} +{id=del1, msg-created=1347630427307, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630427307} +{id=del1, msg-created=1347630432308, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630432308} +{id=del1, msg-created=1347630437309, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630437309} +{id=del1, msg-created=1347630442310, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630442310} +{id=del1, msg-created=1347630447311, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630447311} +{id=del1, msg-created=1347630452312, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630452312} +{location=10.0.2.2, msg-created=1347630454176, action=START_PROBES, channel=topic/rainbowHealth, msg-sent=1347630454176} +{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/rainbowHealth] +listener ProbeBusRelay@10.0.2.2} +{msg-created=1347630454321, action=LOG_EVENT, channel=topic/rainbowHealth, msg-sent=1347630454321, txt=T[topic/probeBus] +listener ProbeBusRelay@10.0.2.2} +{beaconPer=0, id=ProbeBusRelay@10.0.2.2, location=10.0.2.2, cloudT=PB_RELAY, msg-created=1347630454321, action=REPORT_CREATED, channel=topic/rainbowHealth, msg-sent=1347630454321} +{msg-created=1347630454322, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454322, txt=[PBR] Rainbow Runtime - Probe Bus Relay started.} +{msg-created=1347630454370, action=LOG_TRANSLATOR, channel=topic/rainbowHealth, msg-sent=1347630454370, txt=[PBR] IProbe ClientProxyProbe0@10.0.2.2:clientproxy added!} +{beaconPer=0, id=ClientProxyProbe0@10.0.2.2, probeK=JAVA, alias=clientproxy, location=10.0.2.2, cloudT=PROBE, msg-created=1347630454370, action=REPORT_CREATED, svcName=ClientProxyProbe0, channel=topic/rainbowHealth, msg-sent=1347630454370} +{id=del1, location=10.0.2.15, msg-created=1347630454667, action=START, channel=topic/rainbowHealth, msg-sent=1347630454667} +{id=del1, msg-created=1347630457373, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630457373} +{id=del1, location=10.0.2.15, msg-created=1347630459775, action=START, channel=topic/rainbowHealth, msg-sent=1347630459775} +{id=del1, msg-created=1347630462374, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630462374} +{id=del1, msg-created=1347630467375, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630467375} +{id=del1, msg-created=1347630472376, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630472376} +{id=del1, msg-created=1347630477377, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630477377} +{id=del1, msg-created=1347630482378, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630482378} +{id=del1, msg-created=1347630487379, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630487379} +{id=del1, msg-created=1347630492380, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630492380} +{id=del1, msg-created=1347630497381, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630497381} +{id=del1, msg-created=1347630502382, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630502382} +{id=del1, msg-created=1347630507383, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630507383} +{id=del1, msg-created=1347630512384, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630512384} +{id=del1, msg-created=1347630517385, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630517385} +{id=del1, msg-created=1347630522386, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630522386} +{id=del1, msg-created=1347630527387, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630527387} +{id=del1, msg-created=1347630532388, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630532388} +{id=del1, msg-created=1347630537389, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630537389} +{id=del1, msg-created=1347630542390, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630542390} +{id=del1, msg-created=1347630547391, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630547391} +{id=del1, msg-created=1347630552392, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630552392} +{id=del1, msg-created=1347630557393, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630557393} +{id=del1, msg-created=1347630562394, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630562394} +{id=del1, msg-created=1347630567395, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630567395} +{id=del1, msg-created=1347630572396, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630572396} +{id=del1, msg-created=1347630577397, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630577397} +{id=del1, msg-created=1347630582398, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630582398} +{id=del1, msg-created=1347630587399, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630587399} +{id=del1, msg-created=1347630592400, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630592400} +{id=del1, msg-created=1347630597401, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630597401} +{id=del1, msg-created=1347630602402, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630602402} +{id=del1, msg-created=1347630607403, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630607403} +{id=del1, msg-created=1347630612404, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630612404} +{id=del1, msg-created=1347630617405, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630617405} +{id=del1, msg-created=1347630622406, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630622406} +{id=del1, msg-created=1347630627407, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630627407} +{id=del1, msg-created=1347630632408, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630632408} +{id=del1, msg-created=1347630637409, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630637409} +{id=del1, msg-created=1347630642410, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630642410} +{id=del1, msg-created=1347630647411, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630647411} +{id=del1, msg-created=1347630652412, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630652412} +{id=del1, msg-created=1347630657413, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630657413} +{id=del1, msg-created=1347630662414, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630662414} +{id=del1, msg-created=1347630667415, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630667415} +{id=del1, msg-created=1347630672416, action=BEACON, channel=topic/rainbowHealth, msg-sent=1347630672416} diff --git a/targets/znews-ss_2/model/DoSFam.acme b/targets/znews-ss_2/model/DoSFam.acme index 517612eea..2e54d6974 100644 --- a/targets/znews-ss_2/model/DoSFam.acme +++ b/targets/znews-ss_2/model/DoSFam.acme @@ -1,46 +1,46 @@ -Family DoSFam = { - - Element Type PotentiallyMaliciousT = { - - Property deploymentLocation : string; - - Property maliciousness : float << default : float = 0.0; >> ; - - } - - Element Type MaliciousT extends PotentiallyMaliciousT with { - rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; - } - - Element Type SuspiciousT extends PotentiallyMaliciousT with { - rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD && maliciousness <= MALICIOUS_THRESHOLD; - } - - Element Type NormalT extends PotentiallyMaliciousT with { - rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; - - Element Type BlackholerT = { - - Property blackholed : Set {string} << default : Set {string} = {}; >> ; - - } - Port Type BlackholedPortT = { - - Property isBlackholed : boolean = true; - - } - - Port Type CaptchaPortT = { - Property captchaEnabled : boolean << default : boolean = false;>>; - } - - Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; - Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; - rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | - exists bh : BlackholerT in self.COMPONENTS | - contains(c.deploymentLocation, bh.blackholed); - rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.components | - forall ip : string in lb.blackholed | - forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | - c.maliciousness > self.MALICIOUS_THRESHOLD; +Family DoSFam = { + + Element Type PotentiallyMaliciousT = { + + Property deploymentLocation : string; + + Property maliciousness : float << default : float = 0.0; >> ; + + } + + Element Type MaliciousT extends PotentiallyMaliciousT with { + rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; + } + + Element Type SuspiciousT extends PotentiallyMaliciousT with { + rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD && maliciousness <= MALICIOUS_THRESHOLD; + } + + Element Type NormalT extends PotentiallyMaliciousT with { + rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; + + Element Type BlackholerT = { + + Property blackholed : Set {string} << default : Set {string} = {}; >> ; + + } + Port Type BlackholedPortT = { + + Property isBlackholed : boolean = true; + + } + + Port Type CaptchaPortT = { + Property captchaEnabled : boolean << default : boolean = false;>>; + } + + Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; + Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; + rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | + exists bh : BlackholerT in self.COMPONENTS | + contains(c.deploymentLocation, bh.blackholed); + rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.components | + forall ip : string in lb.blackholed | + forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | + c.maliciousness > self.MALICIOUS_THRESHOLD; } \ No newline at end of file diff --git a/targets/znews-ss_2/model/TargetEnv.acme b/targets/znews-ss_2/model/TargetEnv.acme index 4331c55b7..2ec6be259 100644 --- a/targets/znews-ss_2/model/TargetEnv.acme +++ b/targets/znews-ss_2/model/TargetEnv.acme @@ -1,4 +1,4 @@ -System TargetEnv = { - -} - +System TargetEnv = { + +} + diff --git a/targets/znews-ss_2/model/TargetEnvType.acme b/targets/znews-ss_2/model/TargetEnvType.acme index a91a99173..91e499a0e 100644 --- a/targets/znews-ss_2/model/TargetEnvType.acme +++ b/targets/znews-ss_2/model/TargetEnvType.acme @@ -1,67 +1,67 @@ -Family EnvType = { - - Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; - - Role Type ArchRoleT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type PartPortT = { - - } - Component Type ArchElementT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type NetworkRoleT = { - - } - Connector Type MappingT = { - - } - Role Type PartRoleT = { - - } - Connector Type EdgeT = { - - Property bandwidthAvg : ResourceStatePropT; - - Property capacity : ResourceStatePropT; - - } - Component Type NodeT = { - - Property cpuOverall : ResourceStatePropT; - - Property memoryMain : ResourceStatePropT; - - Property storageLocal : ResourceStatePropT; - - Property socketPool : ResourceStatePropT; - - Property batteryOverall : ResourceStatePropT; - - } - Port Type NetworkPortT = { - - } - Connector Type ArchConnT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type ArchPortT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type ContainerRoleT = { - - } - Port Type ContainmentPortT = { - - } -} - +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type PartPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type NetworkRoleT = { + + } + Connector Type MappingT = { + + } + Role Type PartRoleT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Port Type NetworkPortT = { + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type ContainerRoleT = { + + } + Port Type ContainmentPortT = { + + } +} + diff --git a/targets/znews-ss_2/model/TargetEnvType.mtd b/targets/znews-ss_2/model/TargetEnvType.mtd index 6817ebfa8..9d8d87f85 100644 --- a/targets/znews-ss_2/model/TargetEnvType.mtd +++ b/targets/znews-ss_2/model/TargetEnvType.mtd @@ -1,475 +1,475 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews-ss_2/model/ZNewsSys.acme b/targets/znews-ss_2/model/ZNewsSys.acme index ee3f29388..28625b613 100644 --- a/targets/znews-ss_2/model/ZNewsSys.acme +++ b/targets/znews-ss_2/model/ZNewsSys.acme @@ -1,608 +1,608 @@ -Family EnvType = { - - Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; - Port Type PartPortT = { - - } - Port Type NetworkPortT = { - - } - Port Type ArchPortT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } - Port Type ContainmentPortT = { - - } - Component Type ArchElementT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } - Component Type NodeT = { - - Property cpuOverall : ResourceStatePropT; - - Property memoryMain : ResourceStatePropT; - - Property storageLocal : ResourceStatePropT; - - Property socketPool : ResourceStatePropT; - - Property batteryOverall : ResourceStatePropT; - - } - Role Type ArchRoleT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } - Role Type NetworkRoleT = { - - } - Role Type PartRoleT = { - - } - Role Type ContainerRoleT = { - - } - Connector Type MappingT = { - - } - Connector Type EdgeT = { - - Property bandwidthAvg : ResourceStatePropT; - - Property capacity : ResourceStatePropT; - - } - Connector Type ArchConnT = { - - Property isArchEnabled : boolean << default : boolean = true; >> ; - - } -} - -Family ZNewsFam extends EnvType with { - - Port Type HttpPortT extends ArchPortT with { - - } - Port Type ProxyForwardPortT extends ArchPortT with { - - } - Port Type HttpReqPortT extends ArchPortT with { - - } - Port Type SqlReqPort extends ArchPortT with { - - } - Port Type SqlRecPort extends ArchPortT with { - - } - Component Type ProxyT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - } - Component Type ServerT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - Property reqServiceRate : float << default : float = 0.0; >> ; - - Property byteServiceRate : float << default : float = 0.0; >> ; - - Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; - - Property cost : float << default : float = 1.0; >> ; - - Property lastPageHit : Record [uri : string; cnt : int; kbytes : float; ]; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - Component Type ClientT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property experRespTime : float << default : float = 0.0; >> ; - - Property reqRate : float << default : float = 0.0; >> ; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - Component Type DBT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "locahost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - } - Role Type ReceiverRoleT extends ArchRoleT with { - - } - Role Type RequestorRoleT extends ArchRoleT with { - - } - Connector Type ProxyConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - Connector Type SQLConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - Connector Type HttpConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - Property bandwidth : float << default : float = 0.0; >> ; - - Property latency : float << default : float = 0.0; >> ; - - Property numReqsSuccess : int << default : int = 0; >> ; - - Property numReqsRedirect : int << default : int = 0; >> ; - - Property numReqsClientError : int << default : int = 0; >> ; - - Property numReqsServerError : int << default : int = 0; >> ; - - Property latencyRate : float; - - } - - Property MIN_RESPTIME : float; - - Property MAX_RESPTIME : float << default : float = 2; >> ; - - Property TOLERABLE_PERCENT_UNHAPPY : float; - - Property UNHAPPY_GRADIENT_1 : float; - - Property UNHAPPY_GRADIENT_2 : float; - - Property UNHAPPY_GRADIENT_3 : float; - - Property FRACTION_GRADIENT_1 : float; - - Property FRACTION_GRADIENT_2 : float; - - Property FRACTION_GRADIENT_3 : float; - - Property MIN_UTIL : float; - - Property MAX_UTIL : float << default : float = 1; >> ; - - Property MAX_FIDELITY_LEVEL : int; - - Property THRESHOLD_FIDELITY : int; - - Property THRESHOLD_COST : float; -} - -Family DoSFam = { - - Element Type PotentiallyMaliciousT = { - - Property deploymentLocation : string; - - Property maliciousness : float << default : float = 0.0; >> ; - - } - Element Type MaliciousT extends PotentiallyMaliciousT with { - rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; - - } - Element Type SuspiciousT extends PotentiallyMaliciousT with { - rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD AND maliciousness <= MALICIOUS_THRESHOLD; - - } - Element Type NormalT extends PotentiallyMaliciousT with { - rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; - - } - Element Type BlackholerT = { - - Property blackholed : Set {string} << default : Set {string} = {}; >> ; - - } - Element Type CaptchaRedirectT = { - - Property captchaEnabled : boolean << default : boolean = false; >> ; - - } - Element Type ThrottlerT = { - - Property throttled : Set {string} << default : Set {string} = {}; >> ; - - } - Element Type CaptchaHandlerT = { - - Property captcha : int << default : int = 0; >> ; - - } - Element Type AuthenticationHandlerT = { - - Property authenticate : int << default : int = 0; >> ; - - } - Port Type BlackholedPortT = { - - Property isBlackholed : boolean = true; - - } - - Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; - - Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; - rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | - exists bh : BlackholerT in self.COMPONENTS | - contains(c.deploymentLocation, bh.blackholed); - rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | - forall ip : string in lb.blackholed | - forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | - c.maliciousness > self.MALICIOUS_THRESHOLD; -} - -Family ZNewsDosFam extends ZNewsFam, DoSFam with { - - Component Type ZNewsClientT extends ClientT, PotentiallyMaliciousT, CaptchaHandlerT, AuthenticationHandlerT with { - - } - Component Type ZNewsLBT extends ProxyT, CaptchaRedirectT, BlackholerT, ThrottlerT with { - - } -} - -System ZNewsSys : ZNewsDosFam = new ZNewsDosFam extended with { - - Component Server0 : ArchElementT, ServerT = new ArchElementT, ServerT extended with { - Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { - - Property isArchEnabled = true; - - } - Port sql0 : SqlReqPort = new SqlReqPort extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.web0}"; - - Property load = 0.0; - - Property reqServiceRate = 0.0; - - Property byteServiceRate = 0.0; - - Property fidelity = 5; - - Property cost = 1.0; - - Property isArchEnabled = true; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - - Component Server1 : ServerT = new ServerT extended with { - Port p : HttpPortT = new HttpPortT extended with { - - } - Port p0 : SqlReqPort = new SqlReqPort extended with { - - } - Property deploymentLocation = "${customize.system.target.web1}"; - Property load = 0.0; - - Property reqServiceRate = 0.0; - - Property byteServiceRate = 0.0; - - Property fidelity = 5; - - Property cost = 1.0; - - Property isArchEnabled = true; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - - Component ServerB0 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { - - Property isArchEnabled = false; - - } - Port sql0 : SqlReqPort = new SqlReqPort extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.web2}"; - - Property load = 0.0; - - Property reqServiceRate = 0.0; - - Property byteServiceRate = 0.0; - - Property fidelity = 5; - - Property cost = 1.0; - - Property isArchEnabled = false; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - Component LB0 : ZNewsLBT = new ZNewsLBT extended with { - Port http0 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - Port http1 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - Property captchaEnabled = false; - - } - Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - Property isArchEnabled = true; - - } - Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - Property isArchEnabled = false; - - } - Port p : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - - Property deploymentLocation = "${customize.system.target.lb}"; - - Property load = 0.0; - - Property isArchEnabled = true; - - Property blackholed = {}; - - Property captchaEnabled = false; - - Property throttled = {}; - - } - Component DB0 : DBT = new DBT extended with { - Port rec0 : SqlRecPort = new SqlRecPort extended with { - - Property isArchEnabled = true; - - } - Port rec1 : SqlRecPort = new SqlRecPort extended with { - - Property isArchEnabled = true; - - } - Port p : SqlRecPort = new SqlRecPort extended with { - - } - - Property deploymentLocation = "${customize.system.target.db}"; - - Property load = 0.0; - - Property isArchEnabled = true; - - } - Component Client0 : ZNewsClientT = new ZNewsClientT extended with { - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.client1}"; - - Property experRespTime = 5000; - - Property reqRate = 0.0; - - Property isArchEnabled = true; - - Property maliciousness = 0.0; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - Component Client1 : ZNewsClientT = new ZNewsClientT extended with { - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - Property deploymentLocation = "${customize.system.target.client2}"; - - Property experRespTime = 5000.0; - - Property reqRate = 0.0; - - Property isArchEnabled = true; - - Property maliciousness = 1.0; - - Property captcha = 0; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - - Connector httpConn_0_0 : HttpConnT = new HttpConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property bandwidth = 0.0; - - Property latency = 0.0; - - Property numReqsSuccess = 0; - - Property numReqsRedirect = 0; - - Property numReqsClientError = 0; - - Property numReqsServerError = 0; - - Property isArchEnabled = true; - - } - Connector httpConn_1_0 : HttpConnT = new HttpConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property bandwidth = 0.0; - - Property latency = 0.0; - - Property numReqsSuccess = 0; - - Property numReqsRedirect = 0; - - Property numReqsClientError = 0; - - Property numReqsServerError = 0; - - Property isArchEnabled = true; - - } - Connector proxyConn_0_0 : ProxyConnT = new ProxyConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = true; - - } - Connector proxyConn_1_0 : ProxyConnT = new ProxyConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - Property isArchEnabled = true; - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = false; - - } - Connector dbConn_0_0 : SQLConnT = new SQLConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = true; - - } - Connector dbConn_1_0 : SQLConnT = new SQLConnT extended with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - Property isArchEnabled = true; - - } - - Property isArchEnabled = true; - - } - Connector ProxyConnT0 : ProxyConnT = new ProxyConnT extended with { - - } - Connector SQLConnT0 : SQLConnT = new SQLConnT extended with { - - } - Attachment Client1.p0 to httpConn_0_0.req; - Attachment LB0.http0 to httpConn_0_0.rec; - Attachment Client0.p0 to httpConn_1_0.req; - Attachment LB0.http1 to httpConn_1_0.rec; - Attachment Server0.http0 to proxyConn_0_0.rec; - Attachment LB0.fwd0 to proxyConn_0_0.req; - Attachment ServerB0.http0 to proxyConn_1_0.rec; - Attachment LB0.fwd1 to proxyConn_1_0.req; - Attachment Server0.sql0 to dbConn_0_0.rec; - Attachment DB0.rec0 to dbConn_0_0.req; - Attachment ServerB0.sql0 to dbConn_1_0.rec; - Attachment DB0.rec1 to dbConn_1_0.req; - Attachment LB0.p to ProxyConnT0.req; - Attachment Server1.p to ProxyConnT0.rec; - Attachment Server1.p0 to SQLConnT0.req; - Attachment DB0.p to SQLConnT0.rec; - - Property MAX_RESPTIME = 2000.0; - - Property MAX_UTIL = 1; - - Property MALICIOUS_THRESHOLD = 0.8; - rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | - exists bh : BlackholerT in self.COMPONENTS | - contains(c.deploymentLocation, bh.blackholed); - rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | - forall ip : string in lb.blackholed | - forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | - c.maliciousness > self.MALICIOUS_THRESHOLD; -} - +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + Port Type PartPortT = { + + } + Port Type NetworkPortT = { + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Port Type ContainmentPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } + Role Type NetworkRoleT = { + + } + Role Type PartRoleT = { + + } + Role Type ContainerRoleT = { + + } + Connector Type MappingT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = true; >> ; + + } +} + +Family ZNewsFam extends EnvType with { + + Port Type HttpPortT extends ArchPortT with { + + } + Port Type ProxyForwardPortT extends ArchPortT with { + + } + Port Type HttpReqPortT extends ArchPortT with { + + } + Port Type SqlReqPort extends ArchPortT with { + + } + Port Type SqlRecPort extends ArchPortT with { + + } + Component Type ProxyT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Component Type ServerT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + Property reqServiceRate : float << default : float = 0.0; >> ; + + Property byteServiceRate : float << default : float = 0.0; >> ; + + Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; + + Property cost : float << default : float = 1.0; >> ; + + Property lastPageHit : Record [uri : string; cnt : int; kbytes : float; ]; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + Component Type ClientT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property experRespTime : float << default : float = 0.0; >> ; + + Property reqRate : float << default : float = 0.0; >> ; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + Component Type DBT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "locahost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Role Type ReceiverRoleT extends ArchRoleT with { + + } + Role Type RequestorRoleT extends ArchRoleT with { + + } + Connector Type ProxyConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Connector Type SQLConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Connector Type HttpConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + Property bandwidth : float << default : float = 0.0; >> ; + + Property latency : float << default : float = 0.0; >> ; + + Property numReqsSuccess : int << default : int = 0; >> ; + + Property numReqsRedirect : int << default : int = 0; >> ; + + Property numReqsClientError : int << default : int = 0; >> ; + + Property numReqsServerError : int << default : int = 0; >> ; + + Property latencyRate : float; + + } + + Property MIN_RESPTIME : float; + + Property MAX_RESPTIME : float << default : float = 2; >> ; + + Property TOLERABLE_PERCENT_UNHAPPY : float; + + Property UNHAPPY_GRADIENT_1 : float; + + Property UNHAPPY_GRADIENT_2 : float; + + Property UNHAPPY_GRADIENT_3 : float; + + Property FRACTION_GRADIENT_1 : float; + + Property FRACTION_GRADIENT_2 : float; + + Property FRACTION_GRADIENT_3 : float; + + Property MIN_UTIL : float; + + Property MAX_UTIL : float << default : float = 1; >> ; + + Property MAX_FIDELITY_LEVEL : int; + + Property THRESHOLD_FIDELITY : int; + + Property THRESHOLD_COST : float; +} + +Family DoSFam = { + + Element Type PotentiallyMaliciousT = { + + Property deploymentLocation : string; + + Property maliciousness : float << default : float = 0.0; >> ; + + } + Element Type MaliciousT extends PotentiallyMaliciousT with { + rule malicious = invariant maliciousness > MALICIOUS_THRESHOLD; + + } + Element Type SuspiciousT extends PotentiallyMaliciousT with { + rule suspicious = invariant maliciousness > SUSPICIOUS_THRESHOLD AND maliciousness <= MALICIOUS_THRESHOLD; + + } + Element Type NormalT extends PotentiallyMaliciousT with { + rule ok = invariant malicious <= SUSPICIOUS_THRESHOLD; + + } + Element Type BlackholerT = { + + Property blackholed : Set {string} << default : Set {string} = {}; >> ; + + } + Element Type CaptchaRedirectT = { + + Property captchaEnabled : boolean << default : boolean = false; >> ; + + } + Element Type ThrottlerT = { + + Property throttled : Set {string} << default : Set {string} = {}; >> ; + + } + Element Type CaptchaHandlerT = { + + Property captcha : int << default : int = 0; >> ; + + } + Element Type AuthenticationHandlerT = { + + Property authenticate : int << default : int = 0; >> ; + + } + Port Type BlackholedPortT = { + + Property isBlackholed : boolean = true; + + } + + Property MALICIOUS_THRESHOLD : float << default : float = 0.8; >> ; + + Property SUSPICIOUS_THRESHOLD : float << default : float = 0.5; >> ; + rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | + exists bh : BlackholerT in self.COMPONENTS | + contains(c.deploymentLocation, bh.blackholed); + rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | + forall ip : string in lb.blackholed | + forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | + c.maliciousness > self.MALICIOUS_THRESHOLD; +} + +Family ZNewsDosFam extends ZNewsFam, DoSFam with { + + Component Type ZNewsClientT extends ClientT, PotentiallyMaliciousT, CaptchaHandlerT, AuthenticationHandlerT with { + + } + Component Type ZNewsLBT extends ProxyT, CaptchaRedirectT, BlackholerT, ThrottlerT with { + + } +} + +System ZNewsSys : ZNewsDosFam = new ZNewsDosFam extended with { + + Component Server0 : ArchElementT, ServerT = new ArchElementT, ServerT extended with { + Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { + + Property isArchEnabled = true; + + } + Port sql0 : SqlReqPort = new SqlReqPort extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.web0}"; + + Property load = 0.0; + + Property reqServiceRate = 0.0; + + Property byteServiceRate = 0.0; + + Property fidelity = 5; + + Property cost = 1.0; + + Property isArchEnabled = true; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + + Component Server1 : ServerT = new ServerT extended with { + Port p : HttpPortT = new HttpPortT extended with { + + } + Port p0 : SqlReqPort = new SqlReqPort extended with { + + } + Property deploymentLocation = "${customize.system.target.web1}"; + Property load = 0.0; + + Property reqServiceRate = 0.0; + + Property byteServiceRate = 0.0; + + Property fidelity = 5; + + Property cost = 1.0; + + Property isArchEnabled = true; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + + Component ServerB0 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + Port http0 : ArchPortT, HttpPortT = new HttpPortT, ArchPortT extended with { + + Property isArchEnabled = false; + + } + Port sql0 : SqlReqPort = new SqlReqPort extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.web2}"; + + Property load = 0.0; + + Property reqServiceRate = 0.0; + + Property byteServiceRate = 0.0; + + Property fidelity = 5; + + Property cost = 1.0; + + Property isArchEnabled = false; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + Component LB0 : ZNewsLBT = new ZNewsLBT extended with { + Port http0 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + Port http1 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + Property captchaEnabled = false; + + } + Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + Property isArchEnabled = true; + + } + Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + Property isArchEnabled = false; + + } + Port p : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + + Property deploymentLocation = "${customize.system.target.lb}"; + + Property load = 0.0; + + Property isArchEnabled = true; + + Property blackholed = {}; + + Property captchaEnabled = false; + + Property throttled = {}; + + } + Component DB0 : DBT = new DBT extended with { + Port rec0 : SqlRecPort = new SqlRecPort extended with { + + Property isArchEnabled = true; + + } + Port rec1 : SqlRecPort = new SqlRecPort extended with { + + Property isArchEnabled = true; + + } + Port p : SqlRecPort = new SqlRecPort extended with { + + } + + Property deploymentLocation = "${customize.system.target.db}"; + + Property load = 0.0; + + Property isArchEnabled = true; + + } + Component Client0 : ZNewsClientT = new ZNewsClientT extended with { + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.client1}"; + + Property experRespTime = 5000; + + Property reqRate = 0.0; + + Property isArchEnabled = true; + + Property maliciousness = 0.0; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + Component Client1 : ZNewsClientT = new ZNewsClientT extended with { + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + Property deploymentLocation = "${customize.system.target.client2}"; + + Property experRespTime = 5000.0; + + Property reqRate = 0.0; + + Property isArchEnabled = true; + + Property maliciousness = 1.0; + + Property captcha = 0; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + + Connector httpConn_0_0 : HttpConnT = new HttpConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property bandwidth = 0.0; + + Property latency = 0.0; + + Property numReqsSuccess = 0; + + Property numReqsRedirect = 0; + + Property numReqsClientError = 0; + + Property numReqsServerError = 0; + + Property isArchEnabled = true; + + } + Connector httpConn_1_0 : HttpConnT = new HttpConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property bandwidth = 0.0; + + Property latency = 0.0; + + Property numReqsSuccess = 0; + + Property numReqsRedirect = 0; + + Property numReqsClientError = 0; + + Property numReqsServerError = 0; + + Property isArchEnabled = true; + + } + Connector proxyConn_0_0 : ProxyConnT = new ProxyConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = true; + + } + Connector proxyConn_1_0 : ProxyConnT = new ProxyConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + Property isArchEnabled = true; + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = false; + + } + Connector dbConn_0_0 : SQLConnT = new SQLConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = true; + + } + Connector dbConn_1_0 : SQLConnT = new SQLConnT extended with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + Property isArchEnabled = true; + + } + + Property isArchEnabled = true; + + } + Connector ProxyConnT0 : ProxyConnT = new ProxyConnT extended with { + + } + Connector SQLConnT0 : SQLConnT = new SQLConnT extended with { + + } + Attachment Client1.p0 to httpConn_0_0.req; + Attachment LB0.http0 to httpConn_0_0.rec; + Attachment Client0.p0 to httpConn_1_0.req; + Attachment LB0.http1 to httpConn_1_0.rec; + Attachment Server0.http0 to proxyConn_0_0.rec; + Attachment LB0.fwd0 to proxyConn_0_0.req; + Attachment ServerB0.http0 to proxyConn_1_0.rec; + Attachment LB0.fwd1 to proxyConn_1_0.req; + Attachment Server0.sql0 to dbConn_0_0.rec; + Attachment DB0.rec0 to dbConn_0_0.req; + Attachment ServerB0.sql0 to dbConn_1_0.rec; + Attachment DB0.rec1 to dbConn_1_0.req; + Attachment LB0.p to ProxyConnT0.req; + Attachment Server1.p to ProxyConnT0.rec; + Attachment Server1.p0 to SQLConnT0.req; + Attachment DB0.p to SQLConnT0.rec; + + Property MAX_RESPTIME = 2000.0; + + Property MAX_UTIL = 1; + + Property MALICIOUS_THRESHOLD = 0.8; + rule noActiveMalicious = invariant forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[maliciousness >= self.MALICIOUS_THRESHOLD] | + exists bh : BlackholerT in self.COMPONENTS | + contains(c.deploymentLocation, bh.blackholed); + rule noneUnfairlyPenalized = invariant forall lb : BlackholerT in self.COMPONENTS | + forall ip : string in lb.blackholed | + forall c : PotentiallyMaliciousT in /self/COMPONENTS:PotentiallyMaliciousT[deploymentLocation == ip] | + c.maliciousness > self.MALICIOUS_THRESHOLD; +} + diff --git a/targets/znews-ss_2/model/ZNewsSys.mtd b/targets/znews-ss_2/model/ZNewsSys.mtd index 9c791b08c..e608ac720 100644 --- a/targets/znews-ss_2/model/ZNewsSys.mtd +++ b/targets/znews-ss_2/model/ZNewsSys.mtd @@ -1,2005 +1,2005 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews-ss_2/model/gauges.yml b/targets/znews-ss_2/model/gauges.yml index 3acaaa602..a17c28649 100644 --- a/targets/znews-ss_2/model/gauges.yml +++ b/targets/znews-ss_2/model/gauges.yml @@ -1,134 +1,134 @@ -# -# Gauge Type and Gauge Instance Specifications -# - time periods generally in milliseconds -# -# History: -# - [SWC 2007.01.18] Created file, populated ZNews gauge descriptions. -# - [SWC 2007.04.09] Changed LatencyGaugeT to use RtLatencyMultiHostGauge. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# - [SWC 2007.04.11] Added ResponseTimeGaugeT -# - [BRS 2013.11.13] Changed to new format -# -gauge-types: - - - BlackHoleGaugeT: - commands: - blockedIPs: "BlackholerT.setBlackholed({String})" - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.BlackholeGauge" - configParams: - targetProbeType: - type: String - default: ~ - - ThrottleGaugeT: - commands: - throttledIPs: "ThrottlerT.setThrottled({String})" - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.ThrottleGauge" - configParams: - targetProbeType: - type: String - default: ~ - - MaliciousnessGaugeT: - commands: - maliciousness : PotentiallyMaliciousT.setMaliciousness (float) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.EchoGauge" - configParams: - targetGaugeName: - type: String - default: ~ - targetGaugeType: - type: String - default: ~ - targetGaugeValue: - type: String - default: ~ - comment: "EchoGaugeT echos a value reported by another gauge" - - DummyDiagnosisGaugeT: - commands: - maliciousness: PotentiallyMaliciousT.setMaliciousness (float) - captcha: CaptchaHandlerT.setCaptchaResponse (int) - authenticate: CaptchaHandlerT.setAuthenticationResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.DummyDiagnosisGauge" - configParams: - targetProbeList: - type: String - default: ~ - - CaptchaGaugeT: - commands: - enablement : ProxyT.setCaptchaEnabled (boolean) - clientMgmt : CaptchaHandlerT.setCaptchaResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 5000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.CaptchaGauge" - configParams: - targetProbeType: - type: String - default: ~ - - AuthenticationEnablementGaugeT: - commands: - clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 5000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge" - configParams: - targetProbeType: - type: String - default: ~ +# +# Gauge Type and Gauge Instance Specifications +# - time periods generally in milliseconds +# +# History: +# - [SWC 2007.01.18] Created file, populated ZNews gauge descriptions. +# - [SWC 2007.04.09] Changed LatencyGaugeT to use RtLatencyMultiHostGauge. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# - [SWC 2007.04.11] Added ResponseTimeGaugeT +# - [BRS 2013.11.13] Changed to new format +# +gauge-types: + + + BlackHoleGaugeT: + commands: + blockedIPs: "BlackholerT.setBlackholed({String})" + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.BlackholeGauge" + configParams: + targetProbeType: + type: String + default: ~ + + ThrottleGaugeT: + commands: + throttledIPs: "ThrottlerT.setThrottled({String})" + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.ThrottleGauge" + configParams: + targetProbeType: + type: String + default: ~ + + MaliciousnessGaugeT: + commands: + maliciousness : PotentiallyMaliciousT.setMaliciousness (float) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.EchoGauge" + configParams: + targetGaugeName: + type: String + default: ~ + targetGaugeType: + type: String + default: ~ + targetGaugeValue: + type: String + default: ~ + comment: "EchoGaugeT echos a value reported by another gauge" + + DummyDiagnosisGaugeT: + commands: + maliciousness: PotentiallyMaliciousT.setMaliciousness (float) + captcha: CaptchaHandlerT.setCaptchaResponse (int) + authenticate: CaptchaHandlerT.setAuthenticationResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.DummyDiagnosisGauge" + configParams: + targetProbeList: + type: String + default: ~ + + CaptchaGaugeT: + commands: + enablement : ProxyT.setCaptchaEnabled (boolean) + clientMgmt : CaptchaHandlerT.setCaptchaResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 5000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.CaptchaGauge" + configParams: + targetProbeType: + type: String + default: ~ + + AuthenticationEnablementGaugeT: + commands: + clientMgmt: AuthenticationHandlerT.setAuthenticationResponse (int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 5000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.AuthenticationEnablementGauge" + configParams: + targetProbeType: + type: String + default: ~ DiagnosisGaugeT: commands: @@ -143,401 +143,401 @@ gauge-types: javaClass: type: String default: "org.sa.rainbow.translator.znn.gauges.DiagnosisGauge" - configParams: - clients: - type: String + configParams: + clients: + type: String default: "c1=10.5.6.254" reportingPeriod: type: long default: 10000 comment: "Diagnosis gauge for DoS analysis" - - ResponseTimeGaugeT: - commands: - end2endRespTime : ClientT.setResponseTime (float) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znn.gauges.End2EndRespTimeGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "ResponseTimeGaugeT measures and reports the end-to-end response time from a client or its proxy." - - ApacheTopGaugeT: - commands: - reqServiceRate : ServerT.setReqServiceRate(float) - byteServiceRate : ServerT.setByteServiceRate(float) - numReqsSuccess : HttpConnT.setNumSuccessfulRequests(int) - numReqsRedirect : HttpConnT.setNumRedirectedRequests(int) - numReqsClientError : HttpConnT.setNumRequestsClientError(int) - numReqsServerError : HttpConnT.setNumRequestsServerError(int) - pageHit : ServerT.setLastPageHit(String) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.ApacheTopGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "ApacheTopGaugeT measures and reports properties of an Apache server, via a UNIX top like utility" - - DiskIOGaugeT: - commands: - transferRate : ServerT.setDiskTransferRate(double) - readRate : ServerT.setDiskReadRate(double) - writeRate : ServerT.setDiskWriteRate(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.DiskIOGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "DiskIOGaugeT measures and reports disk IO stat of the target host, read/write reported in KBps" - - LoadGaugeT: - commands: - load : ServerT.setLoad(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.CpuLoadGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "LoadGaugeT measures and reports CPU load of the target host" - - FidelityGaugeT: - commands: - fidelity : ServerT.setFidelity(int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.FidelityGauge" - configParams: - samplingFrequency: - type: long - default: 2500 - targetProbeType: - type: String - default: ~ - comment: "FidelityGaugeT measures and reports the fidelity level of served content" - - LatencyGaugeT: - commands: - latency : HttpConnT.setLatency(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge" - configParams: - samplingFrequency: - type: long - default: 1500 - targetProbeType: - type: String - default: ~ - comment: "LatencyGaugeT measures and reports latency on a connection" - - LatencyRateGaugeT: - commands: - latencyRate : HttpConnT.setLatencyRate(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge" - configParams: - samplingFrequency: - type: long - default: 1500 - targetProbeType: - type: String - default: ~ - comment: "LatencyRateGaugeT measures and reports the latency rate of change on a connection" - -gauge-instances: - - BHG1: - type: BlackHoleGaugeT - model: "ZNewsSys:Acme" - commands: - "blockedIPs": LB0.setBlackholed ($) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - reportingPeriod: 10000 - targetProbeType: blackhole - - TG1: - type: ThrottleGaugeT - model: "ZNewsSys:Acme" - commands: - "throttledIPs": LB0.setThrottled ($) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - reportingPeriod: 10000 - targetProbeType: throttle - - MG1: - type: DummyDiagnosisGaugeT - model: "ZNewsSys:Acme" - commands: - "maliciousness(x)": x.setMaliciousness ($) - "captcha(x)": x.setCaptchaResponse ($) - "authenticate(x)": x.setAuthenticationResponse ($) - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - reportingPeriod: 10000 - targetProbeList: "dummymaliciousness@*,authenticationprobe" - - - CG1: - type: CaptchaGaugeT - model: "ZNewsSys:Acme" - commands: - "enabled": LB0.setCaptchaEnabled($) - "clientMgmt(${customize.system.target.client1})": Client0.setCaptchaResponse (0) - "clientMgmt(${customize.system.target.client2})": Client1.setCaptchaResponse (0) - setupValues: - targetIP: "${customize.system.target.lb}" - configValues: - samplingFrequency: 1000 - targetProbeType: captchaprobe - - AEG1: - type: AuthenticationEnablementGaugeT - model: "ZNewsSys:Acme" - commands: - "clientMgmt(${customize.system.target.client1})": Client0.setAuthenticationResponse (0) - "clientMgmt(${customize.system.target.client2})": Client1.setAuthenticationResponse (0) - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - samplingFrequency: 1000 - targetProbeType: authenticationprobe + + ResponseTimeGaugeT: + commands: + end2endRespTime : ClientT.setResponseTime (float) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znn.gauges.End2EndRespTimeGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "ResponseTimeGaugeT measures and reports the end-to-end response time from a client or its proxy." + + ApacheTopGaugeT: + commands: + reqServiceRate : ServerT.setReqServiceRate(float) + byteServiceRate : ServerT.setByteServiceRate(float) + numReqsSuccess : HttpConnT.setNumSuccessfulRequests(int) + numReqsRedirect : HttpConnT.setNumRedirectedRequests(int) + numReqsClientError : HttpConnT.setNumRequestsClientError(int) + numReqsServerError : HttpConnT.setNumRequestsServerError(int) + pageHit : ServerT.setLastPageHit(String) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.ApacheTopGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "ApacheTopGaugeT measures and reports properties of an Apache server, via a UNIX top like utility" + + DiskIOGaugeT: + commands: + transferRate : ServerT.setDiskTransferRate(double) + readRate : ServerT.setDiskReadRate(double) + writeRate : ServerT.setDiskWriteRate(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.DiskIOGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "DiskIOGaugeT measures and reports disk IO stat of the target host, read/write reported in KBps" + + LoadGaugeT: + commands: + load : ServerT.setLoad(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.CpuLoadGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "LoadGaugeT measures and reports CPU load of the target host" + + FidelityGaugeT: + commands: + fidelity : ServerT.setFidelity(int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.FidelityGauge" + configParams: + samplingFrequency: + type: long + default: 2500 + targetProbeType: + type: String + default: ~ + comment: "FidelityGaugeT measures and reports the fidelity level of served content" + + LatencyGaugeT: + commands: + latency : HttpConnT.setLatency(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge" + configParams: + samplingFrequency: + type: long + default: 1500 + targetProbeType: + type: String + default: ~ + comment: "LatencyGaugeT measures and reports latency on a connection" + + LatencyRateGaugeT: + commands: + latencyRate : HttpConnT.setLatencyRate(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge" + configParams: + samplingFrequency: + type: long + default: 1500 + targetProbeType: + type: String + default: ~ + comment: "LatencyRateGaugeT measures and reports the latency rate of change on a connection" + +gauge-instances: + + BHG1: + type: BlackHoleGaugeT + model: "ZNewsSys:Acme" + commands: + "blockedIPs": LB0.setBlackholed ($) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + reportingPeriod: 10000 + targetProbeType: blackhole + + TG1: + type: ThrottleGaugeT + model: "ZNewsSys:Acme" + commands: + "throttledIPs": LB0.setThrottled ($) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + reportingPeriod: 10000 + targetProbeType: throttle + + MG1: + type: DummyDiagnosisGaugeT + model: "ZNewsSys:Acme" + commands: + "maliciousness(x)": x.setMaliciousness ($) + "captcha(x)": x.setCaptchaResponse ($) + "authenticate(x)": x.setAuthenticationResponse ($) + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + reportingPeriod: 10000 + targetProbeList: "dummymaliciousness@*,authenticationprobe" + + + CG1: + type: CaptchaGaugeT + model: "ZNewsSys:Acme" + commands: + "enabled": LB0.setCaptchaEnabled($) + "clientMgmt(${customize.system.target.client1})": Client0.setCaptchaResponse (0) + "clientMgmt(${customize.system.target.client2})": Client1.setCaptchaResponse (0) + setupValues: + targetIP: "${customize.system.target.lb}" + configValues: + samplingFrequency: 1000 + targetProbeType: captchaprobe + + AEG1: + type: AuthenticationEnablementGaugeT + model: "ZNewsSys:Acme" + commands: + "clientMgmt(${customize.system.target.client1})": Client0.setAuthenticationResponse (0) + "clientMgmt(${customize.system.target.client2})": Client1.setAuthenticationResponse (0) + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + samplingFrequency: 1000 + targetProbeType: authenticationprobe - EERTG1: - type: ResponseTimeGaugeT - model: "ZNewsSys:Acme" - commands: - "end2endRespTime(${customize.system.target.master})" : Client0.setResponseTime($) - "end2endRespTime(${customize.system.target.bad})" : Client1.setResponseTime($) - setupValues: - targetIP: "${customize.system.target.master}" - configValues: - samplingFrequency: 1000 - targetProbeType : clientproxy@* - comment: "EERTG1 is associated with the client component of the System, ZNewsSys, defined as an Acme model" - -unused-gauge-instances: - - MG1: - type: MaliciousnessGaugeT - model: "ZNewsSys:Acme" - mappings: - "maliciousness(c2)": Client1.maliciousness - "maliciousness(c1)": Client0.maliciousness - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - targetGaugeName: DG1 - targetGaugeType: DiagnosisGaugeT - targetGaugeValue: maliciousness - - DG1: - type: DiagnosisGaugeT - model: "ZNewsSys:Acme" - mappings: - "maliciousness": x - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - reportingPeriod: 10000 - - ATG1: - type: ApacheTopGaugeT - model: "ZNewsSys:Acme" - mappings: - reqServiceRate : s0.reqServiceRate - byteServiceRate : s0.byteServiceRate - numReqsSuccess : conn0.numReqsSuccess - numReqsRedirect : conn0.numReqsRedirect - numReqsClientError : conn0.numReqsClientError - numReqsServerError : conn0.numReqsServerError - pageHit : s0.lastPageHit - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: ~ - # Leave details unspecified (null) to use default value defined at the type-level - targetProbeType : apachetop - comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" - - DioG1: - type: DiskIOGaugeT - model: "ZNewsSys:Acme" - mappings: - transferRate : s0.diskXferRate - readRate : s0.diskReadRate - writeRate : s0.diskWriteRate - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1000 - targetProbeType : diskio - comment: "DioG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LoG0: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s0.load - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG0 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LoG1: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s1.load - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG1 is associated with the component s1 of the System, ZNewsSys, defined as an Acme model" - - FiG1: - type: FidelityGaugeT - model: "ZNewsSys:Acme" - mappings: - fidelity : s0.fidelity - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 2500 - targetProbeType : fidelity - comment: "FiG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LatG1: - type: LatencyGaugeT - model: "ZNewsSys:Acme" - mappings: - "latency(${rainbow.master.location.host})" : conn0.latency - "latency(@{ZNewsSys.s1.deploymentLocation})" : conn1.latency - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1500 - targetProbeType : pingrtt - comment: "LatG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" - - LatRoCG1: - type: LatencyRateGaugeT - model: "ZNewsSys:Acme" - mappings: - "latencyRate(${rainbow.master.location.host})" : conn0.latencyRate - "latencyRate(@{ZNewsSys.s1.deploymentLocation})" : conn1.latencyRate - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1500 - targetProbeType : pingrtt - comment: "LatRoCG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" - - ATG0: - type: ApacheTopGaugeT - model: "ZNewsSys:Acme" - mappings: - reqServiceRate : s0.reqServiceRate - byteServiceRate : s0.byteServiceRate - numReqsSuccess : conn0.numReqsSuccess - numReqsRedirect : conn0.numReqsRedirect - numReqsClientError : conn0.numReqsClientError - numReqsServerError : conn0.numReqsServerError - pageHit : s0.lastPageHit - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - samplingFrequency: ~ - # Leave details unspecified (null) to use default value defined at the type-level - targetProbeType : apachetop - comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" - - LoG3: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s3.load - setupValues: - targetIP: "${customize.system.target.3}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG3 is associated with the component s3 of the System, ZNewsSys, defined as an Acme model" - + EERTG1: + type: ResponseTimeGaugeT + model: "ZNewsSys:Acme" + commands: + "end2endRespTime(${customize.system.target.master})" : Client0.setResponseTime($) + "end2endRespTime(${customize.system.target.bad})" : Client1.setResponseTime($) + setupValues: + targetIP: "${customize.system.target.master}" + configValues: + samplingFrequency: 1000 + targetProbeType : clientproxy@* + comment: "EERTG1 is associated with the client component of the System, ZNewsSys, defined as an Acme model" + +unused-gauge-instances: + + MG1: + type: MaliciousnessGaugeT + model: "ZNewsSys:Acme" + mappings: + "maliciousness(c2)": Client1.maliciousness + "maliciousness(c1)": Client0.maliciousness + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + targetGaugeName: DG1 + targetGaugeType: DiagnosisGaugeT + targetGaugeValue: maliciousness + + DG1: + type: DiagnosisGaugeT + model: "ZNewsSys:Acme" + mappings: + "maliciousness": x + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + reportingPeriod: 10000 + + ATG1: + type: ApacheTopGaugeT + model: "ZNewsSys:Acme" + mappings: + reqServiceRate : s0.reqServiceRate + byteServiceRate : s0.byteServiceRate + numReqsSuccess : conn0.numReqsSuccess + numReqsRedirect : conn0.numReqsRedirect + numReqsClientError : conn0.numReqsClientError + numReqsServerError : conn0.numReqsServerError + pageHit : s0.lastPageHit + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: ~ + # Leave details unspecified (null) to use default value defined at the type-level + targetProbeType : apachetop + comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" + + DioG1: + type: DiskIOGaugeT + model: "ZNewsSys:Acme" + mappings: + transferRate : s0.diskXferRate + readRate : s0.diskReadRate + writeRate : s0.diskWriteRate + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1000 + targetProbeType : diskio + comment: "DioG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LoG0: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s0.load + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG0 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LoG1: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s1.load + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG1 is associated with the component s1 of the System, ZNewsSys, defined as an Acme model" + + FiG1: + type: FidelityGaugeT + model: "ZNewsSys:Acme" + mappings: + fidelity : s0.fidelity + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 2500 + targetProbeType : fidelity + comment: "FiG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LatG1: + type: LatencyGaugeT + model: "ZNewsSys:Acme" + mappings: + "latency(${rainbow.master.location.host})" : conn0.latency + "latency(@{ZNewsSys.s1.deploymentLocation})" : conn1.latency + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1500 + targetProbeType : pingrtt + comment: "LatG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" + + LatRoCG1: + type: LatencyRateGaugeT + model: "ZNewsSys:Acme" + mappings: + "latencyRate(${rainbow.master.location.host})" : conn0.latencyRate + "latencyRate(@{ZNewsSys.s1.deploymentLocation})" : conn1.latencyRate + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1500 + targetProbeType : pingrtt + comment: "LatRoCG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" + + ATG0: + type: ApacheTopGaugeT + model: "ZNewsSys:Acme" + mappings: + reqServiceRate : s0.reqServiceRate + byteServiceRate : s0.byteServiceRate + numReqsSuccess : conn0.numReqsSuccess + numReqsRedirect : conn0.numReqsRedirect + numReqsClientError : conn0.numReqsClientError + numReqsServerError : conn0.numReqsServerError + pageHit : s0.lastPageHit + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + samplingFrequency: ~ + # Leave details unspecified (null) to use default value defined at the type-level + targetProbeType : apachetop + comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" + + LoG3: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s3.load + setupValues: + targetIP: "${customize.system.target.3}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG3 is associated with the component s3 of the System, ZNewsSys, defined as an Acme model" + diff --git a/targets/znews-ss_2/model/op.map b/targets/znews-ss_2/model/op.map index 867bb0232..5cf840f9c 100644 --- a/targets/znews-ss_2/model/op.map +++ b/targets/znews-ss_2/model/op.map @@ -1,8 +1,8 @@ -setFidelity: changeState -blackhole: changeState -unblackhole: changeState -enableCaptcha: changeState -disableCaptcha: changeState -activateServer: start -deactivateServer: stop - +setFidelity: changeState +blackhole: changeState +unblackhole: changeState +enableCaptcha: changeState +disableCaptcha: changeState +activateServer: start +deactivateServer: stop + diff --git a/targets/znews-ss_2/rainbow-10.5.6.1.properties b/targets/znews-ss_2/rainbow-10.5.6.1.properties index cfc220922..f3b58f741 100644 --- a/targets/znews-ss_2/rainbow-10.5.6.1.properties +++ b/targets/znews-ss_2/rainbow-10.5.6.1.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.1 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.1 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss_2/rainbow-10.5.6.3.properties b/targets/znews-ss_2/rainbow-10.5.6.3.properties index cd2a3a569..1ae1db5fe 100644 --- a/targets/znews-ss_2/rainbow-10.5.6.3.properties +++ b/targets/znews-ss_2/rainbow-10.5.6.3.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.3 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.3 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss_2/rainbow-10.5.6.4.properties b/targets/znews-ss_2/rainbow-10.5.6.4.properties index dc87c9608..e2ffde51c 100644 --- a/targets/znews-ss_2/rainbow-10.5.6.4.properties +++ b/targets/znews-ss_2/rainbow-10.5.6.4.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.4 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.4 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss_2/rainbow-10.5.6.5.properties b/targets/znews-ss_2/rainbow-10.5.6.5.properties index f92704d09..e5cf62d61 100644 --- a/targets/znews-ss_2/rainbow-10.5.6.5.properties +++ b/targets/znews-ss_2/rainbow-10.5.6.5.properties @@ -1,10 +1,10 @@ -rainbow.master.location.host = 10.0.2.2 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.5.6.5 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory +rainbow.master.location.host = 10.0.2.2 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.5.6.5 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory diff --git a/targets/znews-ss_2/rainbow-fir.properties b/targets/znews-ss_2/rainbow-fir.properties index d3a02027c..6b602596d 100644 --- a/targets/znews-ss_2/rainbow-fir.properties +++ b/targets/znews-ss_2/rainbow-fir.properties @@ -1,37 +1,37 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = fir -#rainbow.master.location.host = jarrah -#rainbow.master.location.host = waterfall.able.cs.cmu.edu -#rainbow.master.location.host = fir.wv.cs.cmu.edu -#- Location information of the deployed delegate -rainbow.deployment.location = ${rainbow.master.location.host} -#rainbow.deployment.location = fir.wv.cs.cmu.edu -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = cygwin - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = waterfall.able.cs.cmu.edu -#customize.system.target.2 = phoenix -#customize.system.target.3 = fir -#customize.system.target.3 = fir.wv.cs.cmu.edu -#customize.system.target.size = 4 -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = fir +#rainbow.master.location.host = jarrah +#rainbow.master.location.host = waterfall.able.cs.cmu.edu +#rainbow.master.location.host = fir.wv.cs.cmu.edu +#- Location information of the deployed delegate +rainbow.deployment.location = ${rainbow.master.location.host} +#rainbow.deployment.location = fir.wv.cs.cmu.edu +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = cygwin + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = waterfall.able.cs.cmu.edu +#customize.system.target.2 = phoenix +#customize.system.target.3 = fir +#customize.system.target.3 = fir.wv.cs.cmu.edu +#customize.system.target.size = 4 +customize.system.target.size = 2 diff --git a/targets/znews-ss_2/rainbow-maple.properties b/targets/znews-ss_2/rainbow-maple.properties index 13d831aba..3decb02c7 100644 --- a/targets/znews-ss_2/rainbow-maple.properties +++ b/targets/znews-ss_2/rainbow-maple.properties @@ -1,29 +1,29 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = maple -#- Location information of the deployed delegate -rainbow.deployment.location = maple -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = waterfall.able.cs.cmu.edu -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = maple +#- Location information of the deployed delegate +rainbow.deployment.location = maple +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = waterfall.able.cs.cmu.edu +customize.system.target.size = 2 diff --git a/targets/znews-ss_2/rainbow-oracle.properties b/targets/znews-ss_2/rainbow-oracle.properties index 86a4ae4f1..e6ca2a9b3 100644 --- a/targets/znews-ss_2/rainbow-oracle.properties +++ b/targets/znews-ss_2/rainbow-oracle.properties @@ -1,32 +1,32 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = jarrah -#- Location information of the deployed delegate -rainbow.deployment.location = oracle -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = oracle -#customize.system.target.2 = phoenix -#customize.system.target.3 = waterfall.able.cs.cmu.edu -#customize.system.target.size = 4 -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = jarrah +#- Location information of the deployed delegate +rainbow.deployment.location = oracle +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = oracle +#customize.system.target.2 = phoenix +#customize.system.target.3 = waterfall.able.cs.cmu.edu +#customize.system.target.size = 4 +customize.system.target.size = 2 diff --git a/targets/znews-ss_2/rainbow-waterfall.able.cs.cmu.edu.properties b/targets/znews-ss_2/rainbow-waterfall.able.cs.cmu.edu.properties index 6dce5bcda..321152bf1 100644 --- a/targets/znews-ss_2/rainbow-waterfall.able.cs.cmu.edu.properties +++ b/targets/znews-ss_2/rainbow-waterfall.able.cs.cmu.edu.properties @@ -1,29 +1,29 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = maple -#- Location information of this deployed delegate -rainbow.deployment.location = waterfall.able.cs.cmu.edu -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = waterfall.able.cs.cmu.edu -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = maple +#- Location information of this deployed delegate +rainbow.deployment.location = waterfall.able.cs.cmu.edu +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = waterfall.able.cs.cmu.edu +customize.system.target.size = 2 diff --git a/targets/znews-ss_2/rainbow.properties b/targets/znews-ss_2/rainbow.properties index b9bd60cfa..617029b81 100644 --- a/targets/znews-ss_2/rainbow.properties +++ b/targets/znews-ss_2/rainbow.properties @@ -1,127 +1,127 @@ -################################################################################ -# Purpose: Common configuration file for the Rainbow infrastructure. -# Properties are loaded by class org.sa.rainbow.Rainbow . -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -### -# Default values for location specific properties, meaning that, if the -# rainbow-.properties file does not specify a value, the default value -# set here is used. - -### Utility mechanism configuration -#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL -logging.level = DEBUG -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log -# (default) -#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" -#logging.max.size = 1024 -#logging.max.backups = 5 - -### Rainbow component customization -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = 127.0.0.1 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.0.146 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.event.service = eseb -eBus Relay - -rainbow.delegate.beaconperiod = 10000 -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory - -### Rainbow models -rainbow.model.number=3 - -# Rainbow Acme model of ZNN -rainbow.model.path_0 = model/ZNewsSys.acme -rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory -rainbow.model.name_0 = ZNewsSys -rainbow.model.saveOnClose_0=true -rainbow.model.saveLocation_0=model/ZNewSys-post.acme - -# Rainbow utility model - keeps current utility along desired utility dimensions -# specified in stitch/utilities.yml -rainbow.model.path_1 = stitch/utilities.yml -rainbow.model.load.class_1=org.sa.rainbow.model.utility.UtilityCommandFactory -rainbow.model.name_1=ZNewsSys - -# Rainbow utility history model - keeps utility history -rainbow.model.load.class_2=org.sa.rainbow.model.utility.UtilityHistoryCommandFactory -rainbow.model.name_2=ZNewsSys -rainbow.model.saveOnClose_2=true -rainbow.model.saveLocation_2=model/uh.csv - - -### Rainbow analyses -rainbow.analyses.size = 2 -# Checks architecture for architectural errors -rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator -# Calculates utility of the system after each change to the arch model -rainbow.analyses_1 = org.sa.rainbow.evaluator.utility.UtilityEvaluator - -#Rainbow adaptation & stitch components -rainbow.adaptation.manager.size = 1 -rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager -rainbow.adaptation.manager.model_0=ZNewsSys:Acme - -rainbow.adaptation.executor.size = 1 -rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.StitchExecutor -rainbow.adaptation.executor.model_0=ZNewsSys:Acme - -rainbow.effector.manager.size = 1 -rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager - - -customize.model.evaluate.period = 2000 -## Translator customization -#- Gauge spec -customize.gauges.path = model/gauges.yml -#- Probe spec -customize.probes.path = system/probes.yml -#- Operator spec as mapping to effector -customize.archop.map.path = model/op.map -#- Effector spec -customize.effectors.path = system/effectors.yml -## Adaptation Manager -#- Directory of Stitch adaptation script -customize.scripts.path = stitch -#- Utilities description file, Strategy evaluation config, and minimum score threshold -customize.utility.path = stitch/utilities.yml -customize.utility.trackStrategy = uSF -customize.utility.score.minimum.threshold = 0.33 -customize.utility.scenario = scenario 1 -#- Whether to enable prediction, ONLY enable if system has predictor probes! -#customize.prediction.enable = false - -## System configuration information -# These properties may be referred to in various files -# in the target (e.g., Acme, gauges, effectors, probes) -# and are replaced by Rainbow with the actual values -customize.system.target.master = ${rainbow.deployment.location} -customize.system.target.lb = 10.0.0.173 -customize.system.target.lb.httpPort = 1081 -customize.system.target.web0 = 10.0.0.210 -customize.system.target.web0.httpPort = 1080 -customize.system.target.web1 = 10.0.0.98 -customize.system.target.web1.httpPort = 1080 -customize.system.target.db = 10.0.0.21 -customize.system.target.web2 = 10.0.0.183 -customize.system.target.web2.httpPort=1080 -customize.system.target.web2.disabled=true -customize.system.target.client1=10.0.0.146 -customize.system.target.client2=10.0.0.1 -customize.system.target.bad=10.0.0.1 +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +logging.level = DEBUG +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = 127.0.0.1 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.0.146 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.event.service = eseb +eBus Relay + +rainbow.delegate.beaconperiod = 10000 +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory + +### Rainbow models +rainbow.model.number=3 + +# Rainbow Acme model of ZNN +rainbow.model.path_0 = model/ZNewsSys.acme +rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory +rainbow.model.name_0 = ZNewsSys +rainbow.model.saveOnClose_0=true +rainbow.model.saveLocation_0=model/ZNewSys-post.acme + +# Rainbow utility model - keeps current utility along desired utility dimensions +# specified in stitch/utilities.yml +rainbow.model.path_1 = stitch/utilities.yml +rainbow.model.load.class_1=org.sa.rainbow.model.utility.UtilityCommandFactory +rainbow.model.name_1=ZNewsSys + +# Rainbow utility history model - keeps utility history +rainbow.model.load.class_2=org.sa.rainbow.model.utility.UtilityHistoryCommandFactory +rainbow.model.name_2=ZNewsSys +rainbow.model.saveOnClose_2=true +rainbow.model.saveLocation_2=model/uh.csv + + +### Rainbow analyses +rainbow.analyses.size = 2 +# Checks architecture for architectural errors +rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator +# Calculates utility of the system after each change to the arch model +rainbow.analyses_1 = org.sa.rainbow.evaluator.utility.UtilityEvaluator + +#Rainbow adaptation & stitch components +rainbow.adaptation.manager.size = 1 +rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager +rainbow.adaptation.manager.model_0=ZNewsSys:Acme + +rainbow.adaptation.executor.size = 1 +rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.StitchExecutor +rainbow.adaptation.executor.model_0=ZNewsSys:Acme + +rainbow.effector.manager.size = 1 +rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager + + +customize.model.evaluate.period = 2000 +## Translator customization +#- Gauge spec +customize.gauges.path = model/gauges.yml +#- Probe spec +customize.probes.path = system/probes.yml +#- Operator spec as mapping to effector +customize.archop.map.path = model/op.map +#- Effector spec +customize.effectors.path = system/effectors.yml +## Adaptation Manager +#- Directory of Stitch adaptation script +customize.scripts.path = stitch +#- Utilities description file, Strategy evaluation config, and minimum score threshold +customize.utility.path = stitch/utilities.yml +customize.utility.trackStrategy = uSF +customize.utility.score.minimum.threshold = 0.33 +customize.utility.scenario = scenario 1 +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# These properties may be referred to in various files +# in the target (e.g., Acme, gauges, effectors, probes) +# and are replaced by Rainbow with the actual values +customize.system.target.master = ${rainbow.deployment.location} +customize.system.target.lb = 10.0.0.173 +customize.system.target.lb.httpPort = 1081 +customize.system.target.web0 = 10.0.0.210 +customize.system.target.web0.httpPort = 1080 +customize.system.target.web1 = 10.0.0.98 +customize.system.target.web1.httpPort = 1080 +customize.system.target.db = 10.0.0.21 +customize.system.target.web2 = 10.0.0.183 +customize.system.target.web2.httpPort=1080 +customize.system.target.web2.disabled=true +customize.system.target.client1=10.0.0.146 +customize.system.target.client2=10.0.0.1 +customize.system.target.bad=10.0.0.1 diff --git a/targets/znews-ss_2/rainbow.properties-all-in-one-machine b/targets/znews-ss_2/rainbow.properties-all-in-one-machine index f05013820..349283e56 100644 --- a/targets/znews-ss_2/rainbow.properties-all-in-one-machine +++ b/targets/znews-ss_2/rainbow.properties-all-in-one-machine @@ -1,112 +1,112 @@ -################################################################################ -# Purpose: Common configuration file for the Rainbow infrastructure. -# Properties are loaded by class org.sa.rainbow.Rainbow . -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -### -# Default values for location specific properties, meaning that, if the -# rainbow-.properties file does not specify a value, the default value -# set here is used. - -### Utility mechanism configuration -#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL -logging.level = DEBUG -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log -# (default) -#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" -#logging.max.size = 1024 -#logging.max.backups = 5 - -### Rainbow component customization -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = 127.0.0.1 -#- Location information of the deployed delegate -rainbow.deployment.location = 10.0.2.2 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1100 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que | eseb -rainbow.event.service = eseb -eBus Relay - -rainbow.delegate.beaconperiod = 10000 -rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory - -#Rainbow models -rainbow.model.number=1 -rainbow.model.path_0 = model/ZNewsSys.acme -rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory -rainbow.model.name_0 = ZNewsSys - -#Rainbow analyses -rainbow.analyses.size = 1 -rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator - -#Rainbow adaptation & stitch components -rainbow.adaptation.manager.size = 1 -rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager -rainbow.adaptation.manager.model_0=ZNewsSys:Acme - -rainbow.adaptation.executor.size = 1 -rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.Executor -rainbow.adaptation.executor.model_0=ZNewsSys:Acme - -rainbow.effector.manager.size = 1 -rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager - - -customize.model.evaluate.period = 2000 -## Translator customization -#- Gauge spec -customize.gauges.path = model/gauges.yml -#- Probe spec -customize.probes.path = system/probes.yml -#- Operator spec as mapping to effector -customize.archop.map.path = model/op.map -#- Effector spec -customize.effectors.path = system/effectors.yml -## Adaptation Manager -#- Directory of Stitch adaptation script -customize.scripts.path = stitch -#- Utilities description file, Strategy evaluation config, and minimum score threshold -customize.utility.path = stitch/utilities.yml -customize.utility.trackStrategy = uSF -customize.utility.score.minimum.threshold = 0.33 -customize.utility.scenario = scenario 2 -#- Whether to enable prediction, ONLY enable if system has predictor probes! -#customize.prediction.enable = false - -## System configuration information -# -#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: -#customize.system.sim.path = znewspred/znews-transbw.sim -#- if real target system: -#customize.system.target.0 = ${rainbow.master.location.host} -#customize.system.target.1 = 10.0.2.15 -#customize.system.target.1 = waterfall.able.cs.cmu.edu -#customize.system.target.0 = localhost -#customize.system.target.2 = oracle -#customize.system.target.size = 3 -#customize.system.target.size = 2 -customize.system.target.master = ${rainbow.deployment.location} -customize.system.target.lb = 10.5.6.1 -customize.system.target.lb.httpPort = 1081 -customize.system.target.web0 = 10.5.6.1 -customize.system.target.web0.httpPort = 1080 -customize.system.target.web1 = 10.5.6.1 -customize.system.target.web1.httpPort = 1082 -customize.system.target.db = 10.5.6.1 -#customize.system.target.0 = ${rainbow.deployment.location} -#customize.system.target.1 = 10.5.6.1 -#customize.system.target.size = 2 +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +logging.level = DEBUG +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = 127.0.0.1 +#- Location information of the deployed delegate +rainbow.deployment.location = 10.0.2.2 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1100 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que | eseb +rainbow.event.service = eseb +eBus Relay + +rainbow.delegate.beaconperiod = 10000 +rainbow.deployment.factory.class = org.sa.rainbow.core.ports.eseb.ESEBRainbowPortFactory + +#Rainbow models +rainbow.model.number=1 +rainbow.model.path_0 = model/ZNewsSys.acme +rainbow.model.load.class_0 = org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory +rainbow.model.name_0 = ZNewsSys + +#Rainbow analyses +rainbow.analyses.size = 1 +rainbow.analyses_0 = org.sa.rainbow.evaluator.acme.ArchEvaluator + +#Rainbow adaptation & stitch components +rainbow.adaptation.manager.size = 1 +rainbow.adaptation.manager.class_0=org.sa.rainbow.stitch.adaptation.AdaptationManager +rainbow.adaptation.manager.model_0=ZNewsSys:Acme + +rainbow.adaptation.executor.size = 1 +rainbow.adaptation.executor.class_0=org.sa.rainbow.stitch.adaptation.Executor +rainbow.adaptation.executor.model_0=ZNewsSys:Acme + +rainbow.effector.manager.size = 1 +rainbow.effector.manager.class_0=org.sa.rainbow.effectors.acme.AcmeEffectorManager + + +customize.model.evaluate.period = 2000 +## Translator customization +#- Gauge spec +customize.gauges.path = model/gauges.yml +#- Probe spec +customize.probes.path = system/probes.yml +#- Operator spec as mapping to effector +customize.archop.map.path = model/op.map +#- Effector spec +customize.effectors.path = system/effectors.yml +## Adaptation Manager +#- Directory of Stitch adaptation script +customize.scripts.path = stitch +#- Utilities description file, Strategy evaluation config, and minimum score threshold +customize.utility.path = stitch/utilities.yml +customize.utility.trackStrategy = uSF +customize.utility.score.minimum.threshold = 0.33 +customize.utility.scenario = scenario 2 +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# +#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: +#customize.system.sim.path = znewspred/znews-transbw.sim +#- if real target system: +#customize.system.target.0 = ${rainbow.master.location.host} +#customize.system.target.1 = 10.0.2.15 +#customize.system.target.1 = waterfall.able.cs.cmu.edu +#customize.system.target.0 = localhost +#customize.system.target.2 = oracle +#customize.system.target.size = 3 +#customize.system.target.size = 2 +customize.system.target.master = ${rainbow.deployment.location} +customize.system.target.lb = 10.5.6.1 +customize.system.target.lb.httpPort = 1081 +customize.system.target.web0 = 10.5.6.1 +customize.system.target.web0.httpPort = 1080 +customize.system.target.web1 = 10.5.6.1 +customize.system.target.web1.httpPort = 1082 +customize.system.target.db = 10.5.6.1 +#customize.system.target.0 = ${rainbow.deployment.location} +#customize.system.target.1 = 10.5.6.1 +#customize.system.target.size = 2 diff --git a/targets/znews-ss_2/stitch/README.txt b/targets/znews-ss_2/stitch/README.txt index fe0c94a76..1a5abb8c4 100644 --- a/targets/znews-ss_2/stitch/README.txt +++ b/targets/znews-ss_2/stitch/README.txt @@ -1,2 +1,2 @@ -Extension: Stitch scripts must have the extension ".s"; otherwise, the -Adaptation Manager will not know to load it. +Extension: Stitch scripts must have the extension ".s"; otherwise, the +Adaptation Manager will not know to load it. diff --git a/targets/znews-ss_2/stitch/dosStrategies.s b/targets/znews-ss_2/stitch/dosStrategies.s index 76e36f37e..913cc3f4b 100644 --- a/targets/znews-ss_2/stitch/dosStrategies.s +++ b/targets/znews-ss_2/stitch/dosStrategies.s @@ -1,103 +1,103 @@ -/* - * Adaptation script for security attacks - */ - -module dos.strategies; -import op "org.sa.rainbow.stitch.lib.*"; -import op "org.sa.rainbow.model.acme.znn.ZNN"; -import lib "dosTactics.s"; -import lib "newssiteTactics.s"; - -//define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); - -define boolean haveMaliciousAndSuspicious = exists c : D.ZNewsClientT in M.components | (c.maliciousness >= M.SUSPICIOUS_THRESHOLD); - -define boolean unhandledMalicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness >= M.MALICIOUS_THRESHOLD) && !((exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.blackholed)) || c.captcha == -1 || c.authenticate == -1)); - -// There are people who are suspicious but haven't been throttled -define boolean unhandledSuspicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness < M.MALICIOUS_THRESHOLD && c.maliciousness > M.SUSPICIOUS_THRESHOLD) && !((exists b : D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.throttled)) || c.captcha == -1 || c.authenticate == -1)); - -// There are clients blackholed that are not malicious -define boolean cUnfairlyPenalizedClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD))); - -// There are clients throttled that are not suspicous -define boolean cUnfairlyThrottledClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSPICOUS_THRESHOLD && c.maliciousness <= M.SUSPICIOUS_THRESHOLD))); - -// We haven't captchaed -define boolean cNotChallenging = exists c : D.ZNewsLBT in M.components | (c.captchaEnabled == false); - -// Non-malicious clients are suffering high response times -define boolean cHiRespTime = exists c : T.ClientT/*,D.ZNewsClientT*/ in M.components | (c.experRespTime > M.MAX_RESPTIME); - -// There is atleast one reserve server available -define boolean serversAvailable = ZNN.availableServices(M,T.ServerT) > 0; - -/* Stop the attack by placing attackers into a blackhole. This strategy is triggered - * by the presence of an attacker and an impact on response time - */ -strategy EliminateStrategy -[ cHiRespTime && (unhandledMalicious || unhandledSuspicious) ] { - t0: (unhandledMalicious || unhandledSuspicious) -> blackholeAttacker() @[5000 /*ms*/] { - t1: (!unhandledMalicious) -> done; - t1a: (unhandledSuspicious) -> throttleSuspicious () @[5000] { - t2a: (default) -> TNULL; // in this case, we have no more steps to take - t2b: (success) -> done; - } - } -} - -strategy RestoreStrategy -[cUnfairlyPenalizedClients || cUnfairlyThrottledClients] { - t0: (cUnfairlyPenalizedClients) -> unblackholeAttacker () @[2000 /*ms*/] { - t1 : (!cUnfairlyPenalizedClients) -> done; - t1a: (default) -> TNULL; - } - t2 : (cUnfairlyThrottledClients) -> unthrottle () @[2000] { - t2a: (!cUnfairlyThrottledClients) -> done; - t2b: (default) -> TNULL; - } -} - -strategy Challenge [cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { - t0: (cNotChallenging) -> addCaptcha () @[5000] { - t1: (success) -> done; - t1a: (default) -> TNULL; - } - t2: (!cNotChallenging) -> forceReauthentication () @[5000] { - t3: (success) -> done; - t3a: (default) -> TNULL; - - } -} - - - -strategy DisableChallenges [!haveMaliciousAndSuspicious && !cNotChallenging] { - t0: (!cNotChallenging) -> removeCaptcha () @[1000] { - t1: (cNotChallenging) -> done; - } -} - - -strategy SimpleReduceResponseTime -[cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { - t0: (/*hiLoad*/ cHiRespTime) -> enlistServers(1) @[1000 /*ms*/] { - t1: (!cHiRespTime) -> done; - t2: (cHiRespTime) -> lowerFidelity(2, 100) @[3000 /*ms*/] { - t2a: (!cHiRespTime) -> done; - t2b: (default) -> TNULL; // in this case, we have no more steps to take - } - } -} - -/* This strategy allocates more capacity to counter the impact of a DoS attack. - */ -//strategy IncreaseCapacityStrategy -//[ styleApplies && cHiRespTime && serversAvailable] { -// t0: (/* under attack */ cHiRespTime) -> enlistServer(1) @[1000 /*ms*/] { -// t1: (!cHiRespTime) -> done; -// t1a: (default) -> TNULL; // in this case, we have no more steps to take -// } -//} - - +/* + * Adaptation script for security attacks + */ + +module dos.strategies; +import op "org.sa.rainbow.stitch.lib.*"; +import op "org.sa.rainbow.model.acme.znn.ZNN"; +import lib "dosTactics.s"; +import lib "newssiteTactics.s"; + +//define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); + +define boolean haveMaliciousAndSuspicious = exists c : D.ZNewsClientT in M.components | (c.maliciousness >= M.SUSPICIOUS_THRESHOLD); + +define boolean unhandledMalicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness >= M.MALICIOUS_THRESHOLD) && !((exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.blackholed)) || c.captcha == -1 || c.authenticate == -1)); + +// There are people who are suspicious but haven't been throttled +define boolean unhandledSuspicious = exists c : D.ZNewsClientT in M.components | ((c.maliciousness < M.MALICIOUS_THRESHOLD && c.maliciousness > M.SUSPICIOUS_THRESHOLD) && !((exists b : D.ZNewsLBT in M.components | M.contains (c.deploymentLocation, b.throttled)) || c.captcha == -1 || c.authenticate == -1)); + +// There are clients blackholed that are not malicious +define boolean cUnfairlyPenalizedClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD))); + +// There are clients throttled that are not suspicous +define boolean cUnfairlyThrottledClients = !(forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSPICOUS_THRESHOLD && c.maliciousness <= M.SUSPICIOUS_THRESHOLD))); + +// We haven't captchaed +define boolean cNotChallenging = exists c : D.ZNewsLBT in M.components | (c.captchaEnabled == false); + +// Non-malicious clients are suffering high response times +define boolean cHiRespTime = exists c : T.ClientT/*,D.ZNewsClientT*/ in M.components | (c.experRespTime > M.MAX_RESPTIME); + +// There is atleast one reserve server available +define boolean serversAvailable = ZNN.availableServices(M,T.ServerT) > 0; + +/* Stop the attack by placing attackers into a blackhole. This strategy is triggered + * by the presence of an attacker and an impact on response time + */ +strategy EliminateStrategy +[ cHiRespTime && (unhandledMalicious || unhandledSuspicious) ] { + t0: (unhandledMalicious || unhandledSuspicious) -> blackholeAttacker() @[5000 /*ms*/] { + t1: (!unhandledMalicious) -> done; + t1a: (unhandledSuspicious) -> throttleSuspicious () @[5000] { + t2a: (default) -> TNULL; // in this case, we have no more steps to take + t2b: (success) -> done; + } + } +} + +strategy RestoreStrategy +[cUnfairlyPenalizedClients || cUnfairlyThrottledClients] { + t0: (cUnfairlyPenalizedClients) -> unblackholeAttacker () @[2000 /*ms*/] { + t1 : (!cUnfairlyPenalizedClients) -> done; + t1a: (default) -> TNULL; + } + t2 : (cUnfairlyThrottledClients) -> unthrottle () @[2000] { + t2a: (!cUnfairlyThrottledClients) -> done; + t2b: (default) -> TNULL; + } +} + +strategy Challenge [cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { + t0: (cNotChallenging) -> addCaptcha () @[5000] { + t1: (success) -> done; + t1a: (default) -> TNULL; + } + t2: (!cNotChallenging) -> forceReauthentication () @[5000] { + t3: (success) -> done; + t3a: (default) -> TNULL; + + } +} + + + +strategy DisableChallenges [!haveMaliciousAndSuspicious && !cNotChallenging] { + t0: (!cNotChallenging) -> removeCaptcha () @[1000] { + t1: (cNotChallenging) -> done; + } +} + + +strategy SimpleReduceResponseTime +[cHiRespTime && (unhandledMalicious || unhandledSuspicious)] { + t0: (/*hiLoad*/ cHiRespTime) -> enlistServers(1) @[1000 /*ms*/] { + t1: (!cHiRespTime) -> done; + t2: (cHiRespTime) -> lowerFidelity(2, 100) @[3000 /*ms*/] { + t2a: (!cHiRespTime) -> done; + t2b: (default) -> TNULL; // in this case, we have no more steps to take + } + } +} + +/* This strategy allocates more capacity to counter the impact of a DoS attack. + */ +//strategy IncreaseCapacityStrategy +//[ styleApplies && cHiRespTime && serversAvailable] { +// t0: (/* under attack */ cHiRespTime) -> enlistServer(1) @[1000 /*ms*/] { +// t1: (!cHiRespTime) -> done; +// t1a: (default) -> TNULL; // in this case, we have no more steps to take +// } +//} + + diff --git a/targets/znews-ss_2/stitch/dosTactics.s b/targets/znews-ss_2/stitch/dosTactics.s index b2db07c05..c1303bcd3 100644 --- a/targets/znews-ss_2/stitch/dosTactics.s +++ b/targets/znews-ss_2/stitch/dosTactics.s @@ -1,160 +1,160 @@ -module dos.strategies; - -import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T, ZNewsDosFam as D} ; -import op "org.sa.rainbow.stitch.lib.*"; - -//-------------------------------------------------------------------------------------------------- -// ! exists c : ClientT in self.components | (c.isMalicious and !c.is_blackholed) -// -// Failing this would cause the strategy to fire -// In the long run, isMalicious could be a float that captures the probability -// that a client is malicious -- in this case, we would have a threshold value -// -// Countermeasure #3: Black Hole the attacker(s) -// Blackholing means replying with ICMP giving reason for Black hole the attacking -// client by redirecting connections from a client -// for some period of time (i.e. black hole the traffic). -// -tactic blackholeAttacker () { - condition { - exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.blackholed))); - - // currently just checking if the client is identified as malicious. - // exists c:D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD; - } - action { - // Find the attacker. Currently, this is done by checking if client is identified as an attacker - // the blackHole() routine re-routes all traffic from a client away from the backed servers - // thereby preventing attackers from consuming ZNN resources. - // - set evilClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD}; - set blackholedClients = M.LB0.blackholed; - for (T.ClientT target : evilClients) { - blackholedClients = Set.add (blackholedClients, target.deploymentLocation); - } - M.setBlackholed (M.LB0, blackholedClients); - } - effect { - // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? - // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true - // if the client is blackholed and false otherwise - forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.blackholed))); - //forall c:T.ClientT in M.components | (c.maliciousness > M.MALICIOUS_THRESHOLD) -> !c.isBlackholed)); - } -} - -tactic unblackholeAttacker () { - condition { - exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.blackholed) && c.maliciousness <= M.MALICIOUS_THRESHOLD); - } - action { - set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.MALICIOUS_THRESHOLD}; - set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.blackholed) > 0}; - for (D.ZNewsLBT l : lbs) { - set blackholedClients = l.blackholed; - for (D.ZNewsClientT c : reformedClients) { - // Curiously, if the unblackhole is only in the op.map and - // not in the the EffectOp class, then the parameters need - // to be paired with their parameter name - // Thus, (...,"client", c.deploymentLocation) here - // compared to blackhole above, which is actually - // a method provided in the EffectOp class - blackholedClients = Set.remove (blackholedClients, c.deploymentLocation); - } - M.setBlackholed (l, blackholedClients); - } - } - effect { - forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD)); - } -} - -tactic throttleSuspicious () { - condition { - exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.throttled))); - } - action { - // Find the attacker. Currently, this is done by checking if client is identified as an attacker - // the blackHole() routine re-routes all traffic from a client away from the backed servers - // thereby preventing attackers from consuming ZNN resources. - // - set suspciousClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.SUSCPICIOUS_THRESHOLD}; - set throttledClients = M.LB0.throttled; - for (T.ClientT target : suspciousClients) { - throttledClients = Set.add (throttledClients, target.deploymentLocation); - } - M.setThrottled (M.LB0, throttledClients); - } - effect { - // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? - // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true - // if the client is blackholed and false otherwise - forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.throttled))); - } -} - -tactic unthrottle () { - condition { - exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.throttled) && c.maliciousness <= M.SUSCPICIOUS_THRESHOLD); - } - action { - set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.SUSCPICIOUS_THRESHOLD}; - set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.throttled) > 0}; - for (D.ZNewsLBT l : lbs) { - set throttledClients = l.throttled; - for (D.ZNewsClientT c : reformedClients) { - throttledClients = Set.remove (throttledClients, c.deploymentLocation); - } - M.setThrottled (l, throttledClients); - } - } - effect { - forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSCPICIOUS_THRESHOLD)); - } -} - -tactic forceReauthentication () { - condition { - true; - } - action { - for (ProxyT lb : M.components) { - M.forceReauthentication (lb); - } - } - effect { - true; - } -} - -tactic addCaptcha () { - condition { - exists lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; - } - action { - set lbs = {select l : D.ZNewsLBT in M.components | !l.captchaEnabled}; - for (D.ZNewsLBT l : lbs) { - M.setCaptchaEnabled (l, true); - } - } - effect { - forall lb:D.ZNewsLBT in M.components | lb.captchaEnabled; - } -} - -tactic removeCaptcha () { - condition { - exists lb:D.ZNewsLBT in M.components | lb.captchaEnabled; - } - action { - set lbs = {select l : D.ZNewsLBT in M.components | l.captchaEnabled}; - for (D.ZNewsLBT l : lbs) { - M.setCaptchaEnabled (l, false); - } - } - effect { - forall lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; - } -} - - +module dos.strategies; + +import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T, ZNewsDosFam as D} ; +import op "org.sa.rainbow.stitch.lib.*"; + +//-------------------------------------------------------------------------------------------------- +// ! exists c : ClientT in self.components | (c.isMalicious and !c.is_blackholed) +// +// Failing this would cause the strategy to fire +// In the long run, isMalicious could be a float that captures the probability +// that a client is malicious -- in this case, we would have a threshold value +// +// Countermeasure #3: Black Hole the attacker(s) +// Blackholing means replying with ICMP giving reason for Black hole the attacking +// client by redirecting connections from a client +// for some period of time (i.e. black hole the traffic). +// +tactic blackholeAttacker () { + condition { + exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.blackholed))); + + // currently just checking if the client is identified as malicious. + // exists c:D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD; + } + action { + // Find the attacker. Currently, this is done by checking if client is identified as an attacker + // the blackHole() routine re-routes all traffic from a client away from the backed servers + // thereby preventing attackers from consuming ZNN resources. + // + set evilClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.MALICIOUS_THRESHOLD}; + set blackholedClients = M.LB0.blackholed; + for (T.ClientT target : evilClients) { + blackholedClients = Set.add (blackholedClients, target.deploymentLocation); + } + M.setBlackholed (M.LB0, blackholedClients); + } + effect { + // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? + // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true + // if the client is blackholed and false otherwise + forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.MALICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.blackholed))); + //forall c:T.ClientT in M.components | (c.maliciousness > M.MALICIOUS_THRESHOLD) -> !c.isBlackholed)); + } +} + +tactic unblackholeAttacker () { + condition { + exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.blackholed) && c.maliciousness <= M.MALICIOUS_THRESHOLD); + } + action { + set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.MALICIOUS_THRESHOLD}; + set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.blackholed) > 0}; + for (D.ZNewsLBT l : lbs) { + set blackholedClients = l.blackholed; + for (D.ZNewsClientT c : reformedClients) { + // Curiously, if the unblackhole is only in the op.map and + // not in the the EffectOp class, then the parameters need + // to be paired with their parameter name + // Thus, (...,"client", c.deploymentLocation) here + // compared to blackhole above, which is actually + // a method provided in the EffectOp class + blackholedClients = Set.remove (blackholedClients, c.deploymentLocation); + } + M.setBlackholed (l, blackholedClients); + } + } + effect { + forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.blackholed | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.MALICIOUS_THRESHOLD)); + } +} + +tactic throttleSuspicious () { + condition { + exists c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) && !(exists b:D.ZNewsLBT in M.components | M.contains(c.deploymentLocation, b.throttled))); + } + action { + // Find the attacker. Currently, this is done by checking if client is identified as an attacker + // the blackHole() routine re-routes all traffic from a client away from the backed servers + // thereby preventing attackers from consuming ZNN resources. + // + set suspciousClients = { select c : D.ZNewsClientT in M.components | c.maliciousness > M.SUSCPICIOUS_THRESHOLD}; + set throttledClients = M.LB0.throttled; + for (T.ClientT target : suspciousClients) { + throttledClients = Set.add (throttledClients, target.deploymentLocation); + } + M.setThrottled (M.LB0, throttledClients); + } + effect { + // all the clients that were malicious are now blackholed. Perhaps the "and" is too strong here? + // Do we want to have clients blackholed that are not malicious? This isBlackHoled() routuine returns true + // if the client is blackholed and false otherwise + forall c:D.ZNewsClientT in M.components | ((c.maliciousness > M.SUSCPICIOUS_THRESHOLD) -> (exists b:D.ZNewsLBT in M.components | M.contains (c.deploymentLocation,b.throttled))); + } +} + +tactic unthrottle () { + condition { + exists c:D.ZNewsClientT in M.components | exists l:D.ZNewsLBT in M.components | (M.contains(c.deploymentLocation, l.throttled) && c.maliciousness <= M.SUSCPICIOUS_THRESHOLD); + } + action { + set reformedClients = {select c : D.ZNewsClientT in M.components | c.maliciousness <= M.SUSCPICIOUS_THRESHOLD}; + set lbs = {select l : D.ZNewsLBT in M.components | M.size (l.throttled) > 0}; + for (D.ZNewsLBT l : lbs) { + set throttledClients = l.throttled; + for (D.ZNewsClientT c : reformedClients) { + throttledClients = Set.remove (throttledClients, c.deploymentLocation); + } + M.setThrottled (l, throttledClients); + } + } + effect { + forall lb : D.ZNewsLBT in M.components | forall ip : string in lb.throttled | forall c : D.ZNewsClientT in M.components | ((c.deploymentLocation == ip) -> (c.maliciousness > M.SUSCPICIOUS_THRESHOLD)); + } +} + +tactic forceReauthentication () { + condition { + true; + } + action { + for (ProxyT lb : M.components) { + M.forceReauthentication (lb); + } + } + effect { + true; + } +} + +tactic addCaptcha () { + condition { + exists lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; + } + action { + set lbs = {select l : D.ZNewsLBT in M.components | !l.captchaEnabled}; + for (D.ZNewsLBT l : lbs) { + M.setCaptchaEnabled (l, true); + } + } + effect { + forall lb:D.ZNewsLBT in M.components | lb.captchaEnabled; + } +} + +tactic removeCaptcha () { + condition { + exists lb:D.ZNewsLBT in M.components | lb.captchaEnabled; + } + action { + set lbs = {select l : D.ZNewsLBT in M.components | l.captchaEnabled}; + for (D.ZNewsLBT l : lbs) { + M.setCaptchaEnabled (l, false); + } + } + effect { + forall lb:D.ZNewsLBT in M.components | !lb.captchaEnabled; + } +} + + diff --git a/targets/znews-ss_2/stitch/newssiteTactics.s b/targets/znews-ss_2/stitch/newssiteTactics.s index 891770c68..41d6ad58a 100644 --- a/targets/znews-ss_2/stitch/newssiteTactics.s +++ b/targets/znews-ss_2/stitch/newssiteTactics.s @@ -1,118 +1,118 @@ -module newssite.tactics; - -import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T}; -import op "org.sa.rainbow.stitch.lib.*"; -import op "org.sa.rainbow.model.acme.znn.ZNN"; - - -/** - * Enlist n free servers into service pool. - * Utility: [v] R; [^] C; [<>] F - */ -tactic enlistServers (int n) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // there should be enough available server resources - ZNN.availableServices(M, T.ServerT) >= n; - } - action { - set servers = Set.randomSubset(ZNN.findServices(M, T.ServerT), n); - for (T.ServerT freeSvr : servers) { - M.enableServer (freeSvr, true); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Deactivate n servers from service pool into free pool. - * Utility: [^] R; [v] C; [<>] F - */ -tactic dischargeServers (int n) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there should be enough servers to discharge - Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; - } - action { - set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; - set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); - for (T.ServerT s : subLowUtilSvrs) { - M.enableServer (s, false); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Lowers fidelity by integral steps for percent of requests. - * Utility: [v] R; [v] C; [v] F - */ -tactic lowerFidelity (int step, float fracReq) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // exists server with fidelity to lower - exists s : T.ServerT in M.components | s.fidelity > step; - } - action { - // retrieve set of servers who still have enough fidelity grade to lower - set servers = { select s : T.ServerT in M.components | s.fidelity > step }; - for (T.ServerT s : servers) { - M.setFidelity(s, s.fidelity - step); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Raises fidelity by integral steps for percent of requests. - * Utility: [^] R; [^] C; [^] F - */ -tactic raiseFidelity (int step, float fracReq) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there exists some client with below low-threshold response time - exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - } - action { - // first find the lowest fidelity set - set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; -/* smarter way of doing things... - int lowestFidelity = M.MAX_FIDELITY_LEVEL; - for (T.ServerT s : servers) { - if (s.fidelity < lowestFidelity) { - lowestFidelity = s.fidelity; - } - } - // find only servers with this lowest fidelity setting, and raise fidelity - servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; -*/ - for (T.ServerT s : servers) { - M.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/* - T5) delayClients(set clients) - utility: [^] R; [v] C; [v] F - T6) blockClients(set clients) - utility: [^] R; [v] C; [v] F -*/ +module newssite.tactics; + +import model "ZNewsSys:Acme" { ZNewsSys as M, ZNewsFam as T}; +import op "org.sa.rainbow.stitch.lib.*"; +import op "org.sa.rainbow.model.acme.znn.ZNN"; + + +/** + * Enlist n free servers into service pool. + * Utility: [v] R; [^] C; [<>] F + */ +tactic enlistServers (int n) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // there should be enough available server resources + ZNN.availableServices(M, T.ServerT) >= n; + } + action { + set servers = Set.randomSubset(ZNN.findServices(M, T.ServerT), n); + for (T.ServerT freeSvr : servers) { + M.enableServer (freeSvr, true); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Deactivate n servers from service pool into free pool. + * Utility: [^] R; [v] C; [<>] F + */ +tactic dischargeServers (int n) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there should be enough servers to discharge + Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; + } + action { + set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; + set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); + for (T.ServerT s : subLowUtilSvrs) { + M.enableServer (s, false); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Lowers fidelity by integral steps for percent of requests. + * Utility: [v] R; [v] C; [v] F + */ +tactic lowerFidelity (int step, float fracReq) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // exists server with fidelity to lower + exists s : T.ServerT in M.components | s.fidelity > step; + } + action { + // retrieve set of servers who still have enough fidelity grade to lower + set servers = { select s : T.ServerT in M.components | s.fidelity > step }; + for (T.ServerT s : servers) { + M.setFidelity(s, s.fidelity - step); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Raises fidelity by integral steps for percent of requests. + * Utility: [^] R; [^] C; [^] F + */ +tactic raiseFidelity (int step, float fracReq) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there exists some client with below low-threshold response time + exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + } + action { + // first find the lowest fidelity set + set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; +/* smarter way of doing things... + int lowestFidelity = M.MAX_FIDELITY_LEVEL; + for (T.ServerT s : servers) { + if (s.fidelity < lowestFidelity) { + lowestFidelity = s.fidelity; + } + } + // find only servers with this lowest fidelity setting, and raise fidelity + servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; +*/ + for (T.ServerT s : servers) { + M.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/* + T5) delayClients(set clients) + utility: [^] R; [v] C; [v] F + T6) blockClients(set clients) + utility: [^] R; [v] C; [v] F +*/ diff --git a/targets/znews-ss_2/stitch/utilities.yml b/targets/znews-ss_2/stitch/utilities.yml index 057e48819..b1afa7129 100644 --- a/targets/znews-ss_2/stitch/utilities.yml +++ b/targets/znews-ss_2/stitch/utilities.yml @@ -1,151 +1,151 @@ -# Created October 22nd, 2013 (Javier Camara) -# -# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y -# is the utility in the range [0,1] -# -# History: -# - [JC 2013.10.22] Created file, defined utilities for Dos Attack Demo. -# - [JC 2013.11.1] Added user annoyance to the utility profile. -model: - name: ZNewsSys - type: Acme -utilities: - uR: - label: "Average Response Time" - mapping: "[EAvg]ClientT.experRespTime" - description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" - utility: - 0: 1.00 - 100: 1.00 - 200: 0.99 - 500: 0.90 - 1000: 0.75 - 1500: 0.50 - 2000: 0.25 - 4000: 0.00 - uC: - label: "Average Server Cost" - mapping: "[EXPR]size(/self/components:ServerT[isArchEnabled])" - description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers. Adapted to a 3-server configuration." - utility: - 0: 1.00 - 1: 0.90 - 2: 0.30 - 3: 0.10 - uM: - label: "Malicious Clients" - mapping: "[EXPR](2*size(/self/components:PotentiallyMaliciousT[maliciousness > self.MALICIOUS_THRESHOLD]))/(size(/self/components:PotentiallyMaliciousT)+1)*100" - description: "Percentage of malicious clients." - utility: - 0: 1.00 - 5: 1.00 - 20: 0.80 - 50: 0.40 - 70: 0.00 - uA: - label: "Average User Annoyance" - mapping: "[EAvg]ClientT.annoyance" - description: "Client experienced annoyance level, should be defined as an int property 'ClientT.annoyance' in the architecture, with a range 0-100" - utility: - 0: 1.00 - 100: 0.00 - -# Weighted utility preferences, each set should sum to 1. -# Three scenarios: -# 1.) Priority is given to eliminating malicious clients. -# 2.) Priority is given to optimizing good client experience (both serving them in a timely manner, and minimizing annoyance). -# 3.) Priority is given to keeping cost down. -# Note: Original Weight of uR is now split 50/50% among uR and uA in every scenario. -weights: - scenario 1: - uR: 0.15 - uM: 0.6 - uC: 0.1 - uA: 0.15 - scenario 2: - uR: 0.3 - uM: 0.3 - uC: 0.1 - uA: 0.3 - scenario 3: - uR: 0.2 - uM: 0.2 - uC: 0.4 - uA: 0.2 - -# Tactic quality attribute vectors -# -vectors: -# Utility: [^] R; [<>] M; [v] C; [<>]A -# assume each server will drop response time by 1000 ms and increase cost by 1 unit - enlistServers: - uR: -1000 - uM: 0 - uC: +1.00 - uA: 0 - -# Utility: [^] R; [<>] M; [^] C; [v]A -# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit, increases annoyance of users 5% for low-quality service - lowerFidelity: - uR: -500 - uM: 0 - uC: -0.10 - uA: +5 - -# Utility: [^] R; [^] M; [v] C; [v]A -# assume that adding the captcha reduces response time by 250 ms, reduces level of malicious users by 90%, increases cost 1/2 unit, and increases user annoyance by 50% - addCaptcha: - uR: -250 - uM: -90 - uC: +0.50 - uA: +50 - -# Utility: [^] R; [^] M; [<>] C; [v]A -# assume that forcing users to reauthenticate reduces response time by 250 ms, reduces level of malicious users by 70%, and increases user annoyance by 50% - forceReauthentication: - uR: -250 - uM: -70 - uC: 0.00 - uA: +50 - -# Utility: [^] R; [^] M; [<>] C; [v]A -# assume that blackholing potential attackers reduces response time by 1000 ms, reduces level of malicious users by 100%, and increases user annoyance by 100% - blackholeAttacker: - uR: -1000 - uM: -100 - uC: 0.00 - uA: +50 - -# Utility: [^] R; [<>] M; [<>] C; [v]A -# assume that throttling suspicious clients reduces response time by 500 ms, and increases user annoyance by 50% - throttleSuspicious: - uR: -500 -# uM may need to change if we decide to substitute % of malicious clients by % of malicious user throughput - uM: 0 - uC: 0.00 - uA: +25 - -# Utility: [^] R; [<>] M; [^] C; [^]A -# assume that removing the captcha reduces cost 1/2 unit, and reduces user annoyance by 50% - removeCaptcha: - uR: -500 - uM: 0 - uC: -0.50 - uA: -50 - -# Utility: [<>] R; [<>] M; [<>] C; [^]A -# assume that removing the captcha reduces user annoyance by 100% - unblackholeAttacker: - uR: 0 - uM: 0 - uC: 0.00 - uA: -100 - -# Utility: [<>] R; [<>] M; [<>] C; [^]A -# assume that unthrottling suspicious clients reduces user annoyance by 50% - unthrottle: - uR: 0 - uM: 0 - uC: 0.00 - uA: -50 - +# Created October 22nd, 2013 (Javier Camara) +# +# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y +# is the utility in the range [0,1] +# +# History: +# - [JC 2013.10.22] Created file, defined utilities for Dos Attack Demo. +# - [JC 2013.11.1] Added user annoyance to the utility profile. +model: + name: ZNewsSys + type: Acme +utilities: + uR: + label: "Average Response Time" + mapping: "[EAvg]ClientT.experRespTime" + description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" + utility: + 0: 1.00 + 100: 1.00 + 200: 0.99 + 500: 0.90 + 1000: 0.75 + 1500: 0.50 + 2000: 0.25 + 4000: 0.00 + uC: + label: "Average Server Cost" + mapping: "[EXPR]size(/self/components:ServerT[isArchEnabled])" + description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers. Adapted to a 3-server configuration." + utility: + 0: 1.00 + 1: 0.90 + 2: 0.30 + 3: 0.10 + uM: + label: "Malicious Clients" + mapping: "[EXPR](2*size(/self/components:PotentiallyMaliciousT[maliciousness > self.MALICIOUS_THRESHOLD]))/(size(/self/components:PotentiallyMaliciousT)+1)*100" + description: "Percentage of malicious clients." + utility: + 0: 1.00 + 5: 1.00 + 20: 0.80 + 50: 0.40 + 70: 0.00 + uA: + label: "Average User Annoyance" + mapping: "[EAvg]ClientT.annoyance" + description: "Client experienced annoyance level, should be defined as an int property 'ClientT.annoyance' in the architecture, with a range 0-100" + utility: + 0: 1.00 + 100: 0.00 + +# Weighted utility preferences, each set should sum to 1. +# Three scenarios: +# 1.) Priority is given to eliminating malicious clients. +# 2.) Priority is given to optimizing good client experience (both serving them in a timely manner, and minimizing annoyance). +# 3.) Priority is given to keeping cost down. +# Note: Original Weight of uR is now split 50/50% among uR and uA in every scenario. +weights: + scenario 1: + uR: 0.15 + uM: 0.6 + uC: 0.1 + uA: 0.15 + scenario 2: + uR: 0.3 + uM: 0.3 + uC: 0.1 + uA: 0.3 + scenario 3: + uR: 0.2 + uM: 0.2 + uC: 0.4 + uA: 0.2 + +# Tactic quality attribute vectors +# +vectors: +# Utility: [^] R; [<>] M; [v] C; [<>]A +# assume each server will drop response time by 1000 ms and increase cost by 1 unit + enlistServers: + uR: -1000 + uM: 0 + uC: +1.00 + uA: 0 + +# Utility: [^] R; [<>] M; [^] C; [v]A +# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit, increases annoyance of users 5% for low-quality service + lowerFidelity: + uR: -500 + uM: 0 + uC: -0.10 + uA: +5 + +# Utility: [^] R; [^] M; [v] C; [v]A +# assume that adding the captcha reduces response time by 250 ms, reduces level of malicious users by 90%, increases cost 1/2 unit, and increases user annoyance by 50% + addCaptcha: + uR: -250 + uM: -90 + uC: +0.50 + uA: +50 + +# Utility: [^] R; [^] M; [<>] C; [v]A +# assume that forcing users to reauthenticate reduces response time by 250 ms, reduces level of malicious users by 70%, and increases user annoyance by 50% + forceReauthentication: + uR: -250 + uM: -70 + uC: 0.00 + uA: +50 + +# Utility: [^] R; [^] M; [<>] C; [v]A +# assume that blackholing potential attackers reduces response time by 1000 ms, reduces level of malicious users by 100%, and increases user annoyance by 100% + blackholeAttacker: + uR: -1000 + uM: -100 + uC: 0.00 + uA: +50 + +# Utility: [^] R; [<>] M; [<>] C; [v]A +# assume that throttling suspicious clients reduces response time by 500 ms, and increases user annoyance by 50% + throttleSuspicious: + uR: -500 +# uM may need to change if we decide to substitute % of malicious clients by % of malicious user throughput + uM: 0 + uC: 0.00 + uA: +25 + +# Utility: [^] R; [<>] M; [^] C; [^]A +# assume that removing the captcha reduces cost 1/2 unit, and reduces user annoyance by 50% + removeCaptcha: + uR: -500 + uM: 0 + uC: -0.50 + uA: -50 + +# Utility: [<>] R; [<>] M; [<>] C; [^]A +# assume that removing the captcha reduces user annoyance by 100% + unblackholeAttacker: + uR: 0 + uM: 0 + uC: 0.00 + uA: -100 + +# Utility: [<>] R; [<>] M; [<>] C; [^]A +# assume that unthrottling suspicious clients reduces user annoyance by 50% + unthrottle: + uR: 0 + uM: 0 + uC: 0.00 + uA: -50 + diff --git a/targets/znews-ss_2/system/debpkgs.txt b/targets/znews-ss_2/system/debpkgs.txt index 96003b50f..544fb5fca 100644 --- a/targets/znews-ss_2/system/debpkgs.txt +++ b/targets/znews-ss_2/system/debpkgs.txt @@ -1,19 +1,19 @@ - -Debian packages required: -* sysstat - iostat, vmstat, etc. - -Nice packages: -* bc - calculator (under section "math") -* ganglia-monitor?? - for the Ganglia monitoring framework - -If compiling own Apache HTTPd 2.0.x, PHP, and MySQL... -Things to have in the system in order to compile/build: -- libncurses5 -- gcc/g++ 4.0 (3.3+ should work) -- pkg-config -- make/automake(1.8)/autoconf -- flex (lex generator) -- gettext -- openssl/libssl-dev -- zlib-dev -- libxml2/libxml2-dev + +Debian packages required: +* sysstat - iostat, vmstat, etc. + +Nice packages: +* bc - calculator (under section "math") +* ganglia-monitor?? - for the Ganglia monitoring framework + +If compiling own Apache HTTPd 2.0.x, PHP, and MySQL... +Things to have in the system in order to compile/build: +- libncurses5 +- gcc/g++ 4.0 (3.3+ should work) +- pkg-config +- make/automake(1.8)/autoconf +- flex (lex generator) +- gettext +- openssl/libssl-dev +- zlib-dev +- libxml2/libxml2-dev diff --git a/targets/znews-ss_2/system/effectors.yml b/targets/znews-ss_2/system/effectors.yml index 7fafab190..f96a2eb7c 100644 --- a/targets/znews-ss_2/system/effectors.yml +++ b/targets/znews-ss_2/system/effectors.yml @@ -1,226 +1,226 @@ -# Created January 30, 2007 (Shang-Wen Cheng) -# -# Effector descriptions. -# -# History: -# - [SWC 2007.01.30] Created file, populated ZNews effector descriptions. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# -vars: -# _effectors.commonPath: "${rainbow.path}/system/effectors" -# @ZNN_HOME will be replaced by the rainbow-install script -# _effectors.commonPath: "@ZNN_HOME/effectors" - _effectors.commonPath: "/home/znn/effectors" - - -effectors: - - blackhole: - location: "${customize.system.target.lb}" - command: setBlackholed ($) - type: script - scriptInfo: - path : "/home/znn/effectors/ip-block-mgmt" - argument: "block {0}" - - throttle: - location: "${customize.system.target.lb}" - command: setThrottled($) - type: script - scriptInfo: - path: "/home/znn/effectors/ip-throttle-mgmt" - argument: "throttle {0}" - - flushAuthentication-web0: - location: "${cusomize.system.target.web0}" - command: "${customize.system.target.lb}.forceReauthentication()" - type: script - scriptInfo: - path: "/home/znn/effectors/force-reauthentication" - - flushAuthentication-web1: - location: "${cusomize.system.target.web1}" - command: "${customize.system.target.lb}.forceReauthentication()" - type: script - scriptInfo: - path: "/home/znn/effectors/force-reauthentication" - - enableCaptcha-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-lb: - location: "${customize.system.target.lb}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - enableCaptcha-web2: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setCaptchaEnabled (true)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "on /home/znn/captcha.on" - - disableCaptcha-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-lb: - location: "${customize.system.target.lb}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - disableCaptcha-web2: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setCaptchaEnabled (false)" - type: script - scriptInfo: - path: "/home/znn/effectors/captcha" - argument: "off /home/znn/captcha.on" - - setFidelity-web0: - location: "${customize.system.target.web0}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web0.httpPort}" - - setFidelity-web1: - location: "${customize.system.target.web1}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web1.httpPort}" - - setFidelity-web2: - location: "${customize.system.target.web2}" - command: "${customize.system.target.lb}.setFidelity($)" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.sh" - argument: "{0} /tmp/znn-fidelity-${customize.system.target.web1.httpPort}" - - enable-server-web0: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web0}, true)" - type: script - scriptInfo: - path : /home/znn/effectors/enable-server - argument : "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - disable-server-web0: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web0}, false)" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" - - enable-server-web1: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web1}, true)" - type: script - scriptInfo: - path : /home/znn/effectors/enable-server - argument : "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - disable-server-web1: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web1}, false)" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" - - enable-server-web2: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web2}, true)" - type: script - scriptInfo: - path : /home/znn/effectors/enable-server - argument : "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - disable-server-web2: - location: "${customize.system.target.lb}" - command: "enableServer (${customize.system.target.web2}, false)" - type: script - scriptInfo: - path: /home/znn/effectors/enable-server - argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" - - -unused-effectors: - unblackhole: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path: "/home/znn/effectors/ip-block-mgmt" - argument: "unblock {clients}" - killDelegate2: -# Causes the designated RainbowDelegate to exit process -# Illustrates effector time-out as well as tests executor execution - location: "${customize.system.target.3}" - type: java - javaInfo: - class : org.sa.rainbow.translator.effectors.KillDelegateEffector - - # test from GUI with , SetFidelity, fidelity=<1|3|5> - - - activateServer1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/turnServer.pl" - argument: "-s on" - deactivateServer1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/turnServer.pl" - argument: "-s off" -# test from GUI with , RandomReject, frequency=<0..?> - randomReject1: - location: "${customize.system.target.2}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/setRandomReject.pl" - argument: "-r {frequency}" - killDelegate1: - location: "${customize.system.target.2}" - type: java - javaInfo: - class : org.sa.rainbow.translator.effectors.KillDelegateEffector +# Created January 30, 2007 (Shang-Wen Cheng) +# +# Effector descriptions. +# +# History: +# - [SWC 2007.01.30] Created file, populated ZNews effector descriptions. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# +vars: +# _effectors.commonPath: "${rainbow.path}/system/effectors" +# @ZNN_HOME will be replaced by the rainbow-install script +# _effectors.commonPath: "@ZNN_HOME/effectors" + _effectors.commonPath: "/home/znn/effectors" + + +effectors: + + blackhole: + location: "${customize.system.target.lb}" + command: setBlackholed ($) + type: script + scriptInfo: + path : "/home/znn/effectors/ip-block-mgmt" + argument: "block {0}" + + throttle: + location: "${customize.system.target.lb}" + command: setThrottled($) + type: script + scriptInfo: + path: "/home/znn/effectors/ip-throttle-mgmt" + argument: "throttle {0}" + + flushAuthentication-web0: + location: "${cusomize.system.target.web0}" + command: "${customize.system.target.lb}.forceReauthentication()" + type: script + scriptInfo: + path: "/home/znn/effectors/force-reauthentication" + + flushAuthentication-web1: + location: "${cusomize.system.target.web1}" + command: "${customize.system.target.lb}.forceReauthentication()" + type: script + scriptInfo: + path: "/home/znn/effectors/force-reauthentication" + + enableCaptcha-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-lb: + location: "${customize.system.target.lb}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + enableCaptcha-web2: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setCaptchaEnabled (true)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "on /home/znn/captcha.on" + + disableCaptcha-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-lb: + location: "${customize.system.target.lb}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + disableCaptcha-web2: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setCaptchaEnabled (false)" + type: script + scriptInfo: + path: "/home/znn/effectors/captcha" + argument: "off /home/znn/captcha.on" + + setFidelity-web0: + location: "${customize.system.target.web0}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web0.httpPort}" + + setFidelity-web1: + location: "${customize.system.target.web1}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web1.httpPort}" + + setFidelity-web2: + location: "${customize.system.target.web2}" + command: "${customize.system.target.lb}.setFidelity($)" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.sh" + argument: "{0} /tmp/znn-fidelity-${customize.system.target.web1.httpPort}" + + enable-server-web0: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web0}, true)" + type: script + scriptInfo: + path : /home/znn/effectors/enable-server + argument : "on ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + disable-server-web0: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web0}, false)" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web0}:${customize.system.target.web0.httpPort}" + + enable-server-web1: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web1}, true)" + type: script + scriptInfo: + path : /home/znn/effectors/enable-server + argument : "on ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + disable-server-web1: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web1}, false)" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web1}:${customize.system.target.web1.httpPort}" + + enable-server-web2: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web2}, true)" + type: script + scriptInfo: + path : /home/znn/effectors/enable-server + argument : "on ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + disable-server-web2: + location: "${customize.system.target.lb}" + command: "enableServer (${customize.system.target.web2}, false)" + type: script + scriptInfo: + path: /home/znn/effectors/enable-server + argument: "off ${customize.system.target.web2}:${customize.system.target.web2.httpPort}" + + +unused-effectors: + unblackhole: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path: "/home/znn/effectors/ip-block-mgmt" + argument: "unblock {clients}" + killDelegate2: +# Causes the designated RainbowDelegate to exit process +# Illustrates effector time-out as well as tests executor execution + location: "${customize.system.target.3}" + type: java + javaInfo: + class : org.sa.rainbow.translator.effectors.KillDelegateEffector + + # test from GUI with , SetFidelity, fidelity=<1|3|5> + + + activateServer1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/turnServer.pl" + argument: "-s on" + deactivateServer1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/turnServer.pl" + argument: "-s off" +# test from GUI with , RandomReject, frequency=<0..?> + randomReject1: + location: "${customize.system.target.2}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/setRandomReject.pl" + argument: "-r {frequency}" + killDelegate1: + location: "${customize.system.target.2}" + type: java + javaInfo: + class : org.sa.rainbow.translator.effectors.KillDelegateEffector diff --git a/targets/znews-ss_2/system/effectors/changeFidelity.pl b/targets/znews-ss_2/system/effectors/changeFidelity.pl index a24df7cef..80123eba4 100644 --- a/targets/znews-ss_2/system/effectors/changeFidelity.pl +++ b/targets/znews-ss_2/system/effectors/changeFidelity.pl @@ -1,83 +1,83 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -my $isCygwin = 0; -my $uname; -if ( -e "/bin/uname" ) { - $uname = `/bin/uname`; -} elsif ( -e "/usr/bin/uname" ) { - $uname = `/usr/bin/uname`; -} else { - $uname = "UNKNOWN"; -} -if ($uname =~ /CYGWIN/i) { - $isCygwin = 1; -} - -chomp(my $SCRIPT_DIR = `/usr/bin/dirname "$0"`); -my $APACHE_CONF_DIR = ($isCygwin) ? - "/cygdrive/c/server/Apache2/conf" : - "/etc/apache2"; -my $APACHE_CONF_FILE = ($isCygwin) ? - "httpd.conf" : - "apache2.conf"; -my $APACHE_SITE_DIR = "$APACHE_CONF_DIR/sites-available"; -my $APACHE_SITE_FILE = "z.com"; -my $SOURCE_CONF_DIR = ($isCygwin) ? - "$SCRIPT_DIR/fidelity.conf/cygwin" : - "$SCRIPT_DIR/fidelity.conf/oracle"; - -sub usage() { - print STDERR << "EOF"; - -This effector program changes the webserver fidelity level (1,3,5). - - usage: $0 [option] -l level - - -h : this (help) message - -l level : the new fidelity setting, should be 1, 3, or 5 (0 for original) - -EOF - exit; -} - -# get options -my %opts; -getopts('hl:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{l})); - -my $level = $opts{l}; -usage() if ($level != 0 && $level != 1 && $level != 3 && $level != 5); - -my $fExt = "-f"; -if ($level == 0) { - if ($isCygwin) { - $fExt = ".default"; - } else { - $fExt .= "5"; - } -} else { - $fExt .= $level; -} - -if ($isCygwin) { - - print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; - print `/usr/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; - print "\nGracefully restarting Apache..."; - print `/cygdrive/c/server/Apache2/bin/Apache.exe -w -n "Apache2" -k restart`; - print "\nDone."; - -} else { - - print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; - print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; - print "\nSwapping site to level $level..."; - print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_SITE_FILE$fExt $APACHE_SITE_DIR/$APACHE_SITE_FILE`; - print "\nGracefully restarting Apache..."; - print `/etc/init.d/apache2 reload`; - print "\nDone."; - -} +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +my $isCygwin = 0; +my $uname; +if ( -e "/bin/uname" ) { + $uname = `/bin/uname`; +} elsif ( -e "/usr/bin/uname" ) { + $uname = `/usr/bin/uname`; +} else { + $uname = "UNKNOWN"; +} +if ($uname =~ /CYGWIN/i) { + $isCygwin = 1; +} + +chomp(my $SCRIPT_DIR = `/usr/bin/dirname "$0"`); +my $APACHE_CONF_DIR = ($isCygwin) ? + "/cygdrive/c/server/Apache2/conf" : + "/etc/apache2"; +my $APACHE_CONF_FILE = ($isCygwin) ? + "httpd.conf" : + "apache2.conf"; +my $APACHE_SITE_DIR = "$APACHE_CONF_DIR/sites-available"; +my $APACHE_SITE_FILE = "z.com"; +my $SOURCE_CONF_DIR = ($isCygwin) ? + "$SCRIPT_DIR/fidelity.conf/cygwin" : + "$SCRIPT_DIR/fidelity.conf/oracle"; + +sub usage() { + print STDERR << "EOF"; + +This effector program changes the webserver fidelity level (1,3,5). + + usage: $0 [option] -l level + + -h : this (help) message + -l level : the new fidelity setting, should be 1, 3, or 5 (0 for original) + +EOF + exit; +} + +# get options +my %opts; +getopts('hl:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{l})); + +my $level = $opts{l}; +usage() if ($level != 0 && $level != 1 && $level != 3 && $level != 5); + +my $fExt = "-f"; +if ($level == 0) { + if ($isCygwin) { + $fExt = ".default"; + } else { + $fExt .= "5"; + } +} else { + $fExt .= $level; +} + +if ($isCygwin) { + + print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; + print `/usr/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; + print "\nGracefully restarting Apache..."; + print `/cygdrive/c/server/Apache2/bin/Apache.exe -w -n "Apache2" -k restart`; + print "\nDone."; + +} else { + + print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; + print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; + print "\nSwapping site to level $level..."; + print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_SITE_FILE$fExt $APACHE_SITE_DIR/$APACHE_SITE_FILE`; + print "\nGracefully restarting Apache..."; + print `/etc/init.d/apache2 reload`; + print "\nDone."; + +} diff --git a/targets/znews-ss_2/system/effectors/dummyBlackhole.pl b/targets/znews-ss_2/system/effectors/dummyBlackhole.pl index 0a9e46e42..81ed3be30 100644 --- a/targets/znews-ss_2/system/effectors/dummyBlackhole.pl +++ b/targets/znews-ss_2/system/effectors/dummyBlackhole.pl @@ -1,24 +1,24 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -sub usage () { - print STDERR << "EOF"; - -This effector program is a dummy blackholer. - - usege: $0 [option] -i IP - - -i IP: the IP address that should be blackholed - -EOF - exit; -} - -#get options -my %opts; -getopts ('i:',\%opts) or usage (); -usage () if (!defined($opts{i})); -my $IP = $opts{i} -print "Blackholing $IP...\n"; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +sub usage () { + print STDERR << "EOF"; + +This effector program is a dummy blackholer. + + usege: $0 [option] -i IP + + -i IP: the IP address that should be blackholed + +EOF + exit; +} + +#get options +my %opts; +getopts ('i:',\%opts) or usage (); +usage () if (!defined($opts{i})); +my $IP = $opts{i} +print "Blackholing $IP...\n"; diff --git a/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf b/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf index 4adbba299..5b13550db 100644 --- a/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf +++ b/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf @@ -1,967 +1,967 @@ -### Fidelity-5 Conf file -## - full featured -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -AddType application/x-httpd-php .php - -# configure the path to php.ini -PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.php index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -AddType text/html .shtml -AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-5 Conf file +## - full featured +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +AddType application/x-httpd-php .php + +# configure the path to php.ini +PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.php index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +AddType text/html .shtml +AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 b/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 index 95dd86268..6907bc89d 100644 --- a/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 +++ b/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 @@ -1,974 +1,974 @@ -### Fidelity-1 Conf file -## - reduced timeout from 300 to 30 sec -## - reduced max keep alive reqs from 100 to 10 -## - threads per child reduced from 250 to 10 -## - set an upper limit of max requests per child to 5 -## - excluded user dir function -## - excluded modules dav, imap, rewrite, userdir -## - reduced Directory Options to indexes & symlink only -## - reduced AllowOverride to None -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 30 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 10 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 10 -MaxRequestsPerChild 5 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -#LoadModule cgi_module modules/mod_cgi.so -#LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -#LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -#LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -#LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -#AddType application/x-httpd-php .php - -# configure the path to php.ini -#PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www1" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options Indexes SymLinksIfOwnerMatch - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride None - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -#UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - -# -# Options Indexes -# AllowOverride None -# Order allow,deny -# Allow from all -# -# -# SetHandler type-map -# -# -# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 -# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 -# - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# -# -# AllowOverride None -# Options None -# Order allow,deny -# Allow from all -# - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -#AddType application/x-compress .Z -#AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# -# -# Include conf/ssl.conf -# - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-1 Conf file +## - reduced timeout from 300 to 30 sec +## - reduced max keep alive reqs from 100 to 10 +## - threads per child reduced from 250 to 10 +## - set an upper limit of max requests per child to 5 +## - excluded user dir function +## - excluded modules dav, imap, rewrite, userdir +## - reduced Directory Options to indexes & symlink only +## - reduced AllowOverride to None +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 30 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 10 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 10 +MaxRequestsPerChild 5 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule cgi_module modules/mod_cgi.so +#LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +#LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +#LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +#LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +#AddType application/x-httpd-php .php + +# configure the path to php.ini +#PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www1" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options Indexes SymLinksIfOwnerMatch + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride None + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +#UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + +# +# Options Indexes +# AllowOverride None +# Order allow,deny +# Allow from all +# +# +# SetHandler type-map +# +# +# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 +# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 +# + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +# +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +# + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +#AddType application/x-compress .Z +#AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# +# +# Include conf/ssl.conf +# + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 b/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 index 7fd0f402b..eaab99348 100644 --- a/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 +++ b/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 @@ -1,971 +1,971 @@ -### Fidelity-3 Conf file -## - excluded CGI handling -## - excluded PHP module -## - excluded SSI -## - excluded compression type -## - excluded server manual -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -#LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -#AddType application/x-httpd-php .php - -# configure the path to php.ini -#PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www3" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - -# -# Options Indexes -# AllowOverride None -# Order allow,deny -# Allow from all -# -# -# SetHandler type-map -# -# -# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 -# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 -# - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# -# -# AllowOverride None -# Options None -# Order allow,deny -# Allow from all -# - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -#AddType application/x-compress .Z -#AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-3 Conf file +## - excluded CGI handling +## - excluded PHP module +## - excluded SSI +## - excluded compression type +## - excluded server manual +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +#AddType application/x-httpd-php .php + +# configure the path to php.ini +#PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www3" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + +# +# Options Indexes +# AllowOverride None +# Order allow,deny +# Allow from all +# +# +# SetHandler type-map +# +# +# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 +# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 +# + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +# +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +# + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +#AddType application/x-compress .Z +#AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 b/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 index 4adbba299..5b13550db 100644 --- a/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 +++ b/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 @@ -1,967 +1,967 @@ -### Fidelity-5 Conf file -## - full featured -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -AddType application/x-httpd-php .php - -# configure the path to php.ini -PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.php index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -AddType text/html .shtml -AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-5 Conf file +## - full featured +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +AddType application/x-httpd-php .php + +# configure the path to php.ini +PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.php index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +AddType text/html .shtml +AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf.default b/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf.default index 20dd3c11d..ff8505b79 100644 --- a/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf.default +++ b/targets/znews-ss_2/system/effectors/fidelity.conf/cygwin/httpd.conf.default @@ -1,952 +1,952 @@ -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -#LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -#LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin admin@able.cs.cmu.edu - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/Apache2/htdocs" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options Indexes FollowSymLinks - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride None - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +#LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +#LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin admin@able.cs.cmu.edu + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/Apache2/htdocs" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options Indexes FollowSymLinks + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride None + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# diff --git a/targets/znews-ss_2/system/effectors/setRandomReject.pl b/targets/znews-ss_2/system/effectors/setRandomReject.pl index 5d6b91697..58f70c7b0 100644 --- a/targets/znews-ss_2/system/effectors/setRandomReject.pl +++ b/targets/znews-ss_2/system/effectors/setRandomReject.pl @@ -1,35 +1,35 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -my $APACHE_WWW_DIR = "/home/owen/project/rainbow/delegate/targets/znews1-d/system/webpages/www5"; - -sub usage() { - print STDERR << "EOF"; - -This effector program affects random reject frequency (0 or mod over seconds). - - usage: $0 [option] -r [0|modval] - - -h : this (help) message - -r 0|mod : the modulus value for request rejection (0 for NO reject) - -EOF - exit; -} - -# get options -my %opts; -getopts('hr:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{r})); - -my $modVal = $opts{r}; -usage() if ($modVal < 0 && $modVal > 10); - -my $file = "reject.mod"; -print "Setting reject modulus value to $modVal..."; -open(FOUT, ">$APACHE_WWW_DIR/$file"); -print FOUT $modVal; -close(FOUT); -print "\nDone."; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +my $APACHE_WWW_DIR = "/home/owen/project/rainbow/delegate/targets/znews1-d/system/webpages/www5"; + +sub usage() { + print STDERR << "EOF"; + +This effector program affects random reject frequency (0 or mod over seconds). + + usage: $0 [option] -r [0|modval] + + -h : this (help) message + -r 0|mod : the modulus value for request rejection (0 for NO reject) + +EOF + exit; +} + +# get options +my %opts; +getopts('hr:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{r})); + +my $modVal = $opts{r}; +usage() if ($modVal < 0 && $modVal > 10); + +my $file = "reject.mod"; +print "Setting reject modulus value to $modVal..."; +open(FOUT, ">$APACHE_WWW_DIR/$file"); +print FOUT $modVal; +close(FOUT); +print "\nDone."; diff --git a/targets/znews-ss_2/system/effectors/turnServer.pl b/targets/znews-ss_2/system/effectors/turnServer.pl index 8cc10dd33..9d46f681e 100644 --- a/targets/znews-ss_2/system/effectors/turnServer.pl +++ b/targets/znews-ss_2/system/effectors/turnServer.pl @@ -1,36 +1,36 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; -use IO::Handle; - -sub usage() { - print STDERR << "EOF"; - -This effector program turns the webserver on or off - - usage: $0 [option] -s on|off - - -h : this (help) message - -s on|off : on or off to start/stop webserver - -EOF - exit; -} - -# get options -my %opts; -getopts('hs:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{s})); - -my $switch = $opts{s}; -usage() if ($switch ne "on" && $switch ne "off"); - -if ($switch eq "on") { - print "\nStarting Apache..."; - print `/etc/init.d/apache2 start`; -} else { - print "\nStopping Apache..."; - print `/etc/init.d/apache2 stop`; -} -print "\nDone."; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; +use IO::Handle; + +sub usage() { + print STDERR << "EOF"; + +This effector program turns the webserver on or off + + usage: $0 [option] -s on|off + + -h : this (help) message + -s on|off : on or off to start/stop webserver + +EOF + exit; +} + +# get options +my %opts; +getopts('hs:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{s})); + +my $switch = $opts{s}; +usage() if ($switch ne "on" && $switch ne "off"); + +if ($switch eq "on") { + print "\nStarting Apache..."; + print `/etc/init.d/apache2 start`; +} else { + print "\nStopping Apache..."; + print `/etc/init.d/apache2 stop`; +} +print "\nDone."; diff --git a/targets/znews-ss_2/system/probes.yml b/targets/znews-ss_2/system/probes.yml index 4e3a55c41..d9deb28a1 100644 --- a/targets/znews-ss_2/system/probes.yml +++ b/targets/znews-ss_2/system/probes.yml @@ -1,165 +1,165 @@ -# -# Probe descriptions. -# -# History: -# - [SWC 2007.03.18] Created file, populated new probe descriptions. -# - [SWC 2007.04.09] Added array of host names as arguments to PingRTTProbe. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# - [SWC 2007.04.11] Added ClientProxyProbe -# -vars: -# _probes.commonPath: "${rainbow.path}/system/probes" - _probes.commonPath: /home/znn/znn-benchmark/system/probes - -probes: - - DummyMaliciousnessProbe: - alias: dummymaliciousness - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.DummyProbe - period: 2000 - args.length: 1 - args.0: /home/znn/maliciousness - - BlackholeProbe: - alias: blackhole - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.BlackholeProbe - period: 2000 - args.length: 1 - args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/blocked.conf - - ThrottleProbe: - alias: throttle - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ThrottleProbe - period: 2000 - args.length: 1 - args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/security.conf - - CaptchaProbe: - alias: captchaprobe - location: "${customize.system.target.lb}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.CaptchaProbe - period: 2000 - args.length: 1 - args.0: /tmp/znn-wrapper-1080 -# args.0: /home/znn/lb0/sw/httpd-2.4.2/conf/captcha.on - - AuthenticationProbe: - alias: authenticationprobe - location: "${customize.system.target.web0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.AuthenticationProbe - period: 2000 - args.length: 1 - args.0: /tmp/znn-wrapper-auth-1080 - - ClientProxyProbe0: - alias: clientproxy - location: "${customize.system.target.master}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe - period: 2000 - args.length: 1 - args.0: "http://${customize.system.target.lb}:1081/news.php" - - ClientProxyProbe1: - alias: clientproxy - location: "${customize.system.target.bad}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe - period: 2000 - args.length: 1 - args.0: "http://${customize.system.target.lb}:1081/" - - FidelityProbe1: - alias: fidelity - location: "${customize.system.target.web0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.FidelityProbe - period: 2000 - args.length: 1 - args.0: "/tmp/znn-fidelity-${customize.system.target.web0.httpPort}" - -unused-probes: - ApacheTopProbe1: - alias: apachetop - location: "${customize.system.target.web0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/apachetopProbe.pl" - argument: "-k -s" - DiskIOProbe1: - alias: diskio - location: "${customize.system.target.web0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/diskIOProbe.pl" - argument: "-k -s" - PingRTTProbe1: - alias: pingrtt - location: "${customize.system.target.web0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znn.probes.PingRTTProbe -# sample period in milliseconds - period: 1500 - args.length: 1 - args.0: "${rainbow.master.location.host}" -# args.1: "${customize.system.target.2}" - LoadProbe1: - alias: load - location: "${customize.system.target.web0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" - NullProbe0: - alias: NIL - location: "${customize.system.target.0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.probes.NullProbe - ApacheTopProbe0: - alias: apachetop - location: "${customize.system.target.0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/apachetopProbe.pl" - argument: "-k -s" - LoadProbe0: - alias: load - location: "${customize.system.target.0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" - PingRTTProbe3: - alias: pingrtt - location: "${customize.system.target.3}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znews.probes.PingRTTProbe - period: 1500 - args.length: 1 - args.0: "${rainbow.master.location.host}" - LoadProbe3: - alias: load - location: "${customize.system.target.3}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" +# +# Probe descriptions. +# +# History: +# - [SWC 2007.03.18] Created file, populated new probe descriptions. +# - [SWC 2007.04.09] Added array of host names as arguments to PingRTTProbe. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# - [SWC 2007.04.11] Added ClientProxyProbe +# +vars: +# _probes.commonPath: "${rainbow.path}/system/probes" + _probes.commonPath: /home/znn/znn-benchmark/system/probes + +probes: + + DummyMaliciousnessProbe: + alias: dummymaliciousness + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.DummyProbe + period: 2000 + args.length: 1 + args.0: /home/znn/maliciousness + + BlackholeProbe: + alias: blackhole + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.BlackholeProbe + period: 2000 + args.length: 1 + args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/blocked.conf + + ThrottleProbe: + alias: throttle + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ThrottleProbe + period: 2000 + args.length: 1 + args.0: /home/znn/sw-bin/znn_httpd_lb-2.4.2/conf/security.conf + + CaptchaProbe: + alias: captchaprobe + location: "${customize.system.target.lb}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.CaptchaProbe + period: 2000 + args.length: 1 + args.0: /tmp/znn-wrapper-1080 +# args.0: /home/znn/lb0/sw/httpd-2.4.2/conf/captcha.on + + AuthenticationProbe: + alias: authenticationprobe + location: "${customize.system.target.web0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.AuthenticationProbe + period: 2000 + args.length: 1 + args.0: /tmp/znn-wrapper-auth-1080 + + ClientProxyProbe0: + alias: clientproxy + location: "${customize.system.target.master}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe + period: 2000 + args.length: 1 + args.0: "http://${customize.system.target.lb}:1081/news.php" + + ClientProxyProbe1: + alias: clientproxy + location: "${customize.system.target.bad}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.ClientProxyProbe + period: 2000 + args.length: 1 + args.0: "http://${customize.system.target.lb}:1081/" + + FidelityProbe1: + alias: fidelity + location: "${customize.system.target.web0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.FidelityProbe + period: 2000 + args.length: 1 + args.0: "/tmp/znn-fidelity-${customize.system.target.web0.httpPort}" + +unused-probes: + ApacheTopProbe1: + alias: apachetop + location: "${customize.system.target.web0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/apachetopProbe.pl" + argument: "-k -s" + DiskIOProbe1: + alias: diskio + location: "${customize.system.target.web0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/diskIOProbe.pl" + argument: "-k -s" + PingRTTProbe1: + alias: pingrtt + location: "${customize.system.target.web0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znn.probes.PingRTTProbe +# sample period in milliseconds + period: 1500 + args.length: 1 + args.0: "${rainbow.master.location.host}" +# args.1: "${customize.system.target.2}" + LoadProbe1: + alias: load + location: "${customize.system.target.web0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" + NullProbe0: + alias: NIL + location: "${customize.system.target.0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.probes.NullProbe + ApacheTopProbe0: + alias: apachetop + location: "${customize.system.target.0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/apachetopProbe.pl" + argument: "-k -s" + LoadProbe0: + alias: load + location: "${customize.system.target.0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" + PingRTTProbe3: + alias: pingrtt + location: "${customize.system.target.3}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znews.probes.PingRTTProbe + period: 1500 + args.length: 1 + args.0: "${rainbow.master.location.host}" + LoadProbe3: + alias: load + location: "${customize.system.target.3}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" diff --git a/targets/znews-ss_2/system/probes/apachetopProbe.pl b/targets/znews-ss_2/system/probes/apachetopProbe.pl index 79ba71042..9f8989f04 100644 --- a/targets/znews-ss_2/system/probes/apachetopProbe.pl +++ b/targets/znews-ss_2/system/probes/apachetopProbe.pl @@ -1,90 +1,90 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 5000; # 5 sec delay -my $APACHETOP_LOG = "../../log/apachetop.log"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -if (! -e $APACHETOP_LOG) { # create empty file - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line,$sendBeacon); -while (!shouldTerminate($sock)) { - $sendBeacon = 1; - while ($line = ) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - $sendBeacon = 0; - } - if ($sendBeacon) { # announce something to be alive - announce($ALIAS, "\n", [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 5000; # 5 sec delay +my $APACHETOP_LOG = "../../log/apachetop.log"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +if (! -e $APACHETOP_LOG) { # create empty file + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line,$sendBeacon); +while (!shouldTerminate($sock)) { + $sendBeacon = 1; + while ($line = ) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + $sendBeacon = 0; + } + if ($sendBeacon) { # announce something to be alive + announce($ALIAS, "\n", [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss_2/system/probes/cygwin/apachetopProbe-single.pl b/targets/znews-ss_2/system/probes/cygwin/apachetopProbe-single.pl index 966358241..762a0686a 100644 --- a/targets/znews-ss_2/system/probes/cygwin/apachetopProbe-single.pl +++ b/targets/znews-ss_2/system/probes/cygwin/apachetopProbe-single.pl @@ -1,98 +1,98 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 10; -my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; -my $APACHETOP_LOG = "apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# fork to the apachetop program -my $pid = fork(); -if ($pid == 0) { ### child process - if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); - } - exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; - exit(0); -} - -### parent process - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line); -while (!shouldTerminate($sock)) { - $line = ; - if (defined($line)) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 10; +my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; +my $APACHETOP_LOG = "apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# fork to the apachetop program +my $pid = fork(); +if ($pid == 0) { ### child process + if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); + } + exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; + exit(0); +} + +### parent process + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line); +while (!shouldTerminate($sock)) { + $line = ; + if (defined($line)) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss_2/system/probes/cygwin/apachetopProbe.pl b/targets/znews-ss_2/system/probes/cygwin/apachetopProbe.pl index 79ba71042..9f8989f04 100644 --- a/targets/znews-ss_2/system/probes/cygwin/apachetopProbe.pl +++ b/targets/znews-ss_2/system/probes/cygwin/apachetopProbe.pl @@ -1,90 +1,90 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 5000; # 5 sec delay -my $APACHETOP_LOG = "../../log/apachetop.log"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -if (! -e $APACHETOP_LOG) { # create empty file - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line,$sendBeacon); -while (!shouldTerminate($sock)) { - $sendBeacon = 1; - while ($line = ) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - $sendBeacon = 0; - } - if ($sendBeacon) { # announce something to be alive - announce($ALIAS, "\n", [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 5000; # 5 sec delay +my $APACHETOP_LOG = "../../log/apachetop.log"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +if (! -e $APACHETOP_LOG) { # create empty file + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line,$sendBeacon); +while (!shouldTerminate($sock)) { + $sendBeacon = 1; + while ($line = ) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + $sendBeacon = 0; + } + if ($sendBeacon) { # announce something to be alive + announce($ALIAS, "\n", [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss_2/system/probes/cygwin/fidelityProbe.pl b/targets/znews-ss_2/system/probes/cygwin/fidelityProbe.pl index 21dc6255d..abb411a4d 100644 --- a/targets/znews-ss_2/system/probes/cygwin/fidelityProbe.pl +++ b/targets/znews-ss_2/system/probes/cygwin/fidelityProbe.pl @@ -1,100 +1,100 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "fidelity"; -my $NAME = "FidelityProbe"; -my $DELAY = 1000; -my $REPEATEVERY = 5; -my $APACHE_CONF_DIR = "/cygdrive/c/server/Apache2/conf"; -my $APACHE_CONF_FILE = "httpd.conf"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current server fidelity (1,3,5) to Probe Relay file/socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic server fidelity info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub determineFidelity () { - my $fid = 0; - - open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); - my $firstLine = ; # read the first line - if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { - $fid = $1; - } - close(FIN); - - return $fid; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -my $repeatCnt = $REPEATEVERY; -my $savedFidelity = 0; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # compute new fidelity status - my $fidelity = determineFidelity(); - if ($fidelity != $savedFidelity || $repeatCnt == 0) { - $savedFidelity = $fidelity; #store new fidelity - my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - - if ($repeatCnt == 0) { - $repeatCnt = $REPEATEVERY; - } - } else { - $repeatCnt--; - } -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "fidelity"; +my $NAME = "FidelityProbe"; +my $DELAY = 1000; +my $REPEATEVERY = 5; +my $APACHE_CONF_DIR = "/cygdrive/c/server/Apache2/conf"; +my $APACHE_CONF_FILE = "httpd.conf"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current server fidelity (1,3,5) to Probe Relay file/socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic server fidelity info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub determineFidelity () { + my $fid = 0; + + open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); + my $firstLine = ; # read the first line + if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { + $fid = $1; + } + close(FIN); + + return $fid; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +my $repeatCnt = $REPEATEVERY; +my $savedFidelity = 0; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # compute new fidelity status + my $fidelity = determineFidelity(); + if ($fidelity != $savedFidelity || $repeatCnt == 0) { + $savedFidelity = $fidelity; #store new fidelity + my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + + if ($repeatCnt == 0) { + $repeatCnt = $REPEATEVERY; + } + } else { + $repeatCnt--; + } +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss_2/system/probes/cygwin/loadProbe.pl b/targets/znews-ss_2/system/probes/cygwin/loadProbe.pl index b50e32b17..0ff60debb 100644 --- a/targets/znews-ss_2/system/probes/cygwin/loadProbe.pl +++ b/targets/znews-ss_2/system/probes/cygwin/loadProbe.pl @@ -1,98 +1,98 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "load"; -my $NAME = "LoadProbe"; -my $DELAY = 1000; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current CPU usage to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic CPU usage info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub cpuTime () { - my ($user, $nice, $sys, $idle); - - local(*FIN); - open(FIN, ") { - chomp; - if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/o) { - ($user, $nice, $sys, $idle) = ($1, $2, $3, $4); - last; - } - } - close(FIN); - return ($user, $nice, $sys, $idle); -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# save current cpu ticks -my($userSv, $niceSv, $sysSv, $idleSv) = cpuTime(); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # retrieve new cpu ticks - my ($userN, $niceN, $sysN, $idleN) = cpuTime(); - # compute delta cpu ticks - my ($user, $nice, $sys, $idle) = - ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv); - # store the new saved ticks - ($userSv, $niceSv, $sysSv, $idleSv) = ($userN, $niceN, $sysN, $idleN); - my $total = $user + $nice + $sys + $idle; - my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), - $user/$total, $nice/$total, $sys/$total, $idle/$total); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "load"; +my $NAME = "LoadProbe"; +my $DELAY = 1000; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current CPU usage to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic CPU usage info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub cpuTime () { + my ($user, $nice, $sys, $idle); + + local(*FIN); + open(FIN, ") { + chomp; + if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/o) { + ($user, $nice, $sys, $idle) = ($1, $2, $3, $4); + last; + } + } + close(FIN); + return ($user, $nice, $sys, $idle); +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# save current cpu ticks +my($userSv, $niceSv, $sysSv, $idleSv) = cpuTime(); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # retrieve new cpu ticks + my ($userN, $niceN, $sysN, $idleN) = cpuTime(); + # compute delta cpu ticks + my ($user, $nice, $sys, $idle) = + ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv); + # store the new saved ticks + ($userSv, $niceSv, $sysSv, $idleSv) = ($userN, $niceN, $sysN, $idleN); + my $total = $user + $nice + $sys + $idle; + my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), + $user/$total, $nice/$total, $sys/$total, $idle/$total); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss_2/system/probes/cygwin/probe-cygwin.bat b/targets/znews-ss_2/system/probes/cygwin/probe-cygwin.bat index 4f192949d..b912671dd 100644 --- a/targets/znews-ss_2/system/probes/cygwin/probe-cygwin.bat +++ b/targets/znews-ss_2/system/probes/cygwin/probe-cygwin.bat @@ -1,8 +1,8 @@ -@echo off - -C: -chdir C:\server\cygwin\bin -set DEMO_MODE=%1 -set DEMO_TITLE=%2 - -bash --login -i +@echo off + +C: +chdir C:\server\cygwin\bin +set DEMO_MODE=%1 +set DEMO_TITLE=%2 + +bash --login -i diff --git a/targets/znews-ss_2/system/probes/cygwin/runApachetop.pl b/targets/znews-ss_2/system/probes/cygwin/runApachetop.pl index aca341ab9..0970d810f 100644 --- a/targets/znews-ss_2/system/probes/cygwin/runApachetop.pl +++ b/targets/znews-ss_2/system/probes/cygwin/runApachetop.pl @@ -1,16 +1,16 @@ -#!/usr/bin/perl -w - -use strict; - -############################# -my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; -my $APACHETOP_LOG = "/cygdrive/c/server/rainbow/oracle/targets/znews1/log/apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - -if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; +#!/usr/bin/perl -w + +use strict; + +############################# +my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; +my $APACHETOP_LOG = "/cygdrive/c/server/rainbow/oracle/targets/znews1/log/apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + +if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; diff --git a/targets/znews-ss_2/system/probes/diskIOProbe-diskstats.pl b/targets/znews-ss_2/system/probes/diskIOProbe-diskstats.pl index e4a1e3ba5..a40e58938 100644 --- a/targets/znews-ss_2/system/probes/diskIOProbe-diskstats.pl +++ b/targets/znews-ss_2/system/probes/diskIOProbe-diskstats.pl @@ -1,125 +1,125 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "diskio"; -my $NAME = "DiskIOProbe"; -my $DELAY = 4000; -############################# - -# Determine diskstats format -my $statfile; -my $uname = `uname -a`; -if ($uname =~ /Linux\s+(.+?)\s+(\d+[.]\d+)/) { - if ($2 eq "2.6") { - $statfile = "/proc/diskstats"; -# } elsif ($2 <= 2.5) { -# $statfile = "/proc/partitions"; # granularity of info more coarse - } -} else { - print "Linux version unsupported for diskstat access! Unable to continue probing\n"; - exit -1; -} - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current accumulated Disk IO to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic Disk IO info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub diskUsage () { - my ($MINOR, $FIRST, $TMIO) = (2, 4, 14); # index to stat entry - my (@accumStat) = (0,0,0,0,0,0,0,0,0,0,0); - my (@dstat); #$rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio - - open(FIN, "< $statfile"); - while () { - chomp; - @dstat = split(/\s+/); # blank zeroth element due to space(s) in beginning - if ($dstat[$MINOR] == 0 && $dstat[$TMIO] > 0) { # accum reading from device - for my $i ($FIRST..$#dstat) { - $accumStat[$i-$FIRST] += $dstat[$i]; - } - #print "Accumulated @accumStat\n"; - } - } - close(FIN); - return @accumStat; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# zero out disk IO stats -my($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) - = (0,0,0,0,0,0,0,0,0,0,0); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - # retrieve new disk IO stats - my ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN) = diskUsage(); - # compute delta stats for all except 9th and 10th - my ($rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio) = - ($rcmpN-$rcmpS, $rmrgN-$rmrgS, $rsectN-$rsectS, $rmsN-$rmsS, $wcmpN-$wcmpS, - $wmrgN-$wmrgS, $wsectN-$wsectS, $wmsN-$wmsS, $curioN, $curmsN, $tmioN-$tmioS); - # store the new saved ticks - ($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) = - ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN); - # each sector is 512 bytes as of kernel 2.4, so divide 2 to get kb - #print "D: $rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio\n" if ($doPrint); - my $kbRead = $rsect/2.0; - my $kbRps = ($rms == 0) ? 0 : ($kbRead / $rms) * 1000; # sec = 1000 ms - my $kbWritten = $wsect/2.0; - my $kbWps = ($wms == 0) ? 0 : ($kbWritten / $wms) * 1000; - my $tps = ($rms+$wms == 0) ? 0 : ($rcmp+$wcmp)/($rms+$wms) * 1000; - my $rpt = sprintf("[%s] %9.2f %9.2f %9.2f %9d %9d %9d %9d %9d\n", "".localtime(), - $tps, $kbRps, $kbWps, $kbRead, $kbWritten, $curio, $curms, $tmio); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "diskio"; +my $NAME = "DiskIOProbe"; +my $DELAY = 4000; +############################# + +# Determine diskstats format +my $statfile; +my $uname = `uname -a`; +if ($uname =~ /Linux\s+(.+?)\s+(\d+[.]\d+)/) { + if ($2 eq "2.6") { + $statfile = "/proc/diskstats"; +# } elsif ($2 <= 2.5) { +# $statfile = "/proc/partitions"; # granularity of info more coarse + } +} else { + print "Linux version unsupported for diskstat access! Unable to continue probing\n"; + exit -1; +} + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current accumulated Disk IO to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic Disk IO info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub diskUsage () { + my ($MINOR, $FIRST, $TMIO) = (2, 4, 14); # index to stat entry + my (@accumStat) = (0,0,0,0,0,0,0,0,0,0,0); + my (@dstat); #$rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio + + open(FIN, "< $statfile"); + while () { + chomp; + @dstat = split(/\s+/); # blank zeroth element due to space(s) in beginning + if ($dstat[$MINOR] == 0 && $dstat[$TMIO] > 0) { # accum reading from device + for my $i ($FIRST..$#dstat) { + $accumStat[$i-$FIRST] += $dstat[$i]; + } + #print "Accumulated @accumStat\n"; + } + } + close(FIN); + return @accumStat; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# zero out disk IO stats +my($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) + = (0,0,0,0,0,0,0,0,0,0,0); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + # retrieve new disk IO stats + my ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN) = diskUsage(); + # compute delta stats for all except 9th and 10th + my ($rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio) = + ($rcmpN-$rcmpS, $rmrgN-$rmrgS, $rsectN-$rsectS, $rmsN-$rmsS, $wcmpN-$wcmpS, + $wmrgN-$wmrgS, $wsectN-$wsectS, $wmsN-$wmsS, $curioN, $curmsN, $tmioN-$tmioS); + # store the new saved ticks + ($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) = + ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN); + # each sector is 512 bytes as of kernel 2.4, so divide 2 to get kb + #print "D: $rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio\n" if ($doPrint); + my $kbRead = $rsect/2.0; + my $kbRps = ($rms == 0) ? 0 : ($kbRead / $rms) * 1000; # sec = 1000 ms + my $kbWritten = $wsect/2.0; + my $kbWps = ($wms == 0) ? 0 : ($kbWritten / $wms) * 1000; + my $tps = ($rms+$wms == 0) ? 0 : ($rcmp+$wcmp)/($rms+$wms) * 1000; + my $rpt = sprintf("[%s] %9.2f %9.2f %9.2f %9d %9d %9d %9d %9d\n", "".localtime(), + $tps, $kbRps, $kbWps, $kbRead, $kbWritten, $curio, $curms, $tmio); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss_2/system/probes/diskIOProbe.pl b/targets/znews-ss_2/system/probes/diskIOProbe.pl index ec3391891..fe4b002b3 100644 --- a/targets/znews-ss_2/system/probes/diskIOProbe.pl +++ b/targets/znews-ss_2/system/probes/diskIOProbe.pl @@ -1,101 +1,101 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "diskio"; -my $NAME = "DiskIOProbe"; -my $DELAY = 5000; -############################# - -# Determine diskstats format -my $IOSTAT = "/usr/bin/iostat"; -if (! -e $IOSTAT) { - print "No iostat found, please install the sysstat package to continue!\n"; - exit -1; -} -my $IOSTAT_ARGS = "-k " . ($DELAY/1000); # period, with indefinite ouput - -sub usage() { - print STDERR << "EOF"; - -This program dumps periodic Disk IO status to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic Disk IO info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# init disk IO stats vars -my($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); -my($isInitial, $cntCycle) = (1, 0); -open(FIN, "$IOSTAT $IOSTAT_ARGS |") - || die "Can't fork $IOSTAT: $!"; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - # retrieve new disk IO stats - while () { - chomp; - if (/^Device:/i) { - ++$cntCycle; - if ($isInitial && $cntCycle > 1) { # no longer initial - print "Filtered initial round!\n" if ($doPrint); - $isInitial = 0; - } - } - if (!$isInitial && - /^(\w+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/) { - ($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB) = ($1, $2, $3, $4, $5, $6); - last; - } - } - my $rpt = sprintf("[%s] %s %.2f %.2f %.2f %d %d\n", "".localtime(), - $dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -close(FIN) || die "Bad $IOSTAT: $! $?"; -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "diskio"; +my $NAME = "DiskIOProbe"; +my $DELAY = 5000; +############################# + +# Determine diskstats format +my $IOSTAT = "/usr/bin/iostat"; +if (! -e $IOSTAT) { + print "No iostat found, please install the sysstat package to continue!\n"; + exit -1; +} +my $IOSTAT_ARGS = "-k " . ($DELAY/1000); # period, with indefinite ouput + +sub usage() { + print STDERR << "EOF"; + +This program dumps periodic Disk IO status to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic Disk IO info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# init disk IO stats vars +my($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); +my($isInitial, $cntCycle) = (1, 0); +open(FIN, "$IOSTAT $IOSTAT_ARGS |") + || die "Can't fork $IOSTAT: $!"; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + # retrieve new disk IO stats + while () { + chomp; + if (/^Device:/i) { + ++$cntCycle; + if ($isInitial && $cntCycle > 1) { # no longer initial + print "Filtered initial round!\n" if ($doPrint); + $isInitial = 0; + } + } + if (!$isInitial && + /^(\w+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/) { + ($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB) = ($1, $2, $3, $4, $5, $6); + last; + } + } + my $rpt = sprintf("[%s] %s %.2f %.2f %.2f %d %d\n", "".localtime(), + $dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +close(FIN) || die "Bad $IOSTAT: $! $?"; +cleanup($sock, [$fout]); diff --git a/targets/znews-ss_2/system/probes/fidelityProbe.pl b/targets/znews-ss_2/system/probes/fidelityProbe.pl index d5a8214ff..d22e3f086 100644 --- a/targets/znews-ss_2/system/probes/fidelityProbe.pl +++ b/targets/znews-ss_2/system/probes/fidelityProbe.pl @@ -1,100 +1,100 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "fidelity"; -my $NAME = "FidelityProbe"; -my $DELAY = 1000; -my $REPEATEVERY = 5; -my $APACHE_CONF_DIR = "/etc/apache2"; -my $APACHE_CONF_FILE = "apache2.conf"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current server fidelity (1,3,5) to Probe Relay file/socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic server fidelity info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub determineFidelity () { - my $fid = 0; - - open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); - my $firstLine = ; # read the first line - if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { - $fid = $1; - } - close(FIN); - - return $fid; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -my $repeatCnt = $REPEATEVERY; -my $savedFidelity = 0; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # compute new fidelity status - my $fidelity = determineFidelity(); - if ($fidelity != $savedFidelity || $repeatCnt == 0) { - $savedFidelity = $fidelity; #store new fidelity - my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - - if ($repeatCnt == 0) { - $repeatCnt = $REPEATEVERY; - } - } else { - $repeatCnt--; - } -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "fidelity"; +my $NAME = "FidelityProbe"; +my $DELAY = 1000; +my $REPEATEVERY = 5; +my $APACHE_CONF_DIR = "/etc/apache2"; +my $APACHE_CONF_FILE = "apache2.conf"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current server fidelity (1,3,5) to Probe Relay file/socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic server fidelity info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub determineFidelity () { + my $fid = 0; + + open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); + my $firstLine = ; # read the first line + if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { + $fid = $1; + } + close(FIN); + + return $fid; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +my $repeatCnt = $REPEATEVERY; +my $savedFidelity = 0; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # compute new fidelity status + my $fidelity = determineFidelity(); + if ($fidelity != $savedFidelity || $repeatCnt == 0) { + $savedFidelity = $fidelity; #store new fidelity + my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + + if ($repeatCnt == 0) { + $repeatCnt = $REPEATEVERY; + } + } else { + $repeatCnt--; + } +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss_2/system/probes/iostat.h b/targets/znews-ss_2/system/probes/iostat.h index 14abd66ec..644e9af0a 100644 --- a/targets/znews-ss_2/system/probes/iostat.h +++ b/targets/znews-ss_2/system/probes/iostat.h @@ -1,116 +1,116 @@ -/* - * iostat: report CPU and I/O statistics - * (C) 1999-2004 by Sebastien Godard - */ - -#ifndef _IOSTAT_H -#define _IOSTAT_H - -#include "common.h" - -#define MAX_NAME_LEN 72 - -#define D_CPU_ONLY 0x001 -#define D_DISK_ONLY 0x002 -#define D_TIMESTAMP 0x004 -#define D_EXTENDED 0x008 -#define D_PART_ALL 0x010 -#define D_KILOBYTES 0x020 -#define F_HAS_SYSFS 0x040 -#define F_OLD_KERNEL 0x080 -#define D_UNFILTERED 0x100 -/* 0x100000:0x800000 -> reserved (cf. common.h) */ - -#define DISPLAY_CPU_ONLY(m) (((m) & D_CPU_ONLY) == D_CPU_ONLY) -#define DISPLAY_DISK_ONLY(m) (((m) & D_DISK_ONLY) == D_DISK_ONLY) -#define DISPLAY_TIMESTAMP(m) (((m) & D_TIMESTAMP) == D_TIMESTAMP) -#define DISPLAY_EXTENDED(m) (((m) & D_EXTENDED) == D_EXTENDED) -#define DISPLAY_PART_ALL(m) (((m) & D_PART_ALL) == D_PART_ALL) -#define DISPLAY_KILOBYTES(m) (((m) & D_KILOBYTES) == D_KILOBYTES) -#define HAS_SYSFS(m) (((m) & F_HAS_SYSFS) == F_HAS_SYSFS) -#define HAS_OLD_KERNEL(m) (((m) & F_OLD_KERNEL) == F_OLD_KERNEL) -#define DISPLAY_UNFILTERED(m) (((m) & D_UNFILTERED) == D_UNFILTERED) - -#define DT_DEVICE 0 -#define DT_PARTITION 1 - - -struct comm_stats { - unsigned long uptime; - unsigned long uptime0; - unsigned long cpu_iowait; - unsigned long cpu_idle; - unsigned int cpu_user; - unsigned int cpu_nice; - unsigned int cpu_system; -}; - -#define COMM_STATS_SIZE (sizeof(struct comm_stats)) - -/* - * Structures for I/O stats. - * The number of structures allocated corresponds to the number of devices - * present in the system, plus a preallocation number to handle those - * that can be registered dynamically. - * The number of devices is found by using /sys filesystem (if mounted), - * or the number of "disk_io:" entries in /proc/stat (2.4 kernels), - * else the default value is 4 (for old kernels, which maintained stats - * for the first four devices in /proc/stat). - * For each io_stats structure allocated corresponds a io_hdr_stats structure. - * A io_stats structure is considered as unused or "free" (containing no stats - * for a particular device) if the 'major' field of the io_hdr_stats - * structure is set to 0. - */ -struct io_stats { - /* # of read operations issued to the device */ - unsigned int rd_ios __attribute__ ((aligned (8))); - /* # of read requests merged */ - unsigned int rd_merges __attribute__ ((packed)); - /* # of sectors read */ - unsigned int rd_sectors __attribute__ ((packed)); - /* Time of read requests in queue */ - unsigned int rd_ticks __attribute__ ((packed)); - /* # of write operations issued to the device */ - unsigned int wr_ios __attribute__ ((packed)); - /* # of write requests merged */ - unsigned int wr_merges __attribute__ ((packed)); - /* # of sectors written */ - unsigned int wr_sectors __attribute__ ((packed)); - /* Time of write requests in queue */ - unsigned int wr_ticks __attribute__ ((packed)); - /* # of I/Os in progress */ - unsigned int ios_pgr __attribute__ ((packed)); - /* # of ticks total (for this device) for I/O */ - unsigned int tot_ticks __attribute__ ((packed)); - /* # of ticks requests spent in queue */ - unsigned int rq_ticks __attribute__ ((packed)); - /* # of I/O done since last reboot */ - unsigned int dk_drive __attribute__ ((packed)); - /* # of blocks read */ - unsigned int dk_drive_rblk __attribute__ ((packed)); - /* # of blocks written */ - unsigned int dk_drive_wblk __attribute__ ((packed)); -}; - -#define IO_STATS_SIZE (sizeof(struct io_stats)) - -struct io_hdr_stats { - unsigned int active __attribute__ ((aligned (8))); - unsigned int major __attribute__ ((packed)); - unsigned int index __attribute__ ((packed)); - char name[MAX_NAME_LEN] __attribute__ ((packed)); -}; - -#define IO_HDR_STATS_SIZE (sizeof(struct io_hdr_stats)) - -/* List of devices entered on the command line */ -struct io_dlist { - /* Indicate whether its partitions are to be displayed or not */ - int disp_part __attribute__ ((aligned (8))); - /* Device name */ - char dev_name[MAX_NAME_LEN] __attribute__ ((packed)); -}; - -#define IO_DLIST_SIZE (sizeof(struct io_dlist)) - -#endif /* _IOSTAT_H */ +/* + * iostat: report CPU and I/O statistics + * (C) 1999-2004 by Sebastien Godard + */ + +#ifndef _IOSTAT_H +#define _IOSTAT_H + +#include "common.h" + +#define MAX_NAME_LEN 72 + +#define D_CPU_ONLY 0x001 +#define D_DISK_ONLY 0x002 +#define D_TIMESTAMP 0x004 +#define D_EXTENDED 0x008 +#define D_PART_ALL 0x010 +#define D_KILOBYTES 0x020 +#define F_HAS_SYSFS 0x040 +#define F_OLD_KERNEL 0x080 +#define D_UNFILTERED 0x100 +/* 0x100000:0x800000 -> reserved (cf. common.h) */ + +#define DISPLAY_CPU_ONLY(m) (((m) & D_CPU_ONLY) == D_CPU_ONLY) +#define DISPLAY_DISK_ONLY(m) (((m) & D_DISK_ONLY) == D_DISK_ONLY) +#define DISPLAY_TIMESTAMP(m) (((m) & D_TIMESTAMP) == D_TIMESTAMP) +#define DISPLAY_EXTENDED(m) (((m) & D_EXTENDED) == D_EXTENDED) +#define DISPLAY_PART_ALL(m) (((m) & D_PART_ALL) == D_PART_ALL) +#define DISPLAY_KILOBYTES(m) (((m) & D_KILOBYTES) == D_KILOBYTES) +#define HAS_SYSFS(m) (((m) & F_HAS_SYSFS) == F_HAS_SYSFS) +#define HAS_OLD_KERNEL(m) (((m) & F_OLD_KERNEL) == F_OLD_KERNEL) +#define DISPLAY_UNFILTERED(m) (((m) & D_UNFILTERED) == D_UNFILTERED) + +#define DT_DEVICE 0 +#define DT_PARTITION 1 + + +struct comm_stats { + unsigned long uptime; + unsigned long uptime0; + unsigned long cpu_iowait; + unsigned long cpu_idle; + unsigned int cpu_user; + unsigned int cpu_nice; + unsigned int cpu_system; +}; + +#define COMM_STATS_SIZE (sizeof(struct comm_stats)) + +/* + * Structures for I/O stats. + * The number of structures allocated corresponds to the number of devices + * present in the system, plus a preallocation number to handle those + * that can be registered dynamically. + * The number of devices is found by using /sys filesystem (if mounted), + * or the number of "disk_io:" entries in /proc/stat (2.4 kernels), + * else the default value is 4 (for old kernels, which maintained stats + * for the first four devices in /proc/stat). + * For each io_stats structure allocated corresponds a io_hdr_stats structure. + * A io_stats structure is considered as unused or "free" (containing no stats + * for a particular device) if the 'major' field of the io_hdr_stats + * structure is set to 0. + */ +struct io_stats { + /* # of read operations issued to the device */ + unsigned int rd_ios __attribute__ ((aligned (8))); + /* # of read requests merged */ + unsigned int rd_merges __attribute__ ((packed)); + /* # of sectors read */ + unsigned int rd_sectors __attribute__ ((packed)); + /* Time of read requests in queue */ + unsigned int rd_ticks __attribute__ ((packed)); + /* # of write operations issued to the device */ + unsigned int wr_ios __attribute__ ((packed)); + /* # of write requests merged */ + unsigned int wr_merges __attribute__ ((packed)); + /* # of sectors written */ + unsigned int wr_sectors __attribute__ ((packed)); + /* Time of write requests in queue */ + unsigned int wr_ticks __attribute__ ((packed)); + /* # of I/Os in progress */ + unsigned int ios_pgr __attribute__ ((packed)); + /* # of ticks total (for this device) for I/O */ + unsigned int tot_ticks __attribute__ ((packed)); + /* # of ticks requests spent in queue */ + unsigned int rq_ticks __attribute__ ((packed)); + /* # of I/O done since last reboot */ + unsigned int dk_drive __attribute__ ((packed)); + /* # of blocks read */ + unsigned int dk_drive_rblk __attribute__ ((packed)); + /* # of blocks written */ + unsigned int dk_drive_wblk __attribute__ ((packed)); +}; + +#define IO_STATS_SIZE (sizeof(struct io_stats)) + +struct io_hdr_stats { + unsigned int active __attribute__ ((aligned (8))); + unsigned int major __attribute__ ((packed)); + unsigned int index __attribute__ ((packed)); + char name[MAX_NAME_LEN] __attribute__ ((packed)); +}; + +#define IO_HDR_STATS_SIZE (sizeof(struct io_hdr_stats)) + +/* List of devices entered on the command line */ +struct io_dlist { + /* Indicate whether its partitions are to be displayed or not */ + int disp_part __attribute__ ((aligned (8))); + /* Device name */ + char dev_name[MAX_NAME_LEN] __attribute__ ((packed)); +}; + +#define IO_DLIST_SIZE (sizeof(struct io_dlist)) + +#endif /* _IOSTAT_H */ diff --git a/targets/znews-ss_2/system/probes/iostats.txt b/targets/znews-ss_2/system/probes/iostats.txt index 612dc5511..ba75611ea 100644 --- a/targets/znews-ss_2/system/probes/iostats.txt +++ b/targets/znews-ss_2/system/probes/iostats.txt @@ -1,151 +1,151 @@ -I/O statistics fields ---------------- - -Based on kernel version 2.6.20. Page generated on 2007-02-07 22:05 EST -Last modified Sep 30, 2003 - -Since 2.4.20 (and some versions before, with patches), and 2.5.45, -more extensive disk statistics have been introduced to help measure disk -activity. Tools such as sar and iostat typically interpret these and do -the work for you, but in case you are interested in creating your own -tools, the fields are explained here. - -In 2.4 now, the information is found as additional fields in -/proc/partitions. In 2.6, the same information is found in two -places: one is in the file /proc/diskstats, and the other is within -the sysfs file system, which must be mounted in order to obtain -the information. Throughout this document we'll assume that sysfs -is mounted on /sys, although of course it may be mounted anywhere. -Both /proc/diskstats and sysfs use the same source for the information -and so should not differ. - -Here are examples of these different formats: - -2.4: - 3 0 39082680 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 3 1 9221278 hda1 35486 0 35496 38030 0 0 0 0 0 38030 38030 - - -2.6 sysfs: - 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 35486 38030 38030 38030 - -2.6 diskstats: - 3 0 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 - 3 1 hda1 35486 38030 38030 38030 - -On 2.4 you might execute "grep 'hda ' /proc/partitions". On 2.6, you have -a choice of "cat /sys/block/hda/stat" or "grep 'hda ' /proc/diskstats". -The advantage of one over the other is that the sysfs choice works well -if you are watching a known, small set of disks. /proc/diskstats may -be a better choice if you are watching a large number of disks because -you'll avoid the overhead of 50, 100, or 500 or more opens/closes with -each snapshot of your disk statistics. - -In 2.4, the statistics fields are those after the device name. In -the above example, the first field of statistics would be 446216. -By contrast, in 2.6 if you look at /sys/block/hda/stat, you'll -find just the eleven fields, beginning with 446216. If you look at -/proc/diskstats, the eleven fields will be preceded by the major and -minor device numbers, and device name. Each of these formats provide -eleven fields of statistics, each meaning exactly the same things. -All fields except field 9 are cumulative since boot. Field 9 should -go to zero as I/Os complete; all others only increase. Yes, these are -32 bit unsigned numbers, and on a very busy or long-lived system they -may wrap. Applications should be prepared to deal with that; unless -your observations are measured in large numbers of minutes or hours, -they should not wrap twice before you notice them. - -Each set of stats only applies to the indicated device; if you want -system-wide stats you'll have to find all the devices and sum them all up. - -Field 1 -- # of reads issued - This is the total number of reads completed successfully. -Field 2 -- # of reads merged, field 6 -- # of writes merged - Reads and writes which are adjacent to each other may be merged for - efficiency. Thus two 4K reads may become one 8K read before it is - ultimately handed to the disk, and so it will be counted (and queued) - as only one I/O. This field lets you know how often this was done. -Field 3 -- # of sectors read - This is the total number of sectors read successfully. -Field 4 -- # of milliseconds spent reading - This is the total number of milliseconds spent by all reads (as - measured from __make_request() to end_that_request_last()). -Field 5 -- # of writes completed - This is the total number of writes completed successfully. -Field 7 -- # of sectors written - This is the total number of sectors written successfully. -Field 8 -- # of milliseconds spent writing - This is the total number of milliseconds spent by all writes (as - measured from __make_request() to end_that_request_last()). -Field 9 -- # of I/Os currently in progress - The only field that should go to zero. Incremented as requests are - given to appropriate request_queue_t and decremented as they finish. -Field 10 -- # of milliseconds spent doing I/Os - This field is increases so long as field 9 is nonzero. -Field 11 -- weighted # of milliseconds spent doing I/Os - This field is incremented at each I/O start, I/O completion, I/O - merge, or read of these stats by the number of I/Os in progress - (field 9) times the number of milliseconds spent doing I/O since the - last update of this field. This can provide an easy measure of both - I/O completion time and the backlog that may be accumulating. - - -To avoid introducing performance bottlenecks, no locks are held while -modifying these counters. This implies that minor inaccuracies may be -introduced when changes collide, so (for instance) adding up all the -read I/Os issued per partition should equal those made to the disks ... -but due to the lack of locking it may only be very close. - -In 2.6, there are counters for each cpu, which made the lack of locking -almost a non-issue. When the statistics are read, the per-cpu counters -are summed (possibly overflowing the unsigned 32-bit variable they are -summed to) and the result given to the user. There is no convenient -user interface for accessing the per-cpu counters themselves. - -Disks vs Partitions -------------------- - -There were significant changes between 2.4 and 2.6 in the I/O subsystem. -As a result, some statistic information disappeared. The translation from -a disk address relative to a partition to the disk address relative to -the host disk happens much earlier. All merges and timings now happen -at the disk level rather than at both the disk and partition level as -in 2.4. Consequently, you'll see a different statistics output on 2.6 for -partitions from that for disks. There are only *four* fields available -for partitions on 2.6 machines. This is reflected in the examples above. - -Field 1 -- # of reads issued - This is the total number of reads issued to this partition. -Field 2 -- # of sectors read - This is the total number of sectors requested to be read from this - partition. -Field 3 -- # of writes issued - This is the total number of writes issued to this partition. -Field 4 -- # of sectors written - This is the total number of sectors requested to be written to - this partition. - -Note that since the address is translated to a disk-relative one, and no -record of the partition-relative address is kept, the subsequent success -or failure of the read cannot be attributed to the partition. In other -words, the number of reads for partitions is counted slightly before time -of queuing for partitions, and at completion for whole disks. This is -a subtle distinction that is probably uninteresting for most cases. - -Additional notes ----------------- - -In 2.6, sysfs is not mounted by default. If your distribution of -Linux hasn't added it already, here's the line you'll want to add to -your /etc/fstab: - -none /sys sysfs defaults 0 0 - - -In 2.6, all disk statistics were removed from /proc/stat. In 2.4, they -appear in both /proc/partitions and /proc/stat, although the ones in -/proc/stat take a very different format from those in /proc/partitions -(see proc(5), if your system has it.) - --- ricklind[AT]us.ibm[DOT]com +I/O statistics fields +--------------- + +Based on kernel version 2.6.20. Page generated on 2007-02-07 22:05 EST +Last modified Sep 30, 2003 + +Since 2.4.20 (and some versions before, with patches), and 2.5.45, +more extensive disk statistics have been introduced to help measure disk +activity. Tools such as sar and iostat typically interpret these and do +the work for you, but in case you are interested in creating your own +tools, the fields are explained here. + +In 2.4 now, the information is found as additional fields in +/proc/partitions. In 2.6, the same information is found in two +places: one is in the file /proc/diskstats, and the other is within +the sysfs file system, which must be mounted in order to obtain +the information. Throughout this document we'll assume that sysfs +is mounted on /sys, although of course it may be mounted anywhere. +Both /proc/diskstats and sysfs use the same source for the information +and so should not differ. + +Here are examples of these different formats: + +2.4: + 3 0 39082680 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 3 1 9221278 hda1 35486 0 35496 38030 0 0 0 0 0 38030 38030 + + +2.6 sysfs: + 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 35486 38030 38030 38030 + +2.6 diskstats: + 3 0 hda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 + 3 1 hda1 35486 38030 38030 38030 + +On 2.4 you might execute "grep 'hda ' /proc/partitions". On 2.6, you have +a choice of "cat /sys/block/hda/stat" or "grep 'hda ' /proc/diskstats". +The advantage of one over the other is that the sysfs choice works well +if you are watching a known, small set of disks. /proc/diskstats may +be a better choice if you are watching a large number of disks because +you'll avoid the overhead of 50, 100, or 500 or more opens/closes with +each snapshot of your disk statistics. + +In 2.4, the statistics fields are those after the device name. In +the above example, the first field of statistics would be 446216. +By contrast, in 2.6 if you look at /sys/block/hda/stat, you'll +find just the eleven fields, beginning with 446216. If you look at +/proc/diskstats, the eleven fields will be preceded by the major and +minor device numbers, and device name. Each of these formats provide +eleven fields of statistics, each meaning exactly the same things. +All fields except field 9 are cumulative since boot. Field 9 should +go to zero as I/Os complete; all others only increase. Yes, these are +32 bit unsigned numbers, and on a very busy or long-lived system they +may wrap. Applications should be prepared to deal with that; unless +your observations are measured in large numbers of minutes or hours, +they should not wrap twice before you notice them. + +Each set of stats only applies to the indicated device; if you want +system-wide stats you'll have to find all the devices and sum them all up. + +Field 1 -- # of reads issued + This is the total number of reads completed successfully. +Field 2 -- # of reads merged, field 6 -- # of writes merged + Reads and writes which are adjacent to each other may be merged for + efficiency. Thus two 4K reads may become one 8K read before it is + ultimately handed to the disk, and so it will be counted (and queued) + as only one I/O. This field lets you know how often this was done. +Field 3 -- # of sectors read + This is the total number of sectors read successfully. +Field 4 -- # of milliseconds spent reading + This is the total number of milliseconds spent by all reads (as + measured from __make_request() to end_that_request_last()). +Field 5 -- # of writes completed + This is the total number of writes completed successfully. +Field 7 -- # of sectors written + This is the total number of sectors written successfully. +Field 8 -- # of milliseconds spent writing + This is the total number of milliseconds spent by all writes (as + measured from __make_request() to end_that_request_last()). +Field 9 -- # of I/Os currently in progress + The only field that should go to zero. Incremented as requests are + given to appropriate request_queue_t and decremented as they finish. +Field 10 -- # of milliseconds spent doing I/Os + This field is increases so long as field 9 is nonzero. +Field 11 -- weighted # of milliseconds spent doing I/Os + This field is incremented at each I/O start, I/O completion, I/O + merge, or read of these stats by the number of I/Os in progress + (field 9) times the number of milliseconds spent doing I/O since the + last update of this field. This can provide an easy measure of both + I/O completion time and the backlog that may be accumulating. + + +To avoid introducing performance bottlenecks, no locks are held while +modifying these counters. This implies that minor inaccuracies may be +introduced when changes collide, so (for instance) adding up all the +read I/Os issued per partition should equal those made to the disks ... +but due to the lack of locking it may only be very close. + +In 2.6, there are counters for each cpu, which made the lack of locking +almost a non-issue. When the statistics are read, the per-cpu counters +are summed (possibly overflowing the unsigned 32-bit variable they are +summed to) and the result given to the user. There is no convenient +user interface for accessing the per-cpu counters themselves. + +Disks vs Partitions +------------------- + +There were significant changes between 2.4 and 2.6 in the I/O subsystem. +As a result, some statistic information disappeared. The translation from +a disk address relative to a partition to the disk address relative to +the host disk happens much earlier. All merges and timings now happen +at the disk level rather than at both the disk and partition level as +in 2.4. Consequently, you'll see a different statistics output on 2.6 for +partitions from that for disks. There are only *four* fields available +for partitions on 2.6 machines. This is reflected in the examples above. + +Field 1 -- # of reads issued + This is the total number of reads issued to this partition. +Field 2 -- # of sectors read + This is the total number of sectors requested to be read from this + partition. +Field 3 -- # of writes issued + This is the total number of writes issued to this partition. +Field 4 -- # of sectors written + This is the total number of sectors requested to be written to + this partition. + +Note that since the address is translated to a disk-relative one, and no +record of the partition-relative address is kept, the subsequent success +or failure of the read cannot be attributed to the partition. In other +words, the number of reads for partitions is counted slightly before time +of queuing for partitions, and at completion for whole disks. This is +a subtle distinction that is probably uninteresting for most cases. + +Additional notes +---------------- + +In 2.6, sysfs is not mounted by default. If your distribution of +Linux hasn't added it already, here's the line you'll want to add to +your /etc/fstab: + +none /sys sysfs defaults 0 0 + + +In 2.6, all disk statistics were removed from /proc/stat. In 2.4, they +appear in both /proc/partitions and /proc/stat, although the ones in +/proc/stat take a very different format from those in /proc/partitions +(see proc(5), if your system has it.) + +-- ricklind[AT]us.ibm[DOT]com diff --git a/targets/znews-ss_2/system/probes/loadProbe.pl b/targets/znews-ss_2/system/probes/loadProbe.pl index 7f2e12dc8..3b648fd9c 100644 --- a/targets/znews-ss_2/system/probes/loadProbe.pl +++ b/targets/znews-ss_2/system/probes/loadProbe.pl @@ -1,101 +1,101 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "load"; -my $NAME = "LoadProbe"; -my $DELAY = 2500; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current CPU usage to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic CPU usage info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub cpuTime () { - my ($user, $nice, $sys, $idle, $iowait); - - local(*FIN); - open(FIN, ") { - chomp; - if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(\s+(\d+))?/o) { - ($user, $nice, $sys, $idle, $iowait) = ($1, $2, $3, $4, $6); - if (!defined($iowait)) { - $iowait = 0; - } - last; - } - } - close(FIN); - return ($user, $nice, $sys, $idle, $iowait); -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# save current cpu ticks -my($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = cpuTime(); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # retrieve new cpu ticks - my ($userN, $niceN, $sysN, $idleN, $iowaitN) = cpuTime(); - # compute delta cpu ticks - my ($user, $nice, $sys, $idle, $iowait) = - ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv, $iowaitN - $iowaitSv); - # store the new saved ticks - ($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = ($userN, $niceN, $sysN, $idleN, $iowaitN); - my $total = $user + $nice + $sys + $idle + $iowait; - my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), - $user/$total, $nice/$total, $sys/$total, $idle/$total, $iowait/$total); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "load"; +my $NAME = "LoadProbe"; +my $DELAY = 2500; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current CPU usage to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic CPU usage info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub cpuTime () { + my ($user, $nice, $sys, $idle, $iowait); + + local(*FIN); + open(FIN, ") { + chomp; + if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(\s+(\d+))?/o) { + ($user, $nice, $sys, $idle, $iowait) = ($1, $2, $3, $4, $6); + if (!defined($iowait)) { + $iowait = 0; + } + last; + } + } + close(FIN); + return ($user, $nice, $sys, $idle, $iowait); +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# save current cpu ticks +my($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = cpuTime(); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # retrieve new cpu ticks + my ($userN, $niceN, $sysN, $idleN, $iowaitN) = cpuTime(); + # compute delta cpu ticks + my ($user, $nice, $sys, $idle, $iowait) = + ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv, $iowaitN - $iowaitSv); + # store the new saved ticks + ($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = ($userN, $niceN, $sysN, $idleN, $iowaitN); + my $total = $user + $nice + $sys + $idle + $iowait; + my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), + $user/$total, $nice/$total, $sys/$total, $idle/$total, $iowait/$total); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews-ss_2/system/probes/runApachetop.pl b/targets/znews-ss_2/system/probes/runApachetop.pl index 2d9a80a4d..741ee43f6 100644 --- a/targets/znews-ss_2/system/probes/runApachetop.pl +++ b/targets/znews-ss_2/system/probes/runApachetop.pl @@ -1,16 +1,16 @@ -#!/usr/bin/perl -w - -use strict; - -############################# -my $APACHE_LOG = "/var/log/apache2/access-delegate.log"; -my $APACHETOP_LOG = "../../log/apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - -if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; +#!/usr/bin/perl -w + +use strict; + +############################# +my $APACHE_LOG = "/var/log/apache2/access-delegate.log"; +my $APACHETOP_LOG = "../../log/apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + +if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; diff --git a/targets/znews-ss_2/system/webpages/www1/index.html b/targets/znews-ss_2/system/webpages/www1/index.html index 050159b89..4ec9f5304 100644 --- a/targets/znews-ss_2/system/webpages/www1/index.html +++ b/targets/znews-ss_2/system/webpages/www1/index.html @@ -1,46 +1,46 @@ - - -Somewhere Over the Rainbow - - -

Z.com News - Hello World! (Low-fidelity Settings)

- -We apologize for this text-only content, as we are currently swamped with visitors. Thank you for your patience as we work hard to serve your requests. (This file is a little over 3 KB.) -

-SYDNEY, Australia (Reuters) -- In death as in life, iconic TV naturalist Steve Irwin captivated millions worldwide and clogged the Internet as fans from Guam to Glasgow reacted with disbelief to news "The Crocodile Hunter" was dead. -

-Some Web sites groaned to a halt within hours of the first reports Monday that Irwin had been killed by a stingray's barb through his chest in a freak diving accident off Australia's northeast coast. -

-Web measurement company Hitwise said Irwin's death was the biggest news event read by Australians on the Internet since two Australian miners were trapped by a mine collapse in southern Tasmania state in late April. -

-"We noticed that the Web site www.crocodilehunter.com increased in popularity quite substantially. It became the number one entertainment personality Web site in Australia yesterday and in the United States it also became the third most popular," Hitwise Asia-Pacific marketing director James Borg told Reuters. -

-Australian news Web sites struggled to keep up with demand. -

-The Australian Broadcasting Corp.'s site (www.abc.com.au) had to temporarily shut down, posting a notice Monday that it was experiencing higher than normal traffic. -

-It resumed soon after in a low-bandwidth format to cope with hundreds of thousands of hits. -

-Newspaper Web sites also wobbled but kept up with demand. -

-A spokesman for The Sydney Morning Herald's site, www.smh.com.au, said it had experienced a "huge" 40 percent spike in page impressions compared with the previous week's average weekday number of about 500,000. -

-There was also a 70 percent jump in visitors to its pages, the spokesman said. -

-That pattern was mirrored around the world, with Irwin's death leading major news Web sites such as CNN.com and U.S. and British newspaper Web sites, as well as swamping their most viewed and most emailed categories. -

-Web logs and Internet feedback pages were also awash with postings from shocked readers from around the world, many of them from Americans charmed by Irwin's quirky style and his typically Australian catchphrase of "crikey." -

-Irwin first found fame in the United States before his "Crocodile Hunter" documentaries on U.S.-based television company Discovery Communications' Animal Planet attracted a global audience of 200 million -- 10 times Australia's population. -

-"Crikey!, I miss him so much," Tina Treece from Pittsburgh, Pennsylvania, posted on CNN.com's feedback page CNN Exchange. -

-The site had contributions from readers in Guam, Romania, Thailand, France, Scotland, India, New Zealand, Canada, Brunei, Britain, Malaysia, Denmark and the Netherlands. -

-Many faced the problem of explaining to their children how one of their favorite TV characters had died. -

-"Why did it have to be Steve Irwin?" 11-year-old Daniel told Australian Associated Press. -

-Copyright 2006 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed. - - + + +Somewhere Over the Rainbow + + +

Z.com News - Hello World! (Low-fidelity Settings)

+ +We apologize for this text-only content, as we are currently swamped with visitors. Thank you for your patience as we work hard to serve your requests. (This file is a little over 3 KB.) +

+SYDNEY, Australia (Reuters) -- In death as in life, iconic TV naturalist Steve Irwin captivated millions worldwide and clogged the Internet as fans from Guam to Glasgow reacted with disbelief to news "The Crocodile Hunter" was dead. +

+Some Web sites groaned to a halt within hours of the first reports Monday that Irwin had been killed by a stingray's barb through his chest in a freak diving accident off Australia's northeast coast. +

+Web measurement company Hitwise said Irwin's death was the biggest news event read by Australians on the Internet since two Australian miners were trapped by a mine collapse in southern Tasmania state in late April. +

+"We noticed that the Web site www.crocodilehunter.com increased in popularity quite substantially. It became the number one entertainment personality Web site in Australia yesterday and in the United States it also became the third most popular," Hitwise Asia-Pacific marketing director James Borg told Reuters. +

+Australian news Web sites struggled to keep up with demand. +

+The Australian Broadcasting Corp.'s site (www.abc.com.au) had to temporarily shut down, posting a notice Monday that it was experiencing higher than normal traffic. +

+It resumed soon after in a low-bandwidth format to cope with hundreds of thousands of hits. +

+Newspaper Web sites also wobbled but kept up with demand. +

+A spokesman for The Sydney Morning Herald's site, www.smh.com.au, said it had experienced a "huge" 40 percent spike in page impressions compared with the previous week's average weekday number of about 500,000. +

+There was also a 70 percent jump in visitors to its pages, the spokesman said. +

+That pattern was mirrored around the world, with Irwin's death leading major news Web sites such as CNN.com and U.S. and British newspaper Web sites, as well as swamping their most viewed and most emailed categories. +

+Web logs and Internet feedback pages were also awash with postings from shocked readers from around the world, many of them from Americans charmed by Irwin's quirky style and his typically Australian catchphrase of "crikey." +

+Irwin first found fame in the United States before his "Crocodile Hunter" documentaries on U.S.-based television company Discovery Communications' Animal Planet attracted a global audience of 200 million -- 10 times Australia's population. +

+"Crikey!, I miss him so much," Tina Treece from Pittsburgh, Pennsylvania, posted on CNN.com's feedback page CNN Exchange. +

+The site had contributions from readers in Guam, Romania, Thailand, France, Scotland, India, New Zealand, Canada, Brunei, Britain, Malaysia, Denmark and the Netherlands. +

+Many faced the problem of explaining to their children how one of their favorite TV characters had died. +

+"Why did it have to be Steve Irwin?" 11-year-old Daniel told Australian Associated Press. +

+Copyright 2006 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed. + + diff --git a/targets/znews-ss_2/system/webpages/www3/index.html b/targets/znews-ss_2/system/webpages/www3/index.html index d5801caa4..dee934b7c 100644 --- a/targets/znews-ss_2/system/webpages/www3/index.html +++ b/targets/znews-ss_2/system/webpages/www3/index.html @@ -1,11 +1,11 @@ - - -Somewhere Over the Rainbow - - -

Z.com News - Hello World! (Medium-fidelity Settings)

-This file contains an 800x600 pixel image. The total size of this file is approximately 53K. -
- - + + +Somewhere Over the Rainbow + + +

Z.com News - Hello World! (Medium-fidelity Settings)

+This file contains an 800x600 pixel image. The total size of this file is approximately 53K. +
+ + \ No newline at end of file diff --git a/targets/znews-ss_2/system/webpages/www5/cgi-bin/computePi.pl b/targets/znews-ss_2/system/webpages/www5/cgi-bin/computePi.pl index 6871ac9b4..235516a09 100644 --- a/targets/znews-ss_2/system/webpages/www5/cgi-bin/computePi.pl +++ b/targets/znews-ss_2/system/webpages/www5/cgi-bin/computePi.pl @@ -1,118 +1,118 @@ -#!/usr/bin/perl - -use strict; -use Carp; -use Math::BigFloat; -use Class::Struct qw(struct); -use Data::Dumper; - -# With due homage to Mathsoft's site: -# http://www.mathsoft.com/asolve/constant/pi/pi.html - -# Set the global precision. Faster than passing it everywhichwhere. -my $precision = @ARGV>0?$ARGV[0]:512; - -# Set the iteration count. -my $maxIterations = @ARGV>1?$ARGV[1]:10; - -# Set the verbose debugging flag. -my $debugVerbose = 0; - -# Constants: -my $_1 = Math::BigFloat->new(1); -my $_2 = Math::BigFloat->new(2); -my $_3 = Math::BigFloat->new(3); -my $_4 = Math::BigFloat->new(4); -my $_6 = Math::BigFloat->new(6); -my $_8 = Math::BigFloat->new(8); -my $_239 = Math::BigFloat->new(239); -my $_half = Math::BigFloat->new(0.5); -my $_fifth = Math::BigFloat->new(0.2); -my $_25th = Math::BigFloat->new(0.04); -my $_239th = inv($_239); -my $_57121th = inv($_239*$_239); - - -# Utility methods: -sub div { - my $a = shift; - my $b = shift; - return new Math::BigFloat $a->copy()->fdiv($b,$precision); -} -sub inv { # Inverse (1/x) function. - my $a = shift; - return new Math::BigFloat $_1->copy()->fdiv($a,$precision); -} -sub root2 { - my $self = shift; - return new Math::BigFloat $self->copy()->fsqrt($precision); -} -sub root4 { - my $self = shift; - return root2(root2($self)); -} -sub pow4 { - my $self = shift; - my $square = round($self*$self); - return round($square*$square); -} -sub round { - my $self = shift; - return new Math::BigFloat $self->copy()->fround($precision); -} - -# Method 4: - -# This uses Ramanujan's elliptic integral-based technique to -# compute Pi monstrously quickly. -# -# This algorithm is neat, since it is quartically convergent - -# that means that the error goes as 4^(-iteration_count). -# -# In other words, one more step = four times the # of correct digits. - -sub RamanujanEI { - if (@_) { - my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. - - my $z_4_term = root4($_1 - pow4($z)); - my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); - - my $z_next_plus_1 = $z_next + $_1; - - my $a_next = pow4($z_next_plus_1) * $a - - $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); - $a_next = round($a_next); - return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; - - } else { # Seed the recurrence - my $a = $_6-$_4*root2($_2); - return [ $a, root2($_2)-$_1, $_8, inv($a)]; - } -} - - - -###################################################################### -# -# Main routine: -# -# - -my $iterResult = RamanujanEI(); -for (my $i=1; $i<$maxIterations; $i++) { - $iterResult = RamanujanEI($iterResult); -} -my $piValue = ${$iterResult}[-1]; -my $piStr = "" . $piValue; - -my $CHUNK = 32; -my $i = $CHUNK + 1; -print "Content-type: text/plain\r\n"; -print "Content-length: 570\r\n\r\n"; -print "Pi_512 :=\n"; -print " " . substr($piValue, 0, $i) . "\n"; -for (; $i < length($piValue) ; $i+=$CHUNK) { - print " " . substr($piValue, $i, $CHUNK) . "\n"; -} - +#!/usr/bin/perl + +use strict; +use Carp; +use Math::BigFloat; +use Class::Struct qw(struct); +use Data::Dumper; + +# With due homage to Mathsoft's site: +# http://www.mathsoft.com/asolve/constant/pi/pi.html + +# Set the global precision. Faster than passing it everywhichwhere. +my $precision = @ARGV>0?$ARGV[0]:512; + +# Set the iteration count. +my $maxIterations = @ARGV>1?$ARGV[1]:10; + +# Set the verbose debugging flag. +my $debugVerbose = 0; + +# Constants: +my $_1 = Math::BigFloat->new(1); +my $_2 = Math::BigFloat->new(2); +my $_3 = Math::BigFloat->new(3); +my $_4 = Math::BigFloat->new(4); +my $_6 = Math::BigFloat->new(6); +my $_8 = Math::BigFloat->new(8); +my $_239 = Math::BigFloat->new(239); +my $_half = Math::BigFloat->new(0.5); +my $_fifth = Math::BigFloat->new(0.2); +my $_25th = Math::BigFloat->new(0.04); +my $_239th = inv($_239); +my $_57121th = inv($_239*$_239); + + +# Utility methods: +sub div { + my $a = shift; + my $b = shift; + return new Math::BigFloat $a->copy()->fdiv($b,$precision); +} +sub inv { # Inverse (1/x) function. + my $a = shift; + return new Math::BigFloat $_1->copy()->fdiv($a,$precision); +} +sub root2 { + my $self = shift; + return new Math::BigFloat $self->copy()->fsqrt($precision); +} +sub root4 { + my $self = shift; + return root2(root2($self)); +} +sub pow4 { + my $self = shift; + my $square = round($self*$self); + return round($square*$square); +} +sub round { + my $self = shift; + return new Math::BigFloat $self->copy()->fround($precision); +} + +# Method 4: + +# This uses Ramanujan's elliptic integral-based technique to +# compute Pi monstrously quickly. +# +# This algorithm is neat, since it is quartically convergent - +# that means that the error goes as 4^(-iteration_count). +# +# In other words, one more step = four times the # of correct digits. + +sub RamanujanEI { + if (@_) { + my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. + + my $z_4_term = root4($_1 - pow4($z)); + my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); + + my $z_next_plus_1 = $z_next + $_1; + + my $a_next = pow4($z_next_plus_1) * $a - + $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); + $a_next = round($a_next); + return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; + + } else { # Seed the recurrence + my $a = $_6-$_4*root2($_2); + return [ $a, root2($_2)-$_1, $_8, inv($a)]; + } +} + + + +###################################################################### +# +# Main routine: +# +# + +my $iterResult = RamanujanEI(); +for (my $i=1; $i<$maxIterations; $i++) { + $iterResult = RamanujanEI($iterResult); +} +my $piValue = ${$iterResult}[-1]; +my $piStr = "" . $piValue; + +my $CHUNK = 32; +my $i = $CHUNK + 1; +print "Content-type: text/plain\r\n"; +print "Content-length: 570\r\n\r\n"; +print "Pi_512 :=\n"; +print " " . substr($piValue, 0, $i) . "\n"; +for (; $i < length($piValue) ; $i+=$CHUNK) { + print " " . substr($piValue, $i, $CHUNK) . "\n"; +} + diff --git a/targets/znews-ss_2/system/webpages/www5/cgi-bin/piComputeLib.pl b/targets/znews-ss_2/system/webpages/www5/cgi-bin/piComputeLib.pl index c14fe9400..23ce98e01 100644 --- a/targets/znews-ss_2/system/webpages/www5/cgi-bin/piComputeLib.pl +++ b/targets/znews-ss_2/system/webpages/www5/cgi-bin/piComputeLib.pl @@ -1,233 +1,233 @@ -#!/usr/bin/perl - -#map$x+=(-1)**$_*4/(2*$_+1),0..1e6;die$x - -use strict; -use Carp; -use Math::BigFloat; -use Class::Struct qw(struct); -use Data::Dumper; - -# With due homage to Mathsoft's site: -# http://www.mathsoft.com/asolve/constant/pi/pi.html - -# Set the global precision. Faster than passing it everywhichwhere. -my $precision = @ARGV>0?$ARGV[0]:10; - -# Set the iteration count. -my $maxIterations = @ARGV>1?$ARGV[1]:10; - -# Set the verbose debugging flag. -my $debugVerbose = 0; - -# Constants: -my $_1 = Math::BigFloat->new(1); -my $_2 = Math::BigFloat->new(2); -my $_3 = Math::BigFloat->new(3); -my $_4 = Math::BigFloat->new(4); -my $_6 = Math::BigFloat->new(6); -my $_8 = Math::BigFloat->new(8); -my $_239 = Math::BigFloat->new(239); -my $_half = Math::BigFloat->new(0.5); -my $_fifth = Math::BigFloat->new(0.2); -my $_25th = Math::BigFloat->new(0.04); -my $_239th = inv($_239); -my $_57121th = inv($_239*$_239); - - -# Utility methods: -sub div { - my $a = shift; - my $b = shift; - return new Math::BigFloat $a->copy()->fdiv($b,$precision); -} -sub inv { # Inverse (1/x) function. - my $a = shift; - return new Math::BigFloat $_1->copy()->fdiv($a,$precision); -} -sub root2 { - my $self = shift; - return new Math::BigFloat $self->copy()->fsqrt($precision); -} -sub root4 { - my $self = shift; - return root2(root2($self)); -} -sub pow4 { - my $self = shift; - my $square = round($self*$self); - return round($square*$square); -} -sub round { - my $self = shift; - return new Math::BigFloat $self->copy()->fround($precision); -} - - -# Method 1: - -# This gives Archimedes' approximation, -# 3+10/71 < Pi < 3+1/7 -# ...on the 4th iteration. - -sub BorchardtPfaff { - if (@_) { - my ($a,$b) = @{shift()}; # Retrieve the last iteration. - my $a_next = div( $_2*$a*$b, $a+$b ); - my $b_next = root2($a_next*$b); - return [ round($a_next), round($b_next) ]; - } else { # Seed the recurrence - return [ $_2*root2($_3), $_3 ]; - } -} - -# Method 2: - -# This uses Borwein's AGM method to compute Pi very quickly. -# The 'AGM' is short for the iterated arithmetic-geometric mean; -# which was looked at by Lagrange and Gauss way back in 1799. -# We basically look at the tuple [a,b] which holds the arithmetic -# and geometric means of the previous iteration: -# a[n+1] = (a[n] + b[n])/2 // Arithmetic mean -# b[n+1] = sqrt(a[n] * b[n]) // Geometric mean -# -# This algorithm is neat, since it is quadratically convergent - -# that means that the error goes as 2^(-iteration_count). -# -# In other words, one more step = twice the # of correct digits. - -sub BorweinAGM { - if (@_) { - my ($a,$b,$pi) = @{shift()}; # Retrieve the last iteration. - - my $sqrt_a = root2($a); - my $inv_sqrt_a = inv($sqrt_a); - my $b_plus_1 = $b+$_1; - - my $a_next = $_half * ($sqrt_a+$inv_sqrt_a); - my $b_next = div( $b*$sqrt_a+$inv_sqrt_a , $b_plus_1 ); - my $pi_next = $pi*div( $a_next+$_1 , $b_next+$_1 ); - return [ round($a_next), round($b_next), round($pi_next) ]; - - } else { # Seed the recurrence - my $a0 = root2($_2); - my $pi0 = $_2+root2($_2); - my $b1 = root2($a0); # = root4($_2) - my $a1 = $_half * ($b1 + inv($b1)); - - return [ round($a1), round($b1), round($pi0 * div($a1 + $_1, $b1 + $_1)) ]; - } -} - -# Method 3: - -# The arctangent approximation, as determined by Machin (1706). -# Pi = 4(4 * arctan(1/5) - arctan(1/239)), -# ...where arctan(x) = sum( (-1)^k/(2*k+1)*x^(2*k+1), x=0..infinity). - -sub ArctanPi { - if (@_) { - my ($k, $atan5, $atan239, $denom5, $denom239, $pi) = @{shift()}; # Retrieve the last iteration. - - $k++; - my $parity=$k & 1; - $denom5 = $denom5 * $_25th; - - my $inv_2_k_plus_1='Math::BigFloat'->new(2*$k+1); - - my $term5 = div($denom5, $inv_2_k_plus_1 ); - $denom239 = $denom239 * $_57121th; - - my $term239 = div($denom239, $inv_2_k_plus_1 ); - $atan5 = $parity ? $atan5 - $term5 : $atan5 + $term5; - $atan239 = $parity ? $atan239 - $term239 : $atan239 + $term239; - my $pi = $_4*($_4*$atan5 - $atan239); - - return [ $k, round($atan5), round($atan239), - round($denom5), round($denom239), round($pi) ]; - } else { # Seed the recurrence - my ($k, $atan5, $atan239) = (0, $_fifth, $_239th); - return [ $k, $atan5, $atan239, $atan5, $atan239, $_4*($_4*$atan5 - $atan239)]; - } -} - -# Method 4: - -# This uses Ramanujan's elliptic integral-based technique to -# compute Pi monstrously quickly. -# -# This algorithm is neat, since it is quartically convergent - -# that means that the error goes as 4^(-iteration_count). -# -# In other words, one more step = four times the # of correct digits. - -sub RamanujanEI { - if (@_) { - my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. - - my $z_4_term = root4($_1 - pow4($z)); - my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); - - my $z_next_plus_1 = $z_next + $_1; - - my $a_next = pow4($z_next_plus_1) * $a - - $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); - $a_next = round($a_next); - return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; - - } else { # Seed the recurrence - my $a = $_6-$_4*root2($_2); - return [ $a, root2($_2)-$_1, $_8, inv($a)]; - } -} - - - -###################################################################### -# -# Main routine: -# -# - -my $methods = ["BorchardtPfaff", "ArctanPi", "BorweinAGM", "RamanujanEI" ]; - -my $longestMethodLen=0; -foreach my $method (@{$methods}) { - $longestMethodLen = length($method) if length($method) > $longestMethodLen; -} - -my $pis = [ BorchardtPfaff(), ArctanPi(), BorweinAGM(), RamanujanEI() ]; - -for (my $i=0; $i<$maxIterations; $i++) { - print "Iteration $i:\n"; - if (!$debugVerbose) { - for (my $j=0; $j<@{$methods}; $j++) { - - # The following piece of line noise is equivalent to the - # STL C++, " - - # piValue = pis[j].last(); - - # ", if the declaration for pis is: - - # std::vector > pis; - # - - my $methodName = ${$methods}[$j]; - my $piValue = ${${$pis}[$j]}[-1]; - print ${$methods}[$j] . ": " . - ' ' x ($longestMethodLen - length($methodName)) . - $piValue . "\n"; - } - print "\n"; - } - print(Dumper($pis)) if $debugVerbose; - - last if $i+1 == $maxIterations; - - $pis = [ BorchardtPfaff(${$pis}[0]), - ArctanPi(${$pis}[1]), - BorweinAGM(${$pis}[2]), - RamanujanEI(${$pis}[3]) ]; -} - +#!/usr/bin/perl + +#map$x+=(-1)**$_*4/(2*$_+1),0..1e6;die$x + +use strict; +use Carp; +use Math::BigFloat; +use Class::Struct qw(struct); +use Data::Dumper; + +# With due homage to Mathsoft's site: +# http://www.mathsoft.com/asolve/constant/pi/pi.html + +# Set the global precision. Faster than passing it everywhichwhere. +my $precision = @ARGV>0?$ARGV[0]:10; + +# Set the iteration count. +my $maxIterations = @ARGV>1?$ARGV[1]:10; + +# Set the verbose debugging flag. +my $debugVerbose = 0; + +# Constants: +my $_1 = Math::BigFloat->new(1); +my $_2 = Math::BigFloat->new(2); +my $_3 = Math::BigFloat->new(3); +my $_4 = Math::BigFloat->new(4); +my $_6 = Math::BigFloat->new(6); +my $_8 = Math::BigFloat->new(8); +my $_239 = Math::BigFloat->new(239); +my $_half = Math::BigFloat->new(0.5); +my $_fifth = Math::BigFloat->new(0.2); +my $_25th = Math::BigFloat->new(0.04); +my $_239th = inv($_239); +my $_57121th = inv($_239*$_239); + + +# Utility methods: +sub div { + my $a = shift; + my $b = shift; + return new Math::BigFloat $a->copy()->fdiv($b,$precision); +} +sub inv { # Inverse (1/x) function. + my $a = shift; + return new Math::BigFloat $_1->copy()->fdiv($a,$precision); +} +sub root2 { + my $self = shift; + return new Math::BigFloat $self->copy()->fsqrt($precision); +} +sub root4 { + my $self = shift; + return root2(root2($self)); +} +sub pow4 { + my $self = shift; + my $square = round($self*$self); + return round($square*$square); +} +sub round { + my $self = shift; + return new Math::BigFloat $self->copy()->fround($precision); +} + + +# Method 1: + +# This gives Archimedes' approximation, +# 3+10/71 < Pi < 3+1/7 +# ...on the 4th iteration. + +sub BorchardtPfaff { + if (@_) { + my ($a,$b) = @{shift()}; # Retrieve the last iteration. + my $a_next = div( $_2*$a*$b, $a+$b ); + my $b_next = root2($a_next*$b); + return [ round($a_next), round($b_next) ]; + } else { # Seed the recurrence + return [ $_2*root2($_3), $_3 ]; + } +} + +# Method 2: + +# This uses Borwein's AGM method to compute Pi very quickly. +# The 'AGM' is short for the iterated arithmetic-geometric mean; +# which was looked at by Lagrange and Gauss way back in 1799. +# We basically look at the tuple [a,b] which holds the arithmetic +# and geometric means of the previous iteration: +# a[n+1] = (a[n] + b[n])/2 // Arithmetic mean +# b[n+1] = sqrt(a[n] * b[n]) // Geometric mean +# +# This algorithm is neat, since it is quadratically convergent - +# that means that the error goes as 2^(-iteration_count). +# +# In other words, one more step = twice the # of correct digits. + +sub BorweinAGM { + if (@_) { + my ($a,$b,$pi) = @{shift()}; # Retrieve the last iteration. + + my $sqrt_a = root2($a); + my $inv_sqrt_a = inv($sqrt_a); + my $b_plus_1 = $b+$_1; + + my $a_next = $_half * ($sqrt_a+$inv_sqrt_a); + my $b_next = div( $b*$sqrt_a+$inv_sqrt_a , $b_plus_1 ); + my $pi_next = $pi*div( $a_next+$_1 , $b_next+$_1 ); + return [ round($a_next), round($b_next), round($pi_next) ]; + + } else { # Seed the recurrence + my $a0 = root2($_2); + my $pi0 = $_2+root2($_2); + my $b1 = root2($a0); # = root4($_2) + my $a1 = $_half * ($b1 + inv($b1)); + + return [ round($a1), round($b1), round($pi0 * div($a1 + $_1, $b1 + $_1)) ]; + } +} + +# Method 3: + +# The arctangent approximation, as determined by Machin (1706). +# Pi = 4(4 * arctan(1/5) - arctan(1/239)), +# ...where arctan(x) = sum( (-1)^k/(2*k+1)*x^(2*k+1), x=0..infinity). + +sub ArctanPi { + if (@_) { + my ($k, $atan5, $atan239, $denom5, $denom239, $pi) = @{shift()}; # Retrieve the last iteration. + + $k++; + my $parity=$k & 1; + $denom5 = $denom5 * $_25th; + + my $inv_2_k_plus_1='Math::BigFloat'->new(2*$k+1); + + my $term5 = div($denom5, $inv_2_k_plus_1 ); + $denom239 = $denom239 * $_57121th; + + my $term239 = div($denom239, $inv_2_k_plus_1 ); + $atan5 = $parity ? $atan5 - $term5 : $atan5 + $term5; + $atan239 = $parity ? $atan239 - $term239 : $atan239 + $term239; + my $pi = $_4*($_4*$atan5 - $atan239); + + return [ $k, round($atan5), round($atan239), + round($denom5), round($denom239), round($pi) ]; + } else { # Seed the recurrence + my ($k, $atan5, $atan239) = (0, $_fifth, $_239th); + return [ $k, $atan5, $atan239, $atan5, $atan239, $_4*($_4*$atan5 - $atan239)]; + } +} + +# Method 4: + +# This uses Ramanujan's elliptic integral-based technique to +# compute Pi monstrously quickly. +# +# This algorithm is neat, since it is quartically convergent - +# that means that the error goes as 4^(-iteration_count). +# +# In other words, one more step = four times the # of correct digits. + +sub RamanujanEI { + if (@_) { + my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. + + my $z_4_term = root4($_1 - pow4($z)); + my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); + + my $z_next_plus_1 = $z_next + $_1; + + my $a_next = pow4($z_next_plus_1) * $a - + $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); + $a_next = round($a_next); + return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; + + } else { # Seed the recurrence + my $a = $_6-$_4*root2($_2); + return [ $a, root2($_2)-$_1, $_8, inv($a)]; + } +} + + + +###################################################################### +# +# Main routine: +# +# + +my $methods = ["BorchardtPfaff", "ArctanPi", "BorweinAGM", "RamanujanEI" ]; + +my $longestMethodLen=0; +foreach my $method (@{$methods}) { + $longestMethodLen = length($method) if length($method) > $longestMethodLen; +} + +my $pis = [ BorchardtPfaff(), ArctanPi(), BorweinAGM(), RamanujanEI() ]; + +for (my $i=0; $i<$maxIterations; $i++) { + print "Iteration $i:\n"; + if (!$debugVerbose) { + for (my $j=0; $j<@{$methods}; $j++) { + + # The following piece of line noise is equivalent to the + # STL C++, " + + # piValue = pis[j].last(); + + # ", if the declaration for pis is: + + # std::vector > pis; + # + + my $methodName = ${$methods}[$j]; + my $piValue = ${${$pis}[$j]}[-1]; + print ${$methods}[$j] . ": " . + ' ' x ($longestMethodLen - length($methodName)) . + $piValue . "\n"; + } + print "\n"; + } + print(Dumper($pis)) if $debugVerbose; + + last if $i+1 == $maxIterations; + + $pis = [ BorchardtPfaff(${$pis}[0]), + ArctanPi(${$pis}[1]), + BorweinAGM(${$pis}[2]), + RamanujanEI(${$pis}[3]) ]; +} + diff --git a/targets/znews-ss_2/system/webpages/www5/index.php b/targets/znews-ss_2/system/webpages/www5/index.php index 6c66bd469..b3b52ea5e 100644 --- a/targets/znews-ss_2/system/webpages/www5/index.php +++ b/targets/znews-ss_2/system/webpages/www5/index.php @@ -1,84 +1,84 @@ - 1 && time()%$content == 0) { - echo << - -Please come back... - - -I (the server) am swamped right now!!
-Please kindly come back in a couple of minutes.
-Sorry for the inconvenience, and thanks for understanding! - - -REJECT; - exit(); -} - -/* -$mysql_url = ''; -$mysql_user = ''; -$mysql_password = ''; -$mysql_db = ''; - -$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) - or die('Could not connect: ' . mysql_error()); - -$mydb = mysql_select_db($mysql_db, $link); -if(!$mydb) { - die('Could not select Test database: ' . mysql_error()); -} - -// Performing SQL query -$query = "SELECT COUNT(*) FROM cur"; -$result = mysql_query($query, $link) - or die('Query COUNT failed: ' . mysql_error()); -$row = mysql_fetch_row($result); -if ($row != false) { - $numItems = $row[0]; -} - -$idx = rand(1, $numItems); -$query = "SELECT cur_text FROM cur LIMIT $idx,1"; -$result = mysql_query($query, $link) - or die('Query item $idx failed: ' . mysql_error()); -$row = mysql_fetch_row($result); -if($row != false) { - $text = $row[0]; -} -*/ -$idx = 0; -$text = ""; - -echo << - -Somewhere Over the Rainbow - - - -

Z.com News - Hello World! (High-fidelity Settings)

-This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. - - - - -END - -?> + 1 && time()%$content == 0) { + echo << + +Please come back... + + +I (the server) am swamped right now!!
+Please kindly come back in a couple of minutes.
+Sorry for the inconvenience, and thanks for understanding! + + +REJECT; + exit(); +} + +/* +$mysql_url = ''; +$mysql_user = ''; +$mysql_password = ''; +$mysql_db = ''; + +$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) + or die('Could not connect: ' . mysql_error()); + +$mydb = mysql_select_db($mysql_db, $link); +if(!$mydb) { + die('Could not select Test database: ' . mysql_error()); +} + +// Performing SQL query +$query = "SELECT COUNT(*) FROM cur"; +$result = mysql_query($query, $link) + or die('Query COUNT failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if ($row != false) { + $numItems = $row[0]; +} + +$idx = rand(1, $numItems); +$query = "SELECT cur_text FROM cur LIMIT $idx,1"; +$result = mysql_query($query, $link) + or die('Query item $idx failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if($row != false) { + $text = $row[0]; +} +*/ +$idx = 0; +$text = ""; + +echo << + +Somewhere Over the Rainbow + + + +

Z.com News - Hello World! (High-fidelity Settings)

+This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. + + + + +END + +?> diff --git a/targets/znews0/model/TargetEnv.acme b/targets/znews0/model/TargetEnv.acme index 4331c55b7..2ec6be259 100644 --- a/targets/znews0/model/TargetEnv.acme +++ b/targets/znews0/model/TargetEnv.acme @@ -1,4 +1,4 @@ -System TargetEnv = { - -} - +System TargetEnv = { + +} + diff --git a/targets/znews0/model/TargetEnvType.acme b/targets/znews0/model/TargetEnvType.acme index a91a99173..91e499a0e 100644 --- a/targets/znews0/model/TargetEnvType.acme +++ b/targets/znews0/model/TargetEnvType.acme @@ -1,67 +1,67 @@ -Family EnvType = { - - Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; - - Role Type ArchRoleT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type PartPortT = { - - } - Component Type ArchElementT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type NetworkRoleT = { - - } - Connector Type MappingT = { - - } - Role Type PartRoleT = { - - } - Connector Type EdgeT = { - - Property bandwidthAvg : ResourceStatePropT; - - Property capacity : ResourceStatePropT; - - } - Component Type NodeT = { - - Property cpuOverall : ResourceStatePropT; - - Property memoryMain : ResourceStatePropT; - - Property storageLocal : ResourceStatePropT; - - Property socketPool : ResourceStatePropT; - - Property batteryOverall : ResourceStatePropT; - - } - Port Type NetworkPortT = { - - } - Connector Type ArchConnT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type ArchPortT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type ContainerRoleT = { - - } - Port Type ContainmentPortT = { - - } -} - +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type PartPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type NetworkRoleT = { + + } + Connector Type MappingT = { + + } + Role Type PartRoleT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Port Type NetworkPortT = { + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type ContainerRoleT = { + + } + Port Type ContainmentPortT = { + + } +} + diff --git a/targets/znews0/model/TargetEnvType.mtd b/targets/znews0/model/TargetEnvType.mtd index 6817ebfa8..9d8d87f85 100644 --- a/targets/znews0/model/TargetEnvType.mtd +++ b/targets/znews0/model/TargetEnvType.mtd @@ -1,475 +1,475 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews0/model/ZNewsSys.acme b/targets/znews0/model/ZNewsSys.acme index 5c6a74236..82a17ba0f 100644 --- a/targets/znews0/model/ZNewsSys.acme +++ b/targets/znews0/model/ZNewsSys.acme @@ -1,391 +1,391 @@ -import TargetEnvType.acme; - -Family ZNewsFam extends EnvType with { - - Port Type HttpPortT extends ArchPortT with { - - } - Role Type RequestorRoleT extends ArchRoleT with { - - } - Component Type ProxyT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - } - Port Type ProxyForwardPortT extends ArchPortT with { - - } - Component Type ServerT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - Property reqServiceRate : float << default : float = 0.0; >> ; - - Property byteServiceRate : float << default : float = 0.0; >> ; - - Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; - - Property cost : float << default : float = 1.0; >> ; - - Property lastPageHit : Record [uri : string; cnt : int; kbytes : float; ]; - - Property anotherConstraint : string << default : string = "heuristic self.load <= MAX_UTIL;"; >> ; - - } - Role Type ReceiverRoleT extends ArchRoleT with { - - } - Connector Type ProxyConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - Component Type ClientT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property experRespTime : float << default : float = 100.0; >> ; - - Property reqRate : float << default : float = 0.0; >> ; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - rule reverseConstraint = heuristic self.experRespTime >= MIN_RESPTIME; - - } - Port Type HttpReqPortT extends ArchPortT with { - - } - Connector Type HttpConnT extends ArchConnT with { - - Property bandwidth : float << default : float = 0.0; >> ; - - Property latency : float << default : float = 0.0; >> ; - - Property numReqsSuccess : int << default : int = 0; >> ; - - Property numReqsRedirect : int << default : int = 0; >> ; - - Property numReqsClientError : int << default : int = 0; >> ; - - Property numReqsServerError : int << default : int = 0; >> ; - - Property latencyRate : float; - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - - Property MIN_RESPTIME : float; - - Property MAX_RESPTIME : float; - - Property TOLERABLE_PERCENT_UNHAPPY : float; - - Property UNHAPPY_GRADIENT_1 : float; - - Property UNHAPPY_GRADIENT_2 : float; - - Property UNHAPPY_GRADIENT_3 : float; - - Property FRACTION_GRADIENT_1 : float; - - Property FRACTION_GRADIENT_2 : float; - - Property FRACTION_GRADIENT_3 : float; - - Property MIN_UTIL : float; - - Property MAX_UTIL : float; - - Property MAX_FIDELITY_LEVEL : int; - - Property THRESHOLD_FIDELITY : int; - - Property THRESHOLD_COST : float; - - Property SUPPORT_FRACTION_GRADIENT : boolean; -} - -System ZNewsSys : ZNewsFam = { - - - Property MIN_RESPTIME : float = 100.0; - - Property MAX_RESPTIME : float = 1000.0; - - Property UNHAPPY_GRADIENT_1 : float = 0.1; - - Property UNHAPPY_GRADIENT_2 : float = 0.2; - - Property UNHAPPY_GRADIENT_3 : float = 0.5; - - Property FRACTION_GRADIENT_1 : float = 0.2; - - Property FRACTION_GRADIENT_2 : float = 0.4; - - Property FRACTION_GRADIENT_3 : float = 1.0; - - Property TOLERABLE_PERCENT_UNHAPPY : float = 0.4; - - Property MIN_UTIL : float = 0.1; - - Property MAX_UTIL : float = 0.75; - - Property MAX_FIDELITY_LEVEL : int = 5; - - Property THRESHOLD_FIDELITY : int = 2; - - Property THRESHOLD_COST : float = 4.0; - - Property SUPPORT_FRACTION_GRADIENT : boolean = false; - Component s1 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - - Property deploymentLocation = "phoenix"; - - Property isArchEnabled = true; - - Property cost = 1.0; - - Property fidelity = 5; - - Property load = 1.485; - Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { - - } - - } - Component lbproxy : ProxyT = new ProxyT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property isArchEnabled = true; - - Property load = 0.01; - Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - Property isArchEnabled = true; - - } - Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port http0 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - Port http1 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - Port http2 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - - } - Component s2 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - - Property deploymentLocation = "127.0.0.3"; - - Property isArchEnabled = true; - - Property fidelity = 3; - - Property load = 0.594; - - Property cost = 1.0; - Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { - - Property isArchEnabled = false; - - } - - } - Component s3 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - - Property deploymentLocation = "127.0.0.4"; - - Property isArchEnabled = true; - - Property cost = 1.0; - - Property fidelity = 3; - - Property load = 0.891; - Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { - - } - - } - Component s0 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - - Property deploymentLocation = "oracle"; - - Property cost = 0.9; - - Property fidelity = 3; - - Property load = 0.198; - - Property isArchEnabled = true; - Port http0 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - - } - Component c1 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property isArchEnabled = true; - - Property experRespTime = 2609.5415; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - } - Component c2 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property isArchEnabled = true; - - Property experRespTime = 2520.8613; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - } - Component c0 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property isArchEnabled = true; - - Property experRespTime = 2590.9473; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - } - Connector conn0 : HttpConnT = new HttpConnT extended with { - - Property latencyRate = 0.0; - - Property isArchEnabled = true; - Role req = { - - Property isArchEnabled = true; - - } - Role rec = { - - Property isArchEnabled = true; - - } - - } - Connector proxyconn0 : ProxyConnT = new ProxyConnT extended with { - - Property isArchEnabled = true; - Role req = { - - Property isArchEnabled = true; - - } - Role rec = { - - Property isArchEnabled = true; - - } - - } - Connector proxyconn1 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { - - } - Connector proxyconn3 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { - - } - Connector proxyconn2 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { - - } - Connector conn : HttpConnT = new HttpConnT extended with { - - Property latencyRate = 0.0; - - Property isArchEnabled = true; - Role req = { - - Property isArchEnabled = true; - - } - Role rec = { - - Property isArchEnabled = true; - - } - - } - Connector conn1 : HttpConnT = new HttpConnT extended with { - - Property latencyRate = 0.0; - - Property isArchEnabled = true; - Role req = { - - Property isArchEnabled = true; - - } - Role rec = { - - Property isArchEnabled = true; - - } - - } - Attachment lbproxy.fwd0 to proxyconn0.req; - Attachment s0.http0 to proxyconn0.rec; - Attachment lbproxy.http0 to conn0.rec; - Attachment c1.p0 to conn.req; - Attachment c2.p0 to conn1.req; - Attachment lbproxy.http2 to conn1.rec; - Attachment lbproxy.http1 to conn.rec; - Attachment c0.p0 to conn0.req; - Attachment s2.http0 to proxyconn2.rec; - Attachment lbproxy.fwd1 to proxyconn1.req; - Attachment s1.http0 to proxyconn1.rec; - Attachment s3.http0 to proxyconn3.rec; - Attachment lbproxy.fwd3 to proxyconn3.req; - Attachment lbproxy.fwd2 to proxyconn2.req; -} - +import TargetEnvType.acme; + +Family ZNewsFam extends EnvType with { + + Port Type HttpPortT extends ArchPortT with { + + } + Role Type RequestorRoleT extends ArchRoleT with { + + } + Component Type ProxyT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Port Type ProxyForwardPortT extends ArchPortT with { + + } + Component Type ServerT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + Property reqServiceRate : float << default : float = 0.0; >> ; + + Property byteServiceRate : float << default : float = 0.0; >> ; + + Property fidelity : int << HIGH : int = 5; LOW : int = 1; default : int = 5; >> ; + + Property cost : float << default : float = 1.0; >> ; + + Property lastPageHit : Record [uri : string; cnt : int; kbytes : float; ]; + + Property anotherConstraint : string << default : string = "heuristic self.load <= MAX_UTIL;"; >> ; + + } + Role Type ReceiverRoleT extends ArchRoleT with { + + } + Connector Type ProxyConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Component Type ClientT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property experRespTime : float << default : float = 100.0; >> ; + + Property reqRate : float << default : float = 0.0; >> ; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + rule reverseConstraint = heuristic self.experRespTime >= MIN_RESPTIME; + + } + Port Type HttpReqPortT extends ArchPortT with { + + } + Connector Type HttpConnT extends ArchConnT with { + + Property bandwidth : float << default : float = 0.0; >> ; + + Property latency : float << default : float = 0.0; >> ; + + Property numReqsSuccess : int << default : int = 0; >> ; + + Property numReqsRedirect : int << default : int = 0; >> ; + + Property numReqsClientError : int << default : int = 0; >> ; + + Property numReqsServerError : int << default : int = 0; >> ; + + Property latencyRate : float; + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + + Property MIN_RESPTIME : float; + + Property MAX_RESPTIME : float; + + Property TOLERABLE_PERCENT_UNHAPPY : float; + + Property UNHAPPY_GRADIENT_1 : float; + + Property UNHAPPY_GRADIENT_2 : float; + + Property UNHAPPY_GRADIENT_3 : float; + + Property FRACTION_GRADIENT_1 : float; + + Property FRACTION_GRADIENT_2 : float; + + Property FRACTION_GRADIENT_3 : float; + + Property MIN_UTIL : float; + + Property MAX_UTIL : float; + + Property MAX_FIDELITY_LEVEL : int; + + Property THRESHOLD_FIDELITY : int; + + Property THRESHOLD_COST : float; + + Property SUPPORT_FRACTION_GRADIENT : boolean; +} + +System ZNewsSys : ZNewsFam = { + + + Property MIN_RESPTIME : float = 100.0; + + Property MAX_RESPTIME : float = 1000.0; + + Property UNHAPPY_GRADIENT_1 : float = 0.1; + + Property UNHAPPY_GRADIENT_2 : float = 0.2; + + Property UNHAPPY_GRADIENT_3 : float = 0.5; + + Property FRACTION_GRADIENT_1 : float = 0.2; + + Property FRACTION_GRADIENT_2 : float = 0.4; + + Property FRACTION_GRADIENT_3 : float = 1.0; + + Property TOLERABLE_PERCENT_UNHAPPY : float = 0.4; + + Property MIN_UTIL : float = 0.1; + + Property MAX_UTIL : float = 0.75; + + Property MAX_FIDELITY_LEVEL : int = 5; + + Property THRESHOLD_FIDELITY : int = 2; + + Property THRESHOLD_COST : float = 4.0; + + Property SUPPORT_FRACTION_GRADIENT : boolean = false; + Component s1 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + + Property deploymentLocation = "phoenix"; + + Property isArchEnabled = true; + + Property cost = 1.0; + + Property fidelity = 5; + + Property load = 1.485; + Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { + + } + + } + Component lbproxy : ProxyT = new ProxyT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property isArchEnabled = true; + + Property load = 0.01; + Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + Property isArchEnabled = true; + + } + Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port http0 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + Port http1 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + Port http2 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + + } + Component s2 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + + Property deploymentLocation = "127.0.0.3"; + + Property isArchEnabled = true; + + Property fidelity = 3; + + Property load = 0.594; + + Property cost = 1.0; + Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { + + Property isArchEnabled = false; + + } + + } + Component s3 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + + Property deploymentLocation = "127.0.0.4"; + + Property isArchEnabled = true; + + Property cost = 1.0; + + Property fidelity = 3; + + Property load = 0.891; + Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { + + } + + } + Component s0 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + + Property deploymentLocation = "oracle"; + + Property cost = 0.9; + + Property fidelity = 3; + + Property load = 0.198; + + Property isArchEnabled = true; + Port http0 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + + } + Component c1 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property isArchEnabled = true; + + Property experRespTime = 2609.5415; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + } + Component c2 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property isArchEnabled = true; + + Property experRespTime = 2520.8613; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + } + Component c0 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property isArchEnabled = true; + + Property experRespTime = 2590.9473; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + } + Connector conn0 : HttpConnT = new HttpConnT extended with { + + Property latencyRate = 0.0; + + Property isArchEnabled = true; + Role req = { + + Property isArchEnabled = true; + + } + Role rec = { + + Property isArchEnabled = true; + + } + + } + Connector proxyconn0 : ProxyConnT = new ProxyConnT extended with { + + Property isArchEnabled = true; + Role req = { + + Property isArchEnabled = true; + + } + Role rec = { + + Property isArchEnabled = true; + + } + + } + Connector proxyconn1 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { + + } + Connector proxyconn3 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { + + } + Connector proxyconn2 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { + + } + Connector conn : HttpConnT = new HttpConnT extended with { + + Property latencyRate = 0.0; + + Property isArchEnabled = true; + Role req = { + + Property isArchEnabled = true; + + } + Role rec = { + + Property isArchEnabled = true; + + } + + } + Connector conn1 : HttpConnT = new HttpConnT extended with { + + Property latencyRate = 0.0; + + Property isArchEnabled = true; + Role req = { + + Property isArchEnabled = true; + + } + Role rec = { + + Property isArchEnabled = true; + + } + + } + Attachment lbproxy.fwd0 to proxyconn0.req; + Attachment s0.http0 to proxyconn0.rec; + Attachment lbproxy.http0 to conn0.rec; + Attachment c1.p0 to conn.req; + Attachment c2.p0 to conn1.req; + Attachment lbproxy.http2 to conn1.rec; + Attachment lbproxy.http1 to conn.rec; + Attachment c0.p0 to conn0.req; + Attachment s2.http0 to proxyconn2.rec; + Attachment lbproxy.fwd1 to proxyconn1.req; + Attachment s1.http0 to proxyconn1.rec; + Attachment s3.http0 to proxyconn3.rec; + Attachment lbproxy.fwd3 to proxyconn3.req; + Attachment lbproxy.fwd2 to proxyconn2.req; +} + diff --git a/targets/znews0/model/ZNewsSys.mtd b/targets/znews0/model/ZNewsSys.mtd index 19ab6545c..76c83b82f 100644 --- a/targets/znews0/model/ZNewsSys.mtd +++ b/targets/znews0/model/ZNewsSys.mtd @@ -1,493 +1,493 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews0/rainbow.properties b/targets/znews0/rainbow.properties index 9640707c1..5dabe06a0 100644 --- a/targets/znews0/rainbow.properties +++ b/targets/znews0/rainbow.properties @@ -1,70 +1,70 @@ -################################################################################ -# Purpose: Configuration file for the Rainbow infrastructure, used by "Rainbow" -# Target: ZNews case study system with Gauges and Effectors implemented -# (rainbow.target = znews0) -# -# History: see non-target-specific copy -################################################################################ - -### Utility mechanism configuration -#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL -#logging.level = DEBUG -logging.level = INFO -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log -# (default) -#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" -#logging.max.size = 1024 -#logging.max.backups = 5 - -# The location information of the master and this deployment -rainbow.master.location.host = 127.0.0.1 -#- Location information of the deployed delegate -rainbow.deployment.location = ${rainbow.master.location.host} -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = cygwin -#- Event infrastructure, type of event middleware: rmi | jms | que -rainbow.event.service = que -#- JMS/JBoss-specific configurations -#event.context.factory = org.jnp.interfaces.NamingContextFactory -#event.provider.url = ${rainbow.master.location.host}:1099 -#event.url.prefixes = org.jboss.naming:org.jnp.interfaces - -# Delegate and ProbeBusRelay configurations -rainbow.delegate.id = RainbowDelegate@${rainbow.deployment.location} -rainbow.delegate.beaconperiod = 5000 -probebus.relay.id = ProbeBusRelay@${rainbow.deployment.location} -#- uncomment to enable file-based communication with the ProbeBus Relay -#probebus.relay.file = ${event.log.path}/relay.log - -customize.model.path = model/ZNewsSys.acme -customize.model.persist = false -#- Alpha factor for exponential average of properties, expAvg = (1-alpha)*expAvg + alpha*newVal -customize.model.expavg.alpha = 0.30 -customize.model.evaluate.period = 2000 -customize.archop.map.path = model/op.map -customize.scripts.path = stitch -#- Utilities description file, Strategy evaluation config, and minimum score threshold -customize.utility.path = stitch/utilities.yml -customize.utility.score.minimum.threshold = 0.33 -customize.utility.scenario = scenario 3 -#- Whether to enable prediction, ONLY enable if system has predictor probes! -#customize.prediction.enable = false - -## System configuration information -# -#customize.system.sim.path = znews/znews.sim -#customize.system.sim.path = znews/znews-brute.sim -#customize.system.sim.path = znews/znews-varied.sim -#customize.system.sim.path = znews/znews-smarter.sim -#customize.system.sim.path = znews/znews-smarter2.sim -#customize.system.sim.path = znews/znews-smarter3.sim -#customize.system.sim.path = znews/znews-reducecost.sim -#customize.system.sim.path = znews/znews-improvefidelity.sim -customize.system.sim.path = znews/znews-oscillating.sim +################################################################################ +# Purpose: Configuration file for the Rainbow infrastructure, used by "Rainbow" +# Target: ZNews case study system with Gauges and Effectors implemented +# (rainbow.target = znews0) +# +# History: see non-target-specific copy +################################################################################ + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +#logging.level = DEBUG +logging.level = INFO +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +# The location information of the master and this deployment +rainbow.master.location.host = 127.0.0.1 +#- Location information of the deployed delegate +rainbow.deployment.location = ${rainbow.master.location.host} +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = cygwin +#- Event infrastructure, type of event middleware: rmi | jms | que +rainbow.event.service = que +#- JMS/JBoss-specific configurations +#event.context.factory = org.jnp.interfaces.NamingContextFactory +#event.provider.url = ${rainbow.master.location.host}:1099 +#event.url.prefixes = org.jboss.naming:org.jnp.interfaces + +# Delegate and ProbeBusRelay configurations +rainbow.delegate.id = RainbowDelegate@${rainbow.deployment.location} +rainbow.delegate.beaconperiod = 5000 +probebus.relay.id = ProbeBusRelay@${rainbow.deployment.location} +#- uncomment to enable file-based communication with the ProbeBus Relay +#probebus.relay.file = ${event.log.path}/relay.log + +customize.model.path = model/ZNewsSys.acme +customize.model.persist = false +#- Alpha factor for exponential average of properties, expAvg = (1-alpha)*expAvg + alpha*newVal +customize.model.expavg.alpha = 0.30 +customize.model.evaluate.period = 2000 +customize.archop.map.path = model/op.map +customize.scripts.path = stitch +#- Utilities description file, Strategy evaluation config, and minimum score threshold +customize.utility.path = stitch/utilities.yml +customize.utility.score.minimum.threshold = 0.33 +customize.utility.scenario = scenario 3 +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# +#customize.system.sim.path = znews/znews.sim +#customize.system.sim.path = znews/znews-brute.sim +#customize.system.sim.path = znews/znews-varied.sim +#customize.system.sim.path = znews/znews-smarter.sim +#customize.system.sim.path = znews/znews-smarter2.sim +#customize.system.sim.path = znews/znews-smarter3.sim +#customize.system.sim.path = znews/znews-reducecost.sim +#customize.system.sim.path = znews/znews-improvefidelity.sim +customize.system.sim.path = znews/znews-oscillating.sim diff --git a/targets/znews0/stitch/newssiteStrategies.s b/targets/znews0/stitch/newssiteStrategies.s index 26a8e977b..ce3a93185 100644 --- a/targets/znews0/stitch/newssiteStrategies.s +++ b/targets/znews0/stitch/newssiteStrategies.s @@ -1,153 +1,153 @@ -/* - * Adaptation script for the News Site example. - */ - -module newssite.strategies; - -import lib "newssiteTactics.s"; - -define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); -define boolean cViolation = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - -define set servers = {select s : T.ServerT in M.components | true}; -define set unhappyClients = {select c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME}; -define int numClients = Set.size({select c : T.ClientT in M.components | true}); -define int numUnhappy = Set.size(unhappyClients); -define float numUnhappyFloat = 1.0*numUnhappy; - -define boolean hiLoad = exists s : T.ServerT in M.components | s.load > M.MAX_UTIL; -define boolean hiRespTime = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; -define boolean lowRespTime = exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - -define float totalCost = Model.sumOverProperty("cost", servers); -define boolean hiCost = totalCost >= M.THRESHOLD_COST; - -define float avgFidelity = Model.sumOverProperty("fidelity", servers) / Set.size(servers); -define boolean lowFi = avgFidelity < M.THRESHOLD_FIDELITY; - - -/* For baseline, this Strategy drops the fidelity one notch, and that's it. - * In the presence of Brute, this strategy probably won't ever get picked. - */ -strategy QuickDirtyReduceResponseTime -[ styleApplies && cViolation ] { - t0: (/*hiLoad*/ cViolation) -> lowerFidelity(2, 100) @[2000 /*ms*/] { - t1: (!cViolation) -> done; - } -} - -/* This Strategy will drop fidelity once, observe, then drop again if necessary. - * - * Note: Tested successfully in simulation, znews-brute - */ -strategy BruteReduceResponseTime -[ styleApplies && cViolation ] { - t0: (/*hiLoad*/ cViolation) -> lowerFidelity(2, 100) @[5000 /*ms*/] { - t1: (!cViolation) -> done; - t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[8000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> TNULL; // in this case, we have no more steps to take - } - } -} - -/* This Strategy is simple in that, while it encounters any anomaly in - * experienced response time, it firsts enlists one new server, then lowers - * fidelity one step, and quits - * - * Note: Tested successfully in simulation, znews-varied - */ -strategy VariedReduceResponseTime -[ styleApplies && cViolation ] { - t0: (/*hiLoad*/ cViolation) -> enlistServers(1) @[1000 /*ms*/] { - t1: (!cViolation) -> done; - t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[3000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> TNULL; // in this case, we have no more steps to take - } - } -} - -/* This Strategy is smarter in that it looks for a percentage of clients with - * anomalous experienced response time, in which case it enlists a few servers - * in sequence, then lowers fidelity a few steps, then repeats both once. - * - * Note: Tested successfully in simulation, znews-smarter/2/3 - */ -strategy SmarterReduceResponseTime -[ styleApplies && cViolation ] { - define boolean unhappy = numUnhappyFloat/numClients > M.TOLERABLE_PERCENT_UNHAPPY; - - t0: (unhappy) -> enlistServers(1) @[500 /*ms*/] { - t1: (!cViolation) -> done; - t2: (unhappy) -> enlistServers(1) @[2000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (unhappy) -> lowerFidelity(2, 100) @[2000 /*ms*/] { - t2b1: (!cViolation) -> done; - t2b2: (unhappy) -> do[1] t2; - t2b3: (default) -> TNULL; // in this case, we have no more steps to take - } - } - } -} - -/* This Strategy (experimental!) has the sophistication of reducing fidelity - * for a percentage of requests depending on percentage of unhappy clients - * - * Note: Tested ?? in simulation, znews-? - */ -strategy SophisticatedReduceResponseTime -[ styleApplies && cViolation && M.SUPPORT_FRACTION_GRADIENT ] { - define boolean unhappy1 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_1; // e.g., 10% - define boolean unhappy2 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_2; // e.g., 25% - define boolean unhappy3 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_3; // e.g., 50% - - t1: (hiLoad) -> enlistServers(2) @[500 /*ms*/] { - t1a: (!cViolation) -> done; - t1b: (default) -> TNULL; - } - t2: (unhappy1) -> lowerFidelity(1, M.FRACTION_GRADIENT_1) @[500 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> do[1] t1; - } - t3: (unhappy2) -> lowerFidelity(2, M.FRACTION_GRADIENT_2) @[500 /*ms*/] { - t3a: (!cViolation) -> done; - t3b: (default) -> do[1] t1; - } - t4: (unhappy3) -> lowerFidelity(4, M.FRACTION_GRADIENT_3) @[500 /*ms*/] { - t4a: (!cViolation) -> done; - t4b: (unhappy3) -> enlistServers(2) @[1000 /*ms*/] { - t4b1: (!cViolation) -> done; - t4b2: (default) -> do[1] t1; - } - t4c: (default) -> do[1] t1; - } -} - -/* This Strategy is triggered by the total server costs rising above acceptable - * threshold; this Strategy reduces the number of active servers - * - * Note: Tested successfully in simulation, znews-reducecost + znews-improvefidelity - */ -strategy ReduceOverallCost -[ styleApplies && hiCost ] { - t0: (hiCost) -> dischargeServers(1) @[2000 /*ms*/] { - t1: (!hiCost) -> done; - t2: (lowRespTime && hiCost) -> do[2] t0; - t3: (default) -> TNULL; - } -} - -/* This Strategy is triggered by overall fidelity being below acceptable - * threshold; this Strategy raises the fidelity of the servers - * - * Note: Tested successfully in simulation, znews-improvefidelity - */ -strategy ImproveOverallFidelity -[ styleApplies && lowFi ] { - t0: (lowFi) -> raiseFidelity(2, 100) @[800 /*ms*/] { - t1: (!lowFi) -> done; - t2: (lowRespTime && lowFi) -> do[1] t0; - t3: (default) -> TNULL; - } -} +/* + * Adaptation script for the News Site example. + */ + +module newssite.strategies; + +import lib "newssiteTactics.s"; + +define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); +define boolean cViolation = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + +define set servers = {select s : T.ServerT in M.components | true}; +define set unhappyClients = {select c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME}; +define int numClients = Set.size({select c : T.ClientT in M.components | true}); +define int numUnhappy = Set.size(unhappyClients); +define float numUnhappyFloat = 1.0*numUnhappy; + +define boolean hiLoad = exists s : T.ServerT in M.components | s.load > M.MAX_UTIL; +define boolean hiRespTime = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; +define boolean lowRespTime = exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + +define float totalCost = Model.sumOverProperty("cost", servers); +define boolean hiCost = totalCost >= M.THRESHOLD_COST; + +define float avgFidelity = Model.sumOverProperty("fidelity", servers) / Set.size(servers); +define boolean lowFi = avgFidelity < M.THRESHOLD_FIDELITY; + + +/* For baseline, this Strategy drops the fidelity one notch, and that's it. + * In the presence of Brute, this strategy probably won't ever get picked. + */ +strategy QuickDirtyReduceResponseTime +[ styleApplies && cViolation ] { + t0: (/*hiLoad*/ cViolation) -> lowerFidelity(2, 100) @[2000 /*ms*/] { + t1: (!cViolation) -> done; + } +} + +/* This Strategy will drop fidelity once, observe, then drop again if necessary. + * + * Note: Tested successfully in simulation, znews-brute + */ +strategy BruteReduceResponseTime +[ styleApplies && cViolation ] { + t0: (/*hiLoad*/ cViolation) -> lowerFidelity(2, 100) @[5000 /*ms*/] { + t1: (!cViolation) -> done; + t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[8000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> TNULL; // in this case, we have no more steps to take + } + } +} + +/* This Strategy is simple in that, while it encounters any anomaly in + * experienced response time, it firsts enlists one new server, then lowers + * fidelity one step, and quits + * + * Note: Tested successfully in simulation, znews-varied + */ +strategy VariedReduceResponseTime +[ styleApplies && cViolation ] { + t0: (/*hiLoad*/ cViolation) -> enlistServers(1) @[1000 /*ms*/] { + t1: (!cViolation) -> done; + t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[3000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> TNULL; // in this case, we have no more steps to take + } + } +} + +/* This Strategy is smarter in that it looks for a percentage of clients with + * anomalous experienced response time, in which case it enlists a few servers + * in sequence, then lowers fidelity a few steps, then repeats both once. + * + * Note: Tested successfully in simulation, znews-smarter/2/3 + */ +strategy SmarterReduceResponseTime +[ styleApplies && cViolation ] { + define boolean unhappy = numUnhappyFloat/numClients > M.TOLERABLE_PERCENT_UNHAPPY; + + t0: (unhappy) -> enlistServers(1) @[500 /*ms*/] { + t1: (!cViolation) -> done; + t2: (unhappy) -> enlistServers(1) @[2000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (unhappy) -> lowerFidelity(2, 100) @[2000 /*ms*/] { + t2b1: (!cViolation) -> done; + t2b2: (unhappy) -> do[1] t2; + t2b3: (default) -> TNULL; // in this case, we have no more steps to take + } + } + } +} + +/* This Strategy (experimental!) has the sophistication of reducing fidelity + * for a percentage of requests depending on percentage of unhappy clients + * + * Note: Tested ?? in simulation, znews-? + */ +strategy SophisticatedReduceResponseTime +[ styleApplies && cViolation && M.SUPPORT_FRACTION_GRADIENT ] { + define boolean unhappy1 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_1; // e.g., 10% + define boolean unhappy2 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_2; // e.g., 25% + define boolean unhappy3 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_3; // e.g., 50% + + t1: (hiLoad) -> enlistServers(2) @[500 /*ms*/] { + t1a: (!cViolation) -> done; + t1b: (default) -> TNULL; + } + t2: (unhappy1) -> lowerFidelity(1, M.FRACTION_GRADIENT_1) @[500 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> do[1] t1; + } + t3: (unhappy2) -> lowerFidelity(2, M.FRACTION_GRADIENT_2) @[500 /*ms*/] { + t3a: (!cViolation) -> done; + t3b: (default) -> do[1] t1; + } + t4: (unhappy3) -> lowerFidelity(4, M.FRACTION_GRADIENT_3) @[500 /*ms*/] { + t4a: (!cViolation) -> done; + t4b: (unhappy3) -> enlistServers(2) @[1000 /*ms*/] { + t4b1: (!cViolation) -> done; + t4b2: (default) -> do[1] t1; + } + t4c: (default) -> do[1] t1; + } +} + +/* This Strategy is triggered by the total server costs rising above acceptable + * threshold; this Strategy reduces the number of active servers + * + * Note: Tested successfully in simulation, znews-reducecost + znews-improvefidelity + */ +strategy ReduceOverallCost +[ styleApplies && hiCost ] { + t0: (hiCost) -> dischargeServers(1) @[2000 /*ms*/] { + t1: (!hiCost) -> done; + t2: (lowRespTime && hiCost) -> do[2] t0; + t3: (default) -> TNULL; + } +} + +/* This Strategy is triggered by overall fidelity being below acceptable + * threshold; this Strategy raises the fidelity of the servers + * + * Note: Tested successfully in simulation, znews-improvefidelity + */ +strategy ImproveOverallFidelity +[ styleApplies && lowFi ] { + t0: (lowFi) -> raiseFidelity(2, 100) @[800 /*ms*/] { + t1: (!lowFi) -> done; + t2: (lowRespTime && lowFi) -> do[1] t0; + t3: (default) -> TNULL; + } +} diff --git a/targets/znews0/stitch/newssiteTactics.s b/targets/znews0/stitch/newssiteTactics.s index d11a0fd23..8cae5207e 100644 --- a/targets/znews0/stitch/newssiteTactics.s +++ b/targets/znews0/stitch/newssiteTactics.s @@ -1,118 +1,118 @@ -module newssite.tactics; - -import model "ZNewsSys.acme" { ZNewsSys as M, ZNewsFam as T }; -import op "znews0.operator.EffectOp" { EffectOp as S }; -import op "org.sa.rainbow.stitch.lib.*"; - - -/** - * Enlist n free servers into service pool. - * Utility: [v] R; [^] C; [<>] F - */ -tactic enlistServers (int n) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // there should be enough available server resources - Model.availableServices(T.ServerT) >= n; - } - action { - set servers = Set.randomSubset(Model.findServices(T.ServerT), n); - for (T.ServerT freeSvr : servers) { - S.activateServer(freeSvr); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Deactivate n servers from service pool into free pool. - * Utility: [^] R; [v] C; [<>] F - */ -tactic dischargeServers (int n) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there should be enough servers to discharge - Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; - } - action { - set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; - set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); - for (T.ServerT s : subLowUtilSvrs) { - S.deactivateServer(s); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Lowers fidelity by integral steps for percent of requests. - * Utility: [v] R; [v] C; [v] F - */ -tactic lowerFidelity (int step, float fracReq) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // exists server with fidelity to lower - exists s : T.ServerT in M.components | s.fidelity > step; - } - action { - // retrieve set of servers who still have enough fidelity grade to lower - set servers = { select s : T.ServerT in M.components | s.fidelity > step }; - for (T.ServerT s : servers) { - S.setFidelity(s, s.fidelity - step); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Raises fidelity by integral steps for percent of requests. - * Utility: [^] R; [^] C; [^] F - */ -tactic raiseFidelity (int step, float fracReq) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there exists some client with below low-threshold response time - exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - } - action { - // first find the lowest fidelity set - set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; -/* smarter way of doing things... - int lowestFidelity = M.MAX_FIDELITY_LEVEL; - for (T.ServerT s : servers) { - if (s.fidelity < lowestFidelity) { - lowestFidelity = s.fidelity; - } - } - // find only servers with this lowest fidelity setting, and raise fidelity - servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; -*/ - for (T.ServerT s : servers) { - S.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/* - T5) delayClients(set clients) - utility: [^] R; [v] C; [v] F - T6) blockClients(set clients) - utility: [^] R; [v] C; [v] F -*/ +module newssite.tactics; + +import model "ZNewsSys.acme" { ZNewsSys as M, ZNewsFam as T }; +import op "znews0.operator.EffectOp" { EffectOp as S }; +import op "org.sa.rainbow.stitch.lib.*"; + + +/** + * Enlist n free servers into service pool. + * Utility: [v] R; [^] C; [<>] F + */ +tactic enlistServers (int n) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // there should be enough available server resources + Model.availableServices(T.ServerT) >= n; + } + action { + set servers = Set.randomSubset(Model.findServices(T.ServerT), n); + for (T.ServerT freeSvr : servers) { + S.activateServer(freeSvr); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Deactivate n servers from service pool into free pool. + * Utility: [^] R; [v] C; [<>] F + */ +tactic dischargeServers (int n) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there should be enough servers to discharge + Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; + } + action { + set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; + set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); + for (T.ServerT s : subLowUtilSvrs) { + S.deactivateServer(s); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Lowers fidelity by integral steps for percent of requests. + * Utility: [v] R; [v] C; [v] F + */ +tactic lowerFidelity (int step, float fracReq) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // exists server with fidelity to lower + exists s : T.ServerT in M.components | s.fidelity > step; + } + action { + // retrieve set of servers who still have enough fidelity grade to lower + set servers = { select s : T.ServerT in M.components | s.fidelity > step }; + for (T.ServerT s : servers) { + S.setFidelity(s, s.fidelity - step); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Raises fidelity by integral steps for percent of requests. + * Utility: [^] R; [^] C; [^] F + */ +tactic raiseFidelity (int step, float fracReq) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there exists some client with below low-threshold response time + exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + } + action { + // first find the lowest fidelity set + set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; +/* smarter way of doing things... + int lowestFidelity = M.MAX_FIDELITY_LEVEL; + for (T.ServerT s : servers) { + if (s.fidelity < lowestFidelity) { + lowestFidelity = s.fidelity; + } + } + // find only servers with this lowest fidelity setting, and raise fidelity + servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; +*/ + for (T.ServerT s : servers) { + S.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/* + T5) delayClients(set clients) + utility: [^] R; [v] C; [v] F + T6) blockClients(set clients) + utility: [^] R; [v] C; [v] F +*/ diff --git a/targets/znews0/utilities.yml b/targets/znews0/utilities.yml index 62cb84c4b..e346c83c5 100644 --- a/targets/znews0/utilities.yml +++ b/targets/znews0/utilities.yml @@ -1,103 +1,103 @@ -# Created September 5, 2006 (Shang-Wen Cheng) -# -# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y is the utility in the range [0,1] -# -utilities: - uR: - label: Average Response Time - mapping: "[EAvg]ClientT.experRespTime" - description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" - utility: - 0: 1.00 - 100: 1.00 - 200: 0.99 - 500: 0.90 - 1000: 0.75 - 1500: 0.50 - 2000: 0.25 - 4000: 0.00 - uF: - label: Average Fidelity - mapping: "[EAvg]ServerT.fidelity" - description: "Server content fidelity in level, F, defined as an int property 'ServerT.fidelity' in the architecture, with some artificial range to be determined" - utility: - 0: 0.00 - 5: 1.00 - uC: - label: Average Server Cost - mapping: "[EAvg]ServerT.cost" - description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers" - utility: - 0: 1.00 - 1: 0.90 - 5: 0.20 - 10: 0.00 - uSF: - label: "Historical Strategy Failure" - mapping: "[EAvg]Strategy.rateFailure" - description: "Rate of failure, in fraction, of a strategy; utility has no effect if strategy history is not kept" - utility: - 0: 1.00 - 0.1: 0.80 - 0.5: 0.01 - 1: 0.00 -# -# Weighted utility preferences, each set should sum to 1. -# Three scenarios: -# a) Nominal request rate -> Sustained, peak request rate -> Nominal request rate -# b) Nominal request rate -> Transient, peak request rate -> Nominal request rate -# c) Any request rate -> Abnormally high request rate (e.g., Ramsey case) -> Any request rate -# -weights: - scenario 1: - uR: 0.35 - uF: 0.4 - uC: 0.25 - scenario 2: - uR: 0.5 - uF: 0.3 - uC: 0.2 - scenario 2b: - uR: 0.5 - uF: 0.2 - uC: 0.3 - scenario 3: - uR: 0.6 - uF: 0.3 - uC: 0.1 - scenario 4: - uR: 0.5 - uF: 0.1 - uC: 0.4 - scenario 5: - uR: 0.54 - uF: 0.27 - uC: 0.09 - uSF: 0.10 - -# Tactic quality attribute vectors -# -vectors: -# Utility: [v] R; [^] C; [<>] F -# assume each server will drop response time by 1000 ms and increase cost by 1 unit - enlistServers: - uR: -1000 - uF: 0 - uC: +1.00 -# Utility: [^] R; [v] C; [<>] F - dischargeServers: - uR: +1000 - uF: 0 - uC: -1.00 - -# Utility: [v] R; [v] C; [v] F -# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit - lowerFidelity: - uR: -500 - uF: -2 - uC: -0.10 -# Utility: [^] R; [^] C; [^] F - raiseFidelity: - uR: +500 - uF: +2 - uC: +0.10 +# Created September 5, 2006 (Shang-Wen Cheng) +# +# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y is the utility in the range [0,1] +# +utilities: + uR: + label: Average Response Time + mapping: "[EAvg]ClientT.experRespTime" + description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" + utility: + 0: 1.00 + 100: 1.00 + 200: 0.99 + 500: 0.90 + 1000: 0.75 + 1500: 0.50 + 2000: 0.25 + 4000: 0.00 + uF: + label: Average Fidelity + mapping: "[EAvg]ServerT.fidelity" + description: "Server content fidelity in level, F, defined as an int property 'ServerT.fidelity' in the architecture, with some artificial range to be determined" + utility: + 0: 0.00 + 5: 1.00 + uC: + label: Average Server Cost + mapping: "[EAvg]ServerT.cost" + description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers" + utility: + 0: 1.00 + 1: 0.90 + 5: 0.20 + 10: 0.00 + uSF: + label: "Historical Strategy Failure" + mapping: "[EAvg]Strategy.rateFailure" + description: "Rate of failure, in fraction, of a strategy; utility has no effect if strategy history is not kept" + utility: + 0: 1.00 + 0.1: 0.80 + 0.5: 0.01 + 1: 0.00 +# +# Weighted utility preferences, each set should sum to 1. +# Three scenarios: +# a) Nominal request rate -> Sustained, peak request rate -> Nominal request rate +# b) Nominal request rate -> Transient, peak request rate -> Nominal request rate +# c) Any request rate -> Abnormally high request rate (e.g., Ramsey case) -> Any request rate +# +weights: + scenario 1: + uR: 0.35 + uF: 0.4 + uC: 0.25 + scenario 2: + uR: 0.5 + uF: 0.3 + uC: 0.2 + scenario 2b: + uR: 0.5 + uF: 0.2 + uC: 0.3 + scenario 3: + uR: 0.6 + uF: 0.3 + uC: 0.1 + scenario 4: + uR: 0.5 + uF: 0.1 + uC: 0.4 + scenario 5: + uR: 0.54 + uF: 0.27 + uC: 0.09 + uSF: 0.10 + +# Tactic quality attribute vectors +# +vectors: +# Utility: [v] R; [^] C; [<>] F +# assume each server will drop response time by 1000 ms and increase cost by 1 unit + enlistServers: + uR: -1000 + uF: 0 + uC: +1.00 +# Utility: [^] R; [v] C; [<>] F + dischargeServers: + uR: +1000 + uF: 0 + uC: -1.00 + +# Utility: [v] R; [v] C; [v] F +# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit + lowerFidelity: + uR: -500 + uF: -2 + uC: -0.10 +# Utility: [^] R; [^] C; [^] F + raiseFidelity: + uR: +500 + uF: +2 + uC: +0.10 diff --git a/targets/znews1-d/model/TargetEnv.acme b/targets/znews1-d/model/TargetEnv.acme index 4331c55b7..2ec6be259 100644 --- a/targets/znews1-d/model/TargetEnv.acme +++ b/targets/znews1-d/model/TargetEnv.acme @@ -1,4 +1,4 @@ -System TargetEnv = { - -} - +System TargetEnv = { + +} + diff --git a/targets/znews1-d/model/TargetEnvType.acme b/targets/znews1-d/model/TargetEnvType.acme index a91a99173..91e499a0e 100644 --- a/targets/znews1-d/model/TargetEnvType.acme +++ b/targets/znews1-d/model/TargetEnvType.acme @@ -1,67 +1,67 @@ -Family EnvType = { - - Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; - - Role Type ArchRoleT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type PartPortT = { - - } - Component Type ArchElementT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type NetworkRoleT = { - - } - Connector Type MappingT = { - - } - Role Type PartRoleT = { - - } - Connector Type EdgeT = { - - Property bandwidthAvg : ResourceStatePropT; - - Property capacity : ResourceStatePropT; - - } - Component Type NodeT = { - - Property cpuOverall : ResourceStatePropT; - - Property memoryMain : ResourceStatePropT; - - Property storageLocal : ResourceStatePropT; - - Property socketPool : ResourceStatePropT; - - Property batteryOverall : ResourceStatePropT; - - } - Port Type NetworkPortT = { - - } - Connector Type ArchConnT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Port Type ArchPortT = { - - Property isArchEnabled : boolean << default : boolean = false; >> ; - - } - Role Type ContainerRoleT = { - - } - Port Type ContainmentPortT = { - - } -} - +Family EnvType = { + + Property Type ResourceStatePropT = Record [unit : string; total : float; available : float; used : float; ]; + + Role Type ArchRoleT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type PartPortT = { + + } + Component Type ArchElementT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type NetworkRoleT = { + + } + Connector Type MappingT = { + + } + Role Type PartRoleT = { + + } + Connector Type EdgeT = { + + Property bandwidthAvg : ResourceStatePropT; + + Property capacity : ResourceStatePropT; + + } + Component Type NodeT = { + + Property cpuOverall : ResourceStatePropT; + + Property memoryMain : ResourceStatePropT; + + Property storageLocal : ResourceStatePropT; + + Property socketPool : ResourceStatePropT; + + Property batteryOverall : ResourceStatePropT; + + } + Port Type NetworkPortT = { + + } + Connector Type ArchConnT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Port Type ArchPortT = { + + Property isArchEnabled : boolean << default : boolean = false; >> ; + + } + Role Type ContainerRoleT = { + + } + Port Type ContainmentPortT = { + + } +} + diff --git a/targets/znews1-d/model/TargetEnvType.mtd b/targets/znews1-d/model/TargetEnvType.mtd index 6817ebfa8..9d8d87f85 100644 --- a/targets/znews1-d/model/TargetEnvType.mtd +++ b/targets/znews1-d/model/TargetEnvType.mtd @@ -1,475 +1,475 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews1-d/model/ZNewsSys.acme b/targets/znews1-d/model/ZNewsSys.acme index 1261f2c53..c9c7e83f0 100644 --- a/targets/znews1-d/model/ZNewsSys.acme +++ b/targets/znews1-d/model/ZNewsSys.acme @@ -1,363 +1,363 @@ -import TargetEnvType.acme; - -Family ZNewsFam extends EnvType with { - - Port Type HttpPortT extends ArchPortT with { - - } - Role Type RequestorRoleT extends ArchRoleT with { - - } - Component Type ProxyT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - } - Port Type ProxyForwardPortT extends ArchPortT with { - - } - Component Type ServerT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property load : float << default : float = 0.0; >> ; - - Property reqServiceRate : float << default : float = 0.0; >> ; - - Property byteServiceRate : float << default : float = 0.0; >> ; - - Property fidelity : int << HIGH : int = 5; TEXT : int = 3; LOW : int = 1; default : int = 5; >> ; - - Property cost : float << default : float = 1.0; >> ; - - Property lastPageHit : Record [uri : string; cnt : int; kbytes : float; ]; - rule anotherConstraint = invariant self.load <= MAX_UTIL; - - } - Role Type ReceiverRoleT extends ArchRoleT with { - - } - Connector Type ProxyConnT extends ArchConnT with { - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - Component Type ClientT extends ArchElementT with { - - Property deploymentLocation : string << default : string = "localhost"; >> ; - - Property experRespTime : float << default : float = 0.0; >> ; - - Property reqRate : float << default : float = 0.0; >> ; - rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; - - } - Port Type HttpReqPortT extends ArchPortT with { - - } - Connector Type HttpConnT extends ArchConnT with { - - Property bandwidth : float << default : float = 0.0; >> ; - - Property latency : float << default : float = 0.0; >> ; - - Property numReqsSuccess : int << default : int = 0; >> ; - - Property numReqsRedirect : int << default : int = 0; >> ; - - Property numReqsClientError : int << default : int = 0; >> ; - - Property numReqsServerError : int << default : int = 0; >> ; - - Property latencyRate : float; - Role req : RequestorRoleT = new RequestorRoleT extended with { - - } - Role rec : ReceiverRoleT = new ReceiverRoleT extended with { - - } - - } - - Property MIN_RESPTIME : float; - - Property MAX_RESPTIME : float; - - Property TOLERABLE_PERCENT_UNHAPPY : float; - - Property UNHAPPY_GRADIENT_1 : float; - - Property UNHAPPY_GRADIENT_2 : float; - - Property UNHAPPY_GRADIENT_3 : float; - - Property FRACTION_GRADIENT_1 : float; - - Property FRACTION_GRADIENT_2 : float; - - Property FRACTION_GRADIENT_3 : float; - - Property MIN_UTIL : float; - - Property MAX_UTIL : float; - - Property MAX_FIDELITY_LEVEL : int; - - Property THRESHOLD_FIDELITY : int; - - Property THRESHOLD_COST : float; -} - -System ZNewsSys : ZNewsFam = { - - - Property MIN_RESPTIME : float = 100.0; - - Property MAX_RESPTIME : float = 1000.0; - - Property UNHAPPY_GRADIENT_1 : float = 0.1; - - Property UNHAPPY_GRADIENT_2 : float = 0.2; - - Property UNHAPPY_GRADIENT_3 : float = 0.5; - - Property FRACTION_GRADIENT_1 : float = 0.2; - - Property FRACTION_GRADIENT_2 : float = 0.4; - - Property FRACTION_GRADIENT_3 : float = 1.0; - - Property TOLERABLE_PERCENT_UNHAPPY : float = 0.25; - - Property MIN_UTIL : float = 0.1; - - Property MAX_UTIL : float = 0.75; - - Property MAX_FIDELITY_LEVEL : int = 5; - - Property THRESHOLD_FIDELITY : int = 2; - - Property THRESHOLD_COST : float = 6.0; - Component s1 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - - Property deploymentLocation = "phoenix"; - - Property isArchEnabled = false; - Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { - - } - - } - Component lbproxy : ProxyT = new ProxyT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property isArchEnabled = true; - Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - Property isArchEnabled = true; - - } - Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT extended with { - - } - Port http0 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - Port http1 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - Port http2 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - - } - Component s2 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - - Property deploymentLocation = "127.0.0.3"; - - Property isArchEnabled = false; - Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { - - } - - } - Component s3 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - - Property deploymentLocation = "127.0.0.4"; - - Property isArchEnabled = false; - Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { - - } - - } - Component s0 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { - - Property deploymentLocation = "oracle"; - - Property cost = 1.0; - - Property fidelity = 5; - - Property load = 0.0; - - Property isArchEnabled = true; - Port http0 : HttpPortT = new HttpPortT extended with { - - Property isArchEnabled = true; - - } - - } - Component c0 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property experRespTime : float = 50.0; - - Property isArchEnabled = true; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - } - Component c1 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property experRespTime : float = 50; - - Property isArchEnabled = true; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - } - Component c2 : ClientT = new ClientT extended with { - - Property deploymentLocation = "127.0.0.1"; - - Property experRespTime : float = 50; - - Property isArchEnabled = true; - Port p0 : HttpReqPortT = new HttpReqPortT extended with { - - Property isArchEnabled = true; - - } - - } - Connector conn0 : HttpConnT = new HttpConnT extended with { - - Property latencyRate = 0.0; - - Property isArchEnabled = true; - Role req = { - - Property isArchEnabled = true; - - } - Role rec = { - - Property isArchEnabled = true; - - } - - } - Connector proxyconn0 : ProxyConnT = new ProxyConnT extended with { - - Property isArchEnabled = true; - Role req = { - - Property isArchEnabled = true; - - } - Role rec = { - - Property isArchEnabled = true; - - } - - } - Connector proxyconn1 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { - - } - Connector proxyconn3 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { - - } - Connector proxyconn2 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { - - } - Connector conn : HttpConnT = new HttpConnT extended with { - - Property latencyRate = 0.0; - - Property isArchEnabled = true; - Role req = { - - Property isArchEnabled = true; - - } - Role rec = { - - Property isArchEnabled = true; - - } - - } - Connector conn1 : HttpConnT = new HttpConnT extended with { - - Property latencyRate = 0.0; - - Property isArchEnabled = true; - Role req = { - - Property isArchEnabled = true; - - } - Role rec = { - - Property isArchEnabled = true; - - } - - } - Attachment lbproxy.fwd0 to proxyconn0.req; - Attachment s0.http0 to proxyconn0.rec; - Attachment c0.p0 to conn0.req; - Attachment lbproxy.http0 to conn0.rec; - Attachment c1.p0 to conn.req; - Attachment c2.p0 to conn1.req; - Attachment lbproxy.http2 to conn1.rec; - Attachment lbproxy.http1 to conn.rec; - Attachment s2.http0 to proxyconn2.rec; - Attachment lbproxy.fwd1 to proxyconn1.req; - Attachment s1.http0 to proxyconn1.rec; - Attachment s3.http0 to proxyconn3.rec; - Attachment lbproxy.fwd3 to proxyconn3.req; - Attachment lbproxy.fwd2 to proxyconn2.req; -} - +import TargetEnvType.acme; + +Family ZNewsFam extends EnvType with { + + Port Type HttpPortT extends ArchPortT with { + + } + Role Type RequestorRoleT extends ArchRoleT with { + + } + Component Type ProxyT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + } + Port Type ProxyForwardPortT extends ArchPortT with { + + } + Component Type ServerT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property load : float << default : float = 0.0; >> ; + + Property reqServiceRate : float << default : float = 0.0; >> ; + + Property byteServiceRate : float << default : float = 0.0; >> ; + + Property fidelity : int << HIGH : int = 5; TEXT : int = 3; LOW : int = 1; default : int = 5; >> ; + + Property cost : float << default : float = 1.0; >> ; + + Property lastPageHit : Record [uri : string; cnt : int; kbytes : float; ]; + rule anotherConstraint = invariant self.load <= MAX_UTIL; + + } + Role Type ReceiverRoleT extends ArchRoleT with { + + } + Connector Type ProxyConnT extends ArchConnT with { + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + Component Type ClientT extends ArchElementT with { + + Property deploymentLocation : string << default : string = "localhost"; >> ; + + Property experRespTime : float << default : float = 0.0; >> ; + + Property reqRate : float << default : float = 0.0; >> ; + rule primaryConstraint = invariant self.experRespTime <= MAX_RESPTIME; + + } + Port Type HttpReqPortT extends ArchPortT with { + + } + Connector Type HttpConnT extends ArchConnT with { + + Property bandwidth : float << default : float = 0.0; >> ; + + Property latency : float << default : float = 0.0; >> ; + + Property numReqsSuccess : int << default : int = 0; >> ; + + Property numReqsRedirect : int << default : int = 0; >> ; + + Property numReqsClientError : int << default : int = 0; >> ; + + Property numReqsServerError : int << default : int = 0; >> ; + + Property latencyRate : float; + Role req : RequestorRoleT = new RequestorRoleT extended with { + + } + Role rec : ReceiverRoleT = new ReceiverRoleT extended with { + + } + + } + + Property MIN_RESPTIME : float; + + Property MAX_RESPTIME : float; + + Property TOLERABLE_PERCENT_UNHAPPY : float; + + Property UNHAPPY_GRADIENT_1 : float; + + Property UNHAPPY_GRADIENT_2 : float; + + Property UNHAPPY_GRADIENT_3 : float; + + Property FRACTION_GRADIENT_1 : float; + + Property FRACTION_GRADIENT_2 : float; + + Property FRACTION_GRADIENT_3 : float; + + Property MIN_UTIL : float; + + Property MAX_UTIL : float; + + Property MAX_FIDELITY_LEVEL : int; + + Property THRESHOLD_FIDELITY : int; + + Property THRESHOLD_COST : float; +} + +System ZNewsSys : ZNewsFam = { + + + Property MIN_RESPTIME : float = 100.0; + + Property MAX_RESPTIME : float = 1000.0; + + Property UNHAPPY_GRADIENT_1 : float = 0.1; + + Property UNHAPPY_GRADIENT_2 : float = 0.2; + + Property UNHAPPY_GRADIENT_3 : float = 0.5; + + Property FRACTION_GRADIENT_1 : float = 0.2; + + Property FRACTION_GRADIENT_2 : float = 0.4; + + Property FRACTION_GRADIENT_3 : float = 1.0; + + Property TOLERABLE_PERCENT_UNHAPPY : float = 0.25; + + Property MIN_UTIL : float = 0.1; + + Property MAX_UTIL : float = 0.75; + + Property MAX_FIDELITY_LEVEL : int = 5; + + Property THRESHOLD_FIDELITY : int = 2; + + Property THRESHOLD_COST : float = 6.0; + Component s1 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + + Property deploymentLocation = "phoenix"; + + Property isArchEnabled = false; + Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { + + } + + } + Component lbproxy : ProxyT = new ProxyT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property isArchEnabled = true; + Port fwd0 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + Property isArchEnabled = true; + + } + Port fwd1 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd2 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port fwd3 : ProxyForwardPortT = new ProxyForwardPortT extended with { + + } + Port http0 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + Port http1 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + Port http2 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + + } + Component s2 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + + Property deploymentLocation = "127.0.0.3"; + + Property isArchEnabled = false; + Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { + + } + + } + Component s3 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + + Property deploymentLocation = "127.0.0.4"; + + Property isArchEnabled = false; + Port http0 : HttpPortT, ArchPortT = new HttpPortT, ArchPortT extended with { + + } + + } + Component s0 : ServerT, ArchElementT = new ServerT, ArchElementT extended with { + + Property deploymentLocation = "oracle"; + + Property cost = 1.0; + + Property fidelity = 5; + + Property load = 0.0; + + Property isArchEnabled = true; + Port http0 : HttpPortT = new HttpPortT extended with { + + Property isArchEnabled = true; + + } + + } + Component c0 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50.0; + + Property isArchEnabled = true; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + } + Component c1 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50; + + Property isArchEnabled = true; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + } + Component c2 : ClientT = new ClientT extended with { + + Property deploymentLocation = "127.0.0.1"; + + Property experRespTime : float = 50; + + Property isArchEnabled = true; + Port p0 : HttpReqPortT = new HttpReqPortT extended with { + + Property isArchEnabled = true; + + } + + } + Connector conn0 : HttpConnT = new HttpConnT extended with { + + Property latencyRate = 0.0; + + Property isArchEnabled = true; + Role req = { + + Property isArchEnabled = true; + + } + Role rec = { + + Property isArchEnabled = true; + + } + + } + Connector proxyconn0 : ProxyConnT = new ProxyConnT extended with { + + Property isArchEnabled = true; + Role req = { + + Property isArchEnabled = true; + + } + Role rec = { + + Property isArchEnabled = true; + + } + + } + Connector proxyconn1 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { + + } + Connector proxyconn3 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { + + } + Connector proxyconn2 : ProxyConnT, ArchConnT = new ProxyConnT, ArchConnT extended with { + + } + Connector conn : HttpConnT = new HttpConnT extended with { + + Property latencyRate = 0.0; + + Property isArchEnabled = true; + Role req = { + + Property isArchEnabled = true; + + } + Role rec = { + + Property isArchEnabled = true; + + } + + } + Connector conn1 : HttpConnT = new HttpConnT extended with { + + Property latencyRate = 0.0; + + Property isArchEnabled = true; + Role req = { + + Property isArchEnabled = true; + + } + Role rec = { + + Property isArchEnabled = true; + + } + + } + Attachment lbproxy.fwd0 to proxyconn0.req; + Attachment s0.http0 to proxyconn0.rec; + Attachment c0.p0 to conn0.req; + Attachment lbproxy.http0 to conn0.rec; + Attachment c1.p0 to conn.req; + Attachment c2.p0 to conn1.req; + Attachment lbproxy.http2 to conn1.rec; + Attachment lbproxy.http1 to conn.rec; + Attachment s2.http0 to proxyconn2.rec; + Attachment lbproxy.fwd1 to proxyconn1.req; + Attachment s1.http0 to proxyconn1.rec; + Attachment s3.http0 to proxyconn3.rec; + Attachment lbproxy.fwd3 to proxyconn3.req; + Attachment lbproxy.fwd2 to proxyconn2.req; +} + diff --git a/targets/znews1-d/model/ZNewsSys.mtd b/targets/znews1-d/model/ZNewsSys.mtd index 9c791b08c..e608ac720 100644 --- a/targets/znews1-d/model/ZNewsSys.mtd +++ b/targets/znews1-d/model/ZNewsSys.mtd @@ -1,2005 +1,2005 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/targets/znews1-d/model/gauges.yml b/targets/znews1-d/model/gauges.yml index fd5258022..8b698aab1 100644 --- a/targets/znews1-d/model/gauges.yml +++ b/targets/znews1-d/model/gauges.yml @@ -1,316 +1,316 @@ -# -# Gauge Type and Gauge Instance Specifications -# - time periods generally in milliseconds -# -# History: -# - [SWC 2007.01.18] Created file, populated ZNews gauge descriptions. -# - [SWC 2007.04.09] Changed LatencyGaugeT to use RtLatencyMultiHostGauge. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# - [SWC 2007.04.11] Added ResponseTimeGaugeT -# -gauge-types: - - ResponseTimeGaugeT: - commands: - end2endRespTime : ClientT.setResponseTime (float) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znews.gauges.End2EndRespTimeGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "ResponseTimeGaugeT measures and reports the end-to-end response time from a client or its proxy." - - ApacheTopGaugeT: - commands: - reqServiceRate : ServerT.setReqServiceRate(float) - byteServiceRate : ServerT.setByteServiceRate(float) - numReqsSuccess : HttpConnT.setNumSuccessfulRequests(int) - numReqsRedirect : HttpConnT.setNumRedirectedRequests(int) - numReqsClientError : HttpConnT.setNumRequestsClientError(int) - numReqsServerError : HttpConnT.setNumRequestsServerError(int) - pageHit : ServerT.setLastPageHit(String) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.ApacheTopGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "ApacheTopGaugeT measures and reports properties of an Apache server, via a UNIX top like utility" - - DiskIOGaugeT: - commands: - transferRate : ServerT.setDiskTransferRate(double) - readRate : ServerT.setDiskReadRate(double) - writeRate : ServerT.setDiskWriteRate(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.DiskIOGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "DiskIOGaugeT measures and reports disk IO stat of the target host, read/write reported in KBps" - - LoadGaugeT: - commands: - load : ServerT.setLoad(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.CpuLoadGauge" - configParams: - samplingFrequency: - type: long - default: 1000 - targetProbeType: - type: String - default: ~ - comment: "LoadGaugeT measures and reports CPU load of the target host" - - FidelityGaugeT: - commands: - fidelity : ServerT.setFidelity(int) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 30000 - javaClass: - type: String - default: "org.sa.rainbow.translator.gauges.FidelityGauge" - configParams: - samplingFrequency: - type: long - default: 2500 - targetProbeType: - type: String - default: ~ - comment: "FidelityGaugeT measures and reports the fidelity level of served content" - - LatencyGaugeT: - commands: - latency : HttpConnT.setLatency(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge" - configParams: - samplingFrequency: - type: long - default: 1500 - targetProbeType: - type: String - default: ~ - comment: "LatencyGaugeT measures and reports latency on a connection" - - LatencyRateGaugeT: - commands: - latencyRate : HttpConnT.setLatencyRate(double) - setupParams: - targetIP: - type: String - default: "localhost" - beaconPeriod: - type: long - default: 20000 - javaClass: - type: String - default: "org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge" - configParams: - samplingFrequency: - type: long - default: 1500 - targetProbeType: - type: String - default: ~ - comment: "LatencyRateGaugeT measures and reports the latency rate of change on a connection" - -gauge-instances: - - EERTG1: - type: ResponseTimeGaugeT - model: "ZNewsSys:Acme" - commands: - "end2endRespTime(delegate.oracle)" : c0.setExperiencedResponseTime($) - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - samplingFrequency: 1000 - targetProbeType : clientproxy - comment: "EERTG1 is associated with the client component of the System, ZNewsSys, defined as an Acme model" - - ATG1: - type: ApacheTopGaugeT - model: "ZNewsSys:Acme" - mappings: - reqServiceRate : s0.setReqServiceRate($) - byteServiceRate : s0.setByteServiceRate($) - numReqsSuccess : conn0.setNumSuccessfulRequests($) - numReqsRedirect : conn0.setNumRedirectedRequests($) - numReqsClientError : conn0.setNumRequestsClientError($) - numReqsServerError : conn0.setNumRequestsServerError($) - pageHit : s0.setLastPageHit($) - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: ~ - # Leave details unspecified (null) to use default value defined at the type-level - targetProbeType : apachetop - comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" - - DioG1: - type: DiskIOGaugeT - model: "ZNewsSys:Acme" - mappings: - transferRate : s0.setDiskTransferRate($) - readRate : s0.setDiskReadRate($) - writeRate : s0.setDiskWriteRate($) - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1000 - targetProbeType : diskio - comment: "DioG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LoG0: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s0.setLoad($) - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG0 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LoG1: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s1.setLoad($) - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG1 is associated with the component s1 of the System, ZNewsSys, defined as an Acme model" - - FiG1: - type: FidelityGaugeT - model: "ZNewsSys:Acme" - mappings: - fidelity : s0.setFidelity($) - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 2500 - targetProbeType : fidelity - comment: "FiG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" - - LatG1: - type: LatencyGaugeT - model: "ZNewsSys:Acme" - mappings: - "latency(${rainbow.master.location.host})" : conn0.setLatency($) - "latency(@{ZNewsSys.s1.deploymentLocation})" : conn1.setLatency($) - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1500 - targetProbeType : pingrtt - comment: "LatG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" - - LatRoCG1: - type: LatencyRateGaugeT - model: "ZNewsSys:Acme" - mappings: - "latencyRate(${rainbow.master.location.host})" : conn0.setLatencyRate($) - "latencyRate(@{ZNewsSys.s1.deploymentLocation})" : conn1.setLatencyRate($) - setupValues: - targetIP: "${customize.system.target.1}" - configValues: - samplingFrequency: 1500 - targetProbeType : pingrtt - comment: "LatRoCG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" - -unused-gauge-instances: - - ATG0: - type: ApacheTopGaugeT - model: "ZNewsSys:Acme" - mappings: - reqServiceRate : s0.reqServiceRate - byteServiceRate : s0.byteServiceRate - numReqsSuccess : conn0.numReqsSuccess - numReqsRedirect : conn0.numReqsRedirect - numReqsClientError : conn0.numReqsClientError - numReqsServerError : conn0.numReqsServerError - pageHit : s0.lastPageHit - setupValues: - targetIP: "${customize.system.target.0}" - configValues: - samplingFrequency: ~ - # Leave details unspecified (null) to use default value defined at the type-level - targetProbeType : apachetop - comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" - - LoG3: - type: LoadGaugeT - model: "ZNewsSys:Acme" - mappings: - load : s3.load - setupValues: - targetIP: "${customize.system.target.3}" - configValues: - samplingFrequency: 1000 - targetProbeType : load - comment: "LoG3 is associated with the component s3 of the System, ZNewsSys, defined as an Acme model" - +# +# Gauge Type and Gauge Instance Specifications +# - time periods generally in milliseconds +# +# History: +# - [SWC 2007.01.18] Created file, populated ZNews gauge descriptions. +# - [SWC 2007.04.09] Changed LatencyGaugeT to use RtLatencyMultiHostGauge. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# - [SWC 2007.04.11] Added ResponseTimeGaugeT +# +gauge-types: + + ResponseTimeGaugeT: + commands: + end2endRespTime : ClientT.setResponseTime (float) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znews.gauges.End2EndRespTimeGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "ResponseTimeGaugeT measures and reports the end-to-end response time from a client or its proxy." + + ApacheTopGaugeT: + commands: + reqServiceRate : ServerT.setReqServiceRate(float) + byteServiceRate : ServerT.setByteServiceRate(float) + numReqsSuccess : HttpConnT.setNumSuccessfulRequests(int) + numReqsRedirect : HttpConnT.setNumRedirectedRequests(int) + numReqsClientError : HttpConnT.setNumRequestsClientError(int) + numReqsServerError : HttpConnT.setNumRequestsServerError(int) + pageHit : ServerT.setLastPageHit(String) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.ApacheTopGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "ApacheTopGaugeT measures and reports properties of an Apache server, via a UNIX top like utility" + + DiskIOGaugeT: + commands: + transferRate : ServerT.setDiskTransferRate(double) + readRate : ServerT.setDiskReadRate(double) + writeRate : ServerT.setDiskWriteRate(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.DiskIOGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "DiskIOGaugeT measures and reports disk IO stat of the target host, read/write reported in KBps" + + LoadGaugeT: + commands: + load : ServerT.setLoad(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.CpuLoadGauge" + configParams: + samplingFrequency: + type: long + default: 1000 + targetProbeType: + type: String + default: ~ + comment: "LoadGaugeT measures and reports CPU load of the target host" + + FidelityGaugeT: + commands: + fidelity : ServerT.setFidelity(int) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 30000 + javaClass: + type: String + default: "org.sa.rainbow.translator.gauges.FidelityGauge" + configParams: + samplingFrequency: + type: long + default: 2500 + targetProbeType: + type: String + default: ~ + comment: "FidelityGaugeT measures and reports the fidelity level of served content" + + LatencyGaugeT: + commands: + latency : HttpConnT.setLatency(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znews.gauges.RtLatencyMultiHostGauge" + configParams: + samplingFrequency: + type: long + default: 1500 + targetProbeType: + type: String + default: ~ + comment: "LatencyGaugeT measures and reports latency on a connection" + + LatencyRateGaugeT: + commands: + latencyRate : HttpConnT.setLatencyRate(double) + setupParams: + targetIP: + type: String + default: "localhost" + beaconPeriod: + type: long + default: 20000 + javaClass: + type: String + default: "org.sa.rainbow.translator.znews.gauges.RtLatencyRateMultiHostGauge" + configParams: + samplingFrequency: + type: long + default: 1500 + targetProbeType: + type: String + default: ~ + comment: "LatencyRateGaugeT measures and reports the latency rate of change on a connection" + +gauge-instances: + + EERTG1: + type: ResponseTimeGaugeT + model: "ZNewsSys:Acme" + commands: + "end2endRespTime(delegate.oracle)" : c0.setExperiencedResponseTime($) + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + samplingFrequency: 1000 + targetProbeType : clientproxy + comment: "EERTG1 is associated with the client component of the System, ZNewsSys, defined as an Acme model" + + ATG1: + type: ApacheTopGaugeT + model: "ZNewsSys:Acme" + mappings: + reqServiceRate : s0.setReqServiceRate($) + byteServiceRate : s0.setByteServiceRate($) + numReqsSuccess : conn0.setNumSuccessfulRequests($) + numReqsRedirect : conn0.setNumRedirectedRequests($) + numReqsClientError : conn0.setNumRequestsClientError($) + numReqsServerError : conn0.setNumRequestsServerError($) + pageHit : s0.setLastPageHit($) + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: ~ + # Leave details unspecified (null) to use default value defined at the type-level + targetProbeType : apachetop + comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" + + DioG1: + type: DiskIOGaugeT + model: "ZNewsSys:Acme" + mappings: + transferRate : s0.setDiskTransferRate($) + readRate : s0.setDiskReadRate($) + writeRate : s0.setDiskWriteRate($) + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1000 + targetProbeType : diskio + comment: "DioG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LoG0: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s0.setLoad($) + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG0 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LoG1: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s1.setLoad($) + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG1 is associated with the component s1 of the System, ZNewsSys, defined as an Acme model" + + FiG1: + type: FidelityGaugeT + model: "ZNewsSys:Acme" + mappings: + fidelity : s0.setFidelity($) + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 2500 + targetProbeType : fidelity + comment: "FiG1 is associated with the component s0 of the System, ZNewsSys, defined as an Acme model" + + LatG1: + type: LatencyGaugeT + model: "ZNewsSys:Acme" + mappings: + "latency(${rainbow.master.location.host})" : conn0.setLatency($) + "latency(@{ZNewsSys.s1.deploymentLocation})" : conn1.setLatency($) + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1500 + targetProbeType : pingrtt + comment: "LatG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" + + LatRoCG1: + type: LatencyRateGaugeT + model: "ZNewsSys:Acme" + mappings: + "latencyRate(${rainbow.master.location.host})" : conn0.setLatencyRate($) + "latencyRate(@{ZNewsSys.s1.deploymentLocation})" : conn1.setLatencyRate($) + setupValues: + targetIP: "${customize.system.target.1}" + configValues: + samplingFrequency: 1500 + targetProbeType : pingrtt + comment: "LatRoCG1 is associated with the connectors of the System, ZNewsSys, defined as an Acme model" + +unused-gauge-instances: + + ATG0: + type: ApacheTopGaugeT + model: "ZNewsSys:Acme" + mappings: + reqServiceRate : s0.reqServiceRate + byteServiceRate : s0.byteServiceRate + numReqsSuccess : conn0.numReqsSuccess + numReqsRedirect : conn0.numReqsRedirect + numReqsClientError : conn0.numReqsClientError + numReqsServerError : conn0.numReqsServerError + pageHit : s0.lastPageHit + setupValues: + targetIP: "${customize.system.target.0}" + configValues: + samplingFrequency: ~ + # Leave details unspecified (null) to use default value defined at the type-level + targetProbeType : apachetop + comment: "ATG1 is associated with component s0 and connector conn0 of the System, ZNewsSys, defined as an Acme model" + + LoG3: + type: LoadGaugeT + model: "ZNewsSys:Acme" + mappings: + load : s3.load + setupValues: + targetIP: "${customize.system.target.3}" + configValues: + samplingFrequency: 1000 + targetProbeType : load + comment: "LoG3 is associated with the component s3 of the System, ZNewsSys, defined as an Acme model" + diff --git a/targets/znews1-d/model/op.map b/targets/znews1-d/model/op.map index 52c7bb9d4..20b09b0b1 100644 --- a/targets/znews1-d/model/op.map +++ b/targets/znews1-d/model/op.map @@ -1,3 +1,3 @@ -setFidelity: changeState -activateServer: start -deactivateServer: stop +setFidelity: changeState +activateServer: start +deactivateServer: stop diff --git a/targets/znews1-d/rainbow-fir.able.cs.cmu.edu.properties b/targets/znews1-d/rainbow-fir.able.cs.cmu.edu.properties index 22423afdf..15981afa2 100644 --- a/targets/znews1-d/rainbow-fir.able.cs.cmu.edu.properties +++ b/targets/znews1-d/rainbow-fir.able.cs.cmu.edu.properties @@ -1,29 +1,29 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = fir.able.cs.cmu.edu -#- Location information of the deployed delegate -rainbow.deployment.location = ${rainbow.master.location.host} -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = cygwin - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = waterfall.able.cs.cmu.edu -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = fir.able.cs.cmu.edu +#- Location information of the deployed delegate +rainbow.deployment.location = ${rainbow.master.location.host} +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = cygwin + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = waterfall.able.cs.cmu.edu +customize.system.target.size = 2 diff --git a/targets/znews1-d/rainbow-fir.properties b/targets/znews1-d/rainbow-fir.properties index 278de64bc..642c00063 100644 --- a/targets/znews1-d/rainbow-fir.properties +++ b/targets/znews1-d/rainbow-fir.properties @@ -1,38 +1,38 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = fir -#rainbow.master.location.host = jarrah -#rainbow.master.location.host = waterfall.able.cs.cmu.edu -#rainbow.master.location.host = fir.wv.cs.cmu.edu -#- Location information of the deployed delegate -rainbow.deployment.location = ${rainbow.master.location.host} -#rainbow.deployment.location = fir.wv.cs.cmu.edu -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = cygwin - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = oracle -#customize.system.target.2 = phoenix -#customize.system.target.3 = fir -#customize.system.target.3 = waterfall.able.cs.cmu.edu -#customize.system.target.3 = fir.wv.cs.cmu.edu -#customize.system.target.size = 4 -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = fir +#rainbow.master.location.host = jarrah +#rainbow.master.location.host = waterfall.able.cs.cmu.edu +#rainbow.master.location.host = fir.wv.cs.cmu.edu +#- Location information of the deployed delegate +rainbow.deployment.location = ${rainbow.master.location.host} +#rainbow.deployment.location = fir.wv.cs.cmu.edu +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = cygwin + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = oracle +#customize.system.target.2 = phoenix +#customize.system.target.3 = fir +#customize.system.target.3 = waterfall.able.cs.cmu.edu +#customize.system.target.3 = fir.wv.cs.cmu.edu +#customize.system.target.size = 4 +customize.system.target.size = 2 diff --git a/targets/znews1-d/rainbow-jarrah.properties b/targets/znews1-d/rainbow-jarrah.properties index 70b8d3736..955dcbcb7 100644 --- a/targets/znews1-d/rainbow-jarrah.properties +++ b/targets/znews1-d/rainbow-jarrah.properties @@ -1,34 +1,34 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = jarrah -#- Location information of the deployed delegate -rainbow.deployment.location = ${rainbow.master.location.host} -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = oracle -#customize.system.target.2 = phoenix -#customize.system.target.3 = fir -#customize.system.target.3 = waterfall.able.cs.cmu.edu -#customize.system.target.3 = fir.wv.cs.cmu.edu -#customize.system.target.size = 4 -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = jarrah +#- Location information of the deployed delegate +rainbow.deployment.location = ${rainbow.master.location.host} +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = oracle +#customize.system.target.2 = phoenix +#customize.system.target.3 = fir +#customize.system.target.3 = waterfall.able.cs.cmu.edu +#customize.system.target.3 = fir.wv.cs.cmu.edu +#customize.system.target.size = 4 +customize.system.target.size = 2 diff --git a/targets/znews1-d/rainbow-maple.properties b/targets/znews1-d/rainbow-maple.properties index 13d831aba..3decb02c7 100644 --- a/targets/znews1-d/rainbow-maple.properties +++ b/targets/znews1-d/rainbow-maple.properties @@ -1,29 +1,29 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = maple -#- Location information of the deployed delegate -rainbow.deployment.location = maple -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = waterfall.able.cs.cmu.edu -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = maple +#- Location information of the deployed delegate +rainbow.deployment.location = maple +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = waterfall.able.cs.cmu.edu +customize.system.target.size = 2 diff --git a/targets/znews1-d/rainbow-oracle.properties b/targets/znews1-d/rainbow-oracle.properties index 86a4ae4f1..e6ca2a9b3 100644 --- a/targets/znews1-d/rainbow-oracle.properties +++ b/targets/znews1-d/rainbow-oracle.properties @@ -1,32 +1,32 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = jarrah -#- Location information of the deployed delegate -rainbow.deployment.location = oracle -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = oracle -#customize.system.target.2 = phoenix -#customize.system.target.3 = waterfall.able.cs.cmu.edu -#customize.system.target.size = 4 -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = jarrah +#- Location information of the deployed delegate +rainbow.deployment.location = oracle +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = oracle +#customize.system.target.2 = phoenix +#customize.system.target.3 = waterfall.able.cs.cmu.edu +#customize.system.target.size = 4 +customize.system.target.size = 2 diff --git a/targets/znews1-d/rainbow-phoenix.properties b/targets/znews1-d/rainbow-phoenix.properties index 1f37e5c78..b7e88286d 100644 --- a/targets/znews1-d/rainbow-phoenix.properties +++ b/targets/znews1-d/rainbow-phoenix.properties @@ -1,31 +1,31 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = fir -#- Location information of the deployed delegate -rainbow.deployment.location = phoenix -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = oracle -customize.system.target.2 = phoenix -customize.system.target.3 = waterfall.able.cs.cmu.edu -customize.system.target.size = 4 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = fir +#- Location information of the deployed delegate +rainbow.deployment.location = phoenix +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = oracle +customize.system.target.2 = phoenix +customize.system.target.3 = waterfall.able.cs.cmu.edu +customize.system.target.size = 4 diff --git a/targets/znews1-d/rainbow-waterfall.able.cs.cmu.edu.properties b/targets/znews1-d/rainbow-waterfall.able.cs.cmu.edu.properties index 6dce5bcda..321152bf1 100644 --- a/targets/znews1-d/rainbow-waterfall.able.cs.cmu.edu.properties +++ b/targets/znews1-d/rainbow-waterfall.able.cs.cmu.edu.properties @@ -1,29 +1,29 @@ -################################################################################ -# Purpose: Host-specific configuration file for the Rainbow infrastructure -# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = maple -#- Location information of this deployed delegate -rainbow.deployment.location = waterfall.able.cs.cmu.edu -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux - -## System configuration information -# -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = waterfall.able.cs.cmu.edu -customize.system.target.size = 2 +################################################################################ +# Purpose: Host-specific configuration file for the Rainbow infrastructure +# Properties are loaded by org.sa.rainbow.Rainbow _after_ common file. +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = maple +#- Location information of this deployed delegate +rainbow.deployment.location = waterfall.able.cs.cmu.edu +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux + +## System configuration information +# +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = waterfall.able.cs.cmu.edu +customize.system.target.size = 2 diff --git a/targets/znews1-d/rainbow.properties b/targets/znews1-d/rainbow.properties index 8ac763c80..915f6766d 100644 --- a/targets/znews1-d/rainbow.properties +++ b/targets/znews1-d/rainbow.properties @@ -1,92 +1,92 @@ -################################################################################ -# Purpose: Common configuration file for the Rainbow infrastructure. -# Properties are loaded by class org.sa.rainbow.Rainbow . -# Target: ZNews case study system with Probes, Gauges, and Effectors implemented -# (rainbow.target = znews1-d) -# Framework-defined special properties: -# rainbow.path - the canonical path to the target configuration location -# -# History: see non-target-specific copy -################################################################################ - -### -# Default values for location specific properties, meaning that, if the -# rainbow-.properties file does not specify a value, the default value -# set here is used. - -### Utility mechanism configuration -#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL -logging.level = INFO -event.log.path = log -logging.path = ${event.log.path}/rainbow.out -monitoring.log.path = ${event.log.path}/rainbow-data.log -# (default) -#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" -#logging.max.size = 1024 -#logging.max.backups = 5 - -### Rainbow component customization -## Rainbow host info and communication infrastructure -#- Location information of the master and this deployment -rainbow.master.location.host = localhost -#- Location information of the deployed delegate -rainbow.deployment.location = ${rainbow.master.location.host} -#- Rainbow service port -rainbow.service.port = 9210 -#- default registry port; change if port-tunneling -rainbow.master.location.port = 1099 -#- OS platform, supported modes are: cygwin | linux -# Use "cygwin" for Windows, "linux" for MacOSX -rainbow.deployment.environment = linux -#- Event infrastructure, type of event middleware: rmi | jms | que -rainbow.event.service = rmi -#- JMS/JBoss-specific configurations -#event.context.factory = org.jnp.interfaces.NamingContextFactory -#event.provider.url = ${rainbow.master.location.host}:1099 -#event.url.prefixes = org.jboss.naming:org.jnp.interfaces - -## RainbowDelegate and ProbeBusRelay configurations -rainbow.delegate.id = RainbowDelegate@${rainbow.deployment.location} -rainbow.delegate.beaconperiod = 5000 -rainbow.delegate.startProbesOnInit = false -probebus.relay.id = ProbeBusRelay@${rainbow.deployment.location} -#- uncomment to enable file-based communication with the ProbeBus Relay -#probebus.relay.file = ${event.log.path}/relay.log - -## Model Manager customization -#- Arch model file -customize.model.path = model/ZNewsSys.acme -customize.model.persist = false -#- Alpha factor for exponential average of properties, expAvg = (1-alpha)*expAvg + alpha*newVal -customize.model.expavg.alpha = 0.30 -customize.model.evaluate.period = 2000 -## Translator customization -#- Gauge spec -customize.gauges.path = model/gauges.yml -#- Probe spec -customize.probes.path = system/probes.yml -#- Operator spec as mapping to effector -customize.archop.map.path = model/op.map -#- Effector spec -customize.effectors.path = system/effectors.yml -## Adaptation Manager -#- Directory of Stitch adaptation script -customize.scripts.path = stitch -customize.profile.tactic.duration.path = stitch/profile-tacticdur.db -#- Utilities description file, Strategy evaluation config, and minimum score threshold -customize.utility.path = stitch/utilities.yml -customize.utility.trackStrategy = uSF -customize.utility.score.minimum.threshold = 0.33 -customize.utility.scenario = scenario 2 -#- Whether to enable prediction, ONLY enable if system has predictor probes! -#customize.prediction.enable = false - -## System configuration information -# -#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: -#customize.system.sim.path = znewspred/znews-transbw.sim -#- if real target system: -customize.system.target.0 = ${rainbow.master.location.host} -customize.system.target.1 = oracle -customize.system.target.2 = waterfall.able.cs.cmu.edu -customize.system.target.size = 3 +################################################################################ +# Purpose: Common configuration file for the Rainbow infrastructure. +# Properties are loaded by class org.sa.rainbow.Rainbow . +# Target: ZNews case study system with Probes, Gauges, and Effectors implemented +# (rainbow.target = znews1-d) +# Framework-defined special properties: +# rainbow.path - the canonical path to the target configuration location +# +# History: see non-target-specific copy +################################################################################ + +### +# Default values for location specific properties, meaning that, if the +# rainbow-.properties file does not specify a value, the default value +# set here is used. + +### Utility mechanism configuration +#- Config for Log4J, with levels: OFF,FATAL,ERROR,WARN,INFO,DEBUG,TRACE,ALL +logging.level = INFO +event.log.path = log +logging.path = ${event.log.path}/rainbow.out +monitoring.log.path = ${event.log.path}/rainbow-data.log +# (default) +#logging.pattern = "%d{ISO8601/yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c %x - %m%n" +#logging.max.size = 1024 +#logging.max.backups = 5 + +### Rainbow component customization +## Rainbow host info and communication infrastructure +#- Location information of the master and this deployment +rainbow.master.location.host = localhost +#- Location information of the deployed delegate +rainbow.deployment.location = ${rainbow.master.location.host} +#- Rainbow service port +rainbow.service.port = 9210 +#- default registry port; change if port-tunneling +rainbow.master.location.port = 1099 +#- OS platform, supported modes are: cygwin | linux +# Use "cygwin" for Windows, "linux" for MacOSX +rainbow.deployment.environment = linux +#- Event infrastructure, type of event middleware: rmi | jms | que +rainbow.event.service = rmi +#- JMS/JBoss-specific configurations +#event.context.factory = org.jnp.interfaces.NamingContextFactory +#event.provider.url = ${rainbow.master.location.host}:1099 +#event.url.prefixes = org.jboss.naming:org.jnp.interfaces + +## RainbowDelegate and ProbeBusRelay configurations +rainbow.delegate.id = RainbowDelegate@${rainbow.deployment.location} +rainbow.delegate.beaconperiod = 5000 +rainbow.delegate.startProbesOnInit = false +probebus.relay.id = ProbeBusRelay@${rainbow.deployment.location} +#- uncomment to enable file-based communication with the ProbeBus Relay +#probebus.relay.file = ${event.log.path}/relay.log + +## Model Manager customization +#- Arch model file +customize.model.path = model/ZNewsSys.acme +customize.model.persist = false +#- Alpha factor for exponential average of properties, expAvg = (1-alpha)*expAvg + alpha*newVal +customize.model.expavg.alpha = 0.30 +customize.model.evaluate.period = 2000 +## Translator customization +#- Gauge spec +customize.gauges.path = model/gauges.yml +#- Probe spec +customize.probes.path = system/probes.yml +#- Operator spec as mapping to effector +customize.archop.map.path = model/op.map +#- Effector spec +customize.effectors.path = system/effectors.yml +## Adaptation Manager +#- Directory of Stitch adaptation script +customize.scripts.path = stitch +customize.profile.tactic.duration.path = stitch/profile-tacticdur.db +#- Utilities description file, Strategy evaluation config, and minimum score threshold +customize.utility.path = stitch/utilities.yml +customize.utility.trackStrategy = uSF +customize.utility.score.minimum.threshold = 0.33 +customize.utility.scenario = scenario 2 +#- Whether to enable prediction, ONLY enable if system has predictor probes! +#customize.prediction.enable = false + +## System configuration information +# +#- if in simulation, specify sim path relative to org.sa.rainbow.model.sim/: +#customize.system.sim.path = znewspred/znews-transbw.sim +#- if real target system: +customize.system.target.0 = ${rainbow.master.location.host} +customize.system.target.1 = oracle +customize.system.target.2 = waterfall.able.cs.cmu.edu +customize.system.target.size = 3 diff --git a/targets/znews1-d/stitch/README.txt b/targets/znews1-d/stitch/README.txt index fe0c94a76..1a5abb8c4 100644 --- a/targets/znews1-d/stitch/README.txt +++ b/targets/znews1-d/stitch/README.txt @@ -1,2 +1,2 @@ -Extension: Stitch scripts must have the extension ".s"; otherwise, the -Adaptation Manager will not know to load it. +Extension: Stitch scripts must have the extension ".s"; otherwise, the +Adaptation Manager will not know to load it. diff --git a/targets/znews1-d/stitch/newssiteStrategies.s b/targets/znews1-d/stitch/newssiteStrategies.s index 3eef21719..55f3bf8a9 100644 --- a/targets/znews1-d/stitch/newssiteStrategies.s +++ b/targets/znews1-d/stitch/newssiteStrategies.s @@ -1,117 +1,117 @@ -/* - * Adaptation script for the News Site example. - */ - -module newssite.strategies; - -import lib "newssiteTactics.s"; - -define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); -define boolean cViolation = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - -define set servers = {select s : T.ServerT in M.components | true}; -define set unhappyClients = {select c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME}; -define int numClients = Set.size({select c : T.ClientT in M.components | true}); -define int numUnhappy = Set.size(unhappyClients); -define float numUnhappyFloat = 1.0*numUnhappy; - -define boolean hiLoad = exists s : T.ServerT in M.components | s.load > M.MAX_UTIL; -define boolean hiRespTime = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; -define boolean lowRespTime = exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - -define float totalCost = Model.sumOverProperty("cost", servers); -define boolean hiCost = totalCost >= M.THRESHOLD_COST; - -define float avgFidelity = Model.sumOverProperty("fidelity", servers) / Set.size(servers); -define boolean lowFi = avgFidelity < M.THRESHOLD_FIDELITY; - -/* This Strategy is simple in that, while it encounters any anomaly in - * experienced response time, it firsts enlists one new server, then lowers - * fidelity one step, and quits - */ -strategy SimpleReduceResponseTime -[ styleApplies && cViolation ] { - t0: (/*hiLoad*/ cViolation) -> enlistServers(1) @[1000 /*ms*/] { - t1: (!cViolation) -> done; - t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[3000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> TNULL; // in this case, we have no more steps to take - } - } -} - -/* This Strategy is smarter in that it looks for a percentage of clients with - * anomalous experienced response time, in which case it enlists a few servers - * in sequence, then lowers fidelity a few steps, then starts delaying Clients - */ -strategy SmarterReduceResponseTime -[ styleApplies && cViolation ] { - define boolean unhappy = numUnhappyFloat/numClients > M.TOLERABLE_PERCENT_UNHAPPY; - - t0: (unhappy) -> enlistServers(1) @[500 /*ms*/] { - t1: (!cViolation) -> done; - t2: (unhappy) -> enlistServers(1) @[2000 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (unhappy) -> lowerFidelity(2, 100) @[2000 /*ms*/] { - t2b1: (!cViolation) -> done; - t2b2: (unhappy) -> do[1] t2; - t2b3: (default) -> TNULL; // in this case, we have no more steps to take - } - } - } -} - -/* This Strategy (experimental!) has the sophistication of reducing fidelity - * for a percentage of requests depending on percentage of unhappy clients - */ -strategy SophisticatedReduceResponseTime -[ styleApplies && cViolation && M.SUPPORT_FRACTION_GRADIENT ] { - define boolean unhappy1 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_1; // e.g., 10% - define boolean unhappy2 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_2; // e.g., 25% - define boolean unhappy3 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_3; // e.g., 50% - - t1: (hiLoad) -> enlistServers(2) @[500 /*ms*/] { - t1a: (!cViolation) -> done; - t1b: (default) -> TNULL; - } - t2: (unhappy1) -> lowerFidelity(1, M.FRACTION_GRADIENT_1) @[500 /*ms*/] { - t2a: (!cViolation) -> done; - t2b: (default) -> do[1] t1; - } - t3: (unhappy2) -> lowerFidelity(2, M.FRACTION_GRADIENT_2) @[500 /*ms*/] { - t3a: (!cViolation) -> done; - t3b: (default) -> do[1] t1; - } - t4: (unhappy3) -> lowerFidelity(4, M.FRACTION_GRADIENT_3) @[500 /*ms*/] { - t4a: (!cViolation) -> done; - t4b: (unhappy3) -> enlistServers(2) @[1000 /*ms*/] { - t4b1: (!cViolation) -> done; - t4b2: (default) -> do[1] t1; - } - t4c: (default) -> do[1] t1; - } -} - -/* This Strategy is triggered by the total server costs rising above acceptable - * threshold; this Strategy reduces the number of active servers - */ -strategy ReduceOverallCost -[ styleApplies && hiCost ] { - t0: (hiCost) -> dischargeServers(1) @[2000 /*ms*/] { - t1: (!hiCost) -> done; - t2: (lowRespTime && hiCost) -> do[2] t0; - t3: (default) -> TNULL; - } -} - -/* This Strategy is triggered by overall fidelity being below acceptable - * threshold; this Strategy raises the fidelity of the servers - */ -strategy ImproveOverallFidelity -[ styleApplies && lowFi ] { - t0: (lowFi) -> raiseFidelity(2, 100) @[800 /*ms*/] { - t1: (!lowFi) -> done; - t2: (lowRespTime && lowFi) -> do[1] t0; - t3: (default) -> TNULL; - } -} +/* + * Adaptation script for the News Site example. + */ + +module newssite.strategies; + +import lib "newssiteTactics.s"; + +define boolean styleApplies = Model.hasType(M, "ClientT") && Model.hasType(M, "ServerT"); +define boolean cViolation = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + +define set servers = {select s : T.ServerT in M.components | true}; +define set unhappyClients = {select c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME}; +define int numClients = Set.size({select c : T.ClientT in M.components | true}); +define int numUnhappy = Set.size(unhappyClients); +define float numUnhappyFloat = 1.0*numUnhappy; + +define boolean hiLoad = exists s : T.ServerT in M.components | s.load > M.MAX_UTIL; +define boolean hiRespTime = exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; +define boolean lowRespTime = exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + +define float totalCost = Model.sumOverProperty("cost", servers); +define boolean hiCost = totalCost >= M.THRESHOLD_COST; + +define float avgFidelity = Model.sumOverProperty("fidelity", servers) / Set.size(servers); +define boolean lowFi = avgFidelity < M.THRESHOLD_FIDELITY; + +/* This Strategy is simple in that, while it encounters any anomaly in + * experienced response time, it firsts enlists one new server, then lowers + * fidelity one step, and quits + */ +strategy SimpleReduceResponseTime +[ styleApplies && cViolation ] { + t0: (/*hiLoad*/ cViolation) -> enlistServers(1) @[1000 /*ms*/] { + t1: (!cViolation) -> done; + t2: (/*hiRespTime*/ cViolation) -> lowerFidelity(2, 100) @[3000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> TNULL; // in this case, we have no more steps to take + } + } +} + +/* This Strategy is smarter in that it looks for a percentage of clients with + * anomalous experienced response time, in which case it enlists a few servers + * in sequence, then lowers fidelity a few steps, then starts delaying Clients + */ +strategy SmarterReduceResponseTime +[ styleApplies && cViolation ] { + define boolean unhappy = numUnhappyFloat/numClients > M.TOLERABLE_PERCENT_UNHAPPY; + + t0: (unhappy) -> enlistServers(1) @[500 /*ms*/] { + t1: (!cViolation) -> done; + t2: (unhappy) -> enlistServers(1) @[2000 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (unhappy) -> lowerFidelity(2, 100) @[2000 /*ms*/] { + t2b1: (!cViolation) -> done; + t2b2: (unhappy) -> do[1] t2; + t2b3: (default) -> TNULL; // in this case, we have no more steps to take + } + } + } +} + +/* This Strategy (experimental!) has the sophistication of reducing fidelity + * for a percentage of requests depending on percentage of unhappy clients + */ +strategy SophisticatedReduceResponseTime +[ styleApplies && cViolation && M.SUPPORT_FRACTION_GRADIENT ] { + define boolean unhappy1 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_1; // e.g., 10% + define boolean unhappy2 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_2; // e.g., 25% + define boolean unhappy3 = numUnhappyFloat/numClients > M.UNHAPPY_GRADIENT_3; // e.g., 50% + + t1: (hiLoad) -> enlistServers(2) @[500 /*ms*/] { + t1a: (!cViolation) -> done; + t1b: (default) -> TNULL; + } + t2: (unhappy1) -> lowerFidelity(1, M.FRACTION_GRADIENT_1) @[500 /*ms*/] { + t2a: (!cViolation) -> done; + t2b: (default) -> do[1] t1; + } + t3: (unhappy2) -> lowerFidelity(2, M.FRACTION_GRADIENT_2) @[500 /*ms*/] { + t3a: (!cViolation) -> done; + t3b: (default) -> do[1] t1; + } + t4: (unhappy3) -> lowerFidelity(4, M.FRACTION_GRADIENT_3) @[500 /*ms*/] { + t4a: (!cViolation) -> done; + t4b: (unhappy3) -> enlistServers(2) @[1000 /*ms*/] { + t4b1: (!cViolation) -> done; + t4b2: (default) -> do[1] t1; + } + t4c: (default) -> do[1] t1; + } +} + +/* This Strategy is triggered by the total server costs rising above acceptable + * threshold; this Strategy reduces the number of active servers + */ +strategy ReduceOverallCost +[ styleApplies && hiCost ] { + t0: (hiCost) -> dischargeServers(1) @[2000 /*ms*/] { + t1: (!hiCost) -> done; + t2: (lowRespTime && hiCost) -> do[2] t0; + t3: (default) -> TNULL; + } +} + +/* This Strategy is triggered by overall fidelity being below acceptable + * threshold; this Strategy raises the fidelity of the servers + */ +strategy ImproveOverallFidelity +[ styleApplies && lowFi ] { + t0: (lowFi) -> raiseFidelity(2, 100) @[800 /*ms*/] { + t1: (!lowFi) -> done; + t2: (lowRespTime && lowFi) -> do[1] t0; + t3: (default) -> TNULL; + } +} diff --git a/targets/znews1-d/stitch/newssiteTactics.s b/targets/znews1-d/stitch/newssiteTactics.s index a0efdb740..0684601ef 100644 --- a/targets/znews1-d/stitch/newssiteTactics.s +++ b/targets/znews1-d/stitch/newssiteTactics.s @@ -1,118 +1,118 @@ -module newssite.tactics; - -import model "ZNewsSys.acme" { ZNewsSys as M, ZNewsFam as T }; -import op "znews1.operator.EffectOp" { EffectOp as S }; -import op "org.sa.rainbow.stitch.lib.*"; - - -/** - * Enlist n free servers into service pool. - * Utility: [v] R; [^] C; [<>] F - */ -tactic enlistServers (int n) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // there should be enough available server resources - Model.availableServices(T.ServerT) >= n; - } - action { - set servers = Set.randomSubset(Model.findServices(T.ServerT), n); - for (T.ServerT freeSvr : servers) { - S.activateServer(freeSvr); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Deactivate n servers from service pool into free pool. - * Utility: [^] R; [v] C; [<>] F - */ -tactic dischargeServers (int n) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there should be enough servers to discharge - Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; - } - action { - set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; - set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); - for (T.ServerT s : subLowUtilSvrs) { - S.deactivateServer(s); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Lowers fidelity by integral steps for percent of requests. - * Utility: [v] R; [v] C; [v] F - */ -tactic lowerFidelity (int step, float fracReq) { - condition { - // some client should be experiencing high response time - exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; - // exists server with fidelity to lower - exists s : T.ServerT in M.components | s.fidelity > step; - } - action { - // retrieve set of servers who still have enough fidelity grade to lower - set servers = { select s : T.ServerT in M.components | s.fidelity > step }; - for (T.ServerT s : servers) { - S.setFidelity(s, s.fidelity - step); - } - } - effect { - // response time decreasing below threshold should result - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/** - * Raises fidelity by integral steps for percent of requests. - * Utility: [^] R; [^] C; [^] F - */ -tactic raiseFidelity (int step, float fracReq) { - condition { - // there should be NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - // there exists some client with below low-threshold response time - exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; - } - action { - // first find the lowest fidelity set - set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; -/* smarter way of doing things... - int lowestFidelity = M.MAX_FIDELITY_LEVEL; - for (T.ServerT s : servers) { - if (s.fidelity < lowestFidelity) { - lowestFidelity = s.fidelity; - } - } - // find only servers with this lowest fidelity setting, and raise fidelity - servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; -*/ - for (T.ServerT s : servers) { - S.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); - } - } - effect { - // still NO client with high response time - forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; - } -} - -/* - T5) delayClients(set clients) - utility: [^] R; [v] C; [v] F - T6) blockClients(set clients) - utility: [^] R; [v] C; [v] F -*/ +module newssite.tactics; + +import model "ZNewsSys.acme" { ZNewsSys as M, ZNewsFam as T }; +import op "znews1.operator.EffectOp" { EffectOp as S }; +import op "org.sa.rainbow.stitch.lib.*"; + + +/** + * Enlist n free servers into service pool. + * Utility: [v] R; [^] C; [<>] F + */ +tactic enlistServers (int n) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // there should be enough available server resources + Model.availableServices(T.ServerT) >= n; + } + action { + set servers = Set.randomSubset(Model.findServices(T.ServerT), n); + for (T.ServerT freeSvr : servers) { + S.activateServer(freeSvr); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Deactivate n servers from service pool into free pool. + * Utility: [^] R; [v] C; [<>] F + */ +tactic dischargeServers (int n) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there should be enough servers to discharge + Set.size({ select s : T.ServerT in M.components | s.load < M.MIN_UTIL }) >= n; + } + action { + set lowUtilSvrs = { select s : T.ServerT in M.components | s.load < M.MIN_UTIL }; + set subLowUtilSvrs = Set.randomSubset(lowUtilSvrs, n); + for (T.ServerT s : subLowUtilSvrs) { + S.deactivateServer(s); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Lowers fidelity by integral steps for percent of requests. + * Utility: [v] R; [v] C; [v] F + */ +tactic lowerFidelity (int step, float fracReq) { + condition { + // some client should be experiencing high response time + exists c : T.ClientT in M.components | c.experRespTime > M.MAX_RESPTIME; + // exists server with fidelity to lower + exists s : T.ServerT in M.components | s.fidelity > step; + } + action { + // retrieve set of servers who still have enough fidelity grade to lower + set servers = { select s : T.ServerT in M.components | s.fidelity > step }; + for (T.ServerT s : servers) { + S.setFidelity(s, s.fidelity - step); + } + } + effect { + // response time decreasing below threshold should result + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/** + * Raises fidelity by integral steps for percent of requests. + * Utility: [^] R; [^] C; [^] F + */ +tactic raiseFidelity (int step, float fracReq) { + condition { + // there should be NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + // there exists some client with below low-threshold response time + exists c : T.ClientT in M.components | c.experRespTime < M.MIN_RESPTIME; + } + action { + // first find the lowest fidelity set + set servers = { select s : T.ServerT in M.components | s.fidelity <= M.MAX_FIDELITY_LEVEL - step}; +/* smarter way of doing things... + int lowestFidelity = M.MAX_FIDELITY_LEVEL; + for (T.ServerT s : servers) { + if (s.fidelity < lowestFidelity) { + lowestFidelity = s.fidelity; + } + } + // find only servers with this lowest fidelity setting, and raise fidelity + servers = { select s : T.ServerT in M.components | s.fidelity <= lowestFidelity}; +*/ + for (T.ServerT s : servers) { + S.setFidelity(s, java.lang.Math.min(s.fidelity + step, M.MAX_FIDELITY_LEVEL)); + } + } + effect { + // still NO client with high response time + forall c : T.ClientT in M.components | c.experRespTime <= M.MAX_RESPTIME; + } +} + +/* + T5) delayClients(set clients) + utility: [^] R; [v] C; [v] F + T6) blockClients(set clients) + utility: [^] R; [v] C; [v] F +*/ diff --git a/targets/znews1-d/stitch/utilities.yml b/targets/znews1-d/stitch/utilities.yml index 3f8d1ffc3..7f472fe38 100644 --- a/targets/znews1-d/stitch/utilities.yml +++ b/targets/znews1-d/stitch/utilities.yml @@ -1,106 +1,106 @@ -# Created September 5, 2006 (Shang-Wen Cheng) -# -# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y -# is the utility in the range [0,1] -# -# History: -# - [SWC 2006.09.05] Created file, defined utilities for ZNews. -# - [SWC 2007.03.13] Added utility dimension to incorporate strategy failure history. -# -utilities: - uR: - label: "Average Response Time" - mapping: "[EAvg]ClientT.experRespTime" - description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" - utility: - 0: 1.00 - 100: 1.00 - 200: 0.99 - 500: 0.90 - 1000: 0.75 - 1500: 0.50 - 2000: 0.25 - 4000: 0.00 - uF: - label: "Average Fidelity" - mapping: "[EAvg]ServerT.fidelity" - description: "Server content fidelity in level, F, defined as an int property 'ServerT.fidelity' in the architecture, with some artificial range to be determined" - utility: - 1: 0.80 - 5: 1.00 - uC: - label: "Average Server Cost" - mapping: "[EAvg]ServerT.cost" - description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers" - utility: - 0: 1.00 - 1: 0.90 - 5: 0.20 - 10: 0.00 -# uD: -# label: "Service Disruption" -# mapping: "[EAvg]ServerT.rejectedRequests" -# description: "Service disruption measured by requests rejected" -# utility: -# 1: 1.00 -# 2: 0.98 -# 3: 0.00 -# 5: 0.00 - uSF: - label: "Historical Strategy Failure" - mapping: "[EAvg]Strategy.rateFailure" - description: "Rate of failure, in fraction, of a strategy; utility has no effect if strategy history is not kept" - utility: - 0: 1.00 - 0.5: 0.01 - 1: 0.00 - -# Weighted utility preferences, each set should sum to 1. -# Three scenarios: -# 1.) Nominal request rate -> Sustained, peak request rate -> Nominal request rate -# 2.) Nominal request rate -> Transient, peak request rate -> Nominal request rate -# 3.) Any request rate -> Abnormally high request rate (e.g., Ramsey case) -> Any request rate -# -weights: - scenario 1: - uR: 0.3 - uF: 0.4 - uC: 0.2 - uSF: 0.1 - scenario 2: - uR: 0.5 - uF: 0.25 - uC: 0.15 - uSF: 0.1 - scenario 3: - uR: 0.45 - uF: 0.3 - uC: 0.1 - uSF: 0.15 - -# Tactic quality attribute vectors -# -vectors: -# Utility: [v] R; [^] C; [<>] F -# assume each server will drop response time by 1000 ms and increase cost by 1 unit - enlistServers: - uR: -1000 - uF: 0 - uC: +1.00 -# Utility: [^] R; [v] C; [<>] F - dischargeServers: - uR: +1000 - uF: 0 - uC: -1.00 - -# Utility: [v] R; [v] C; [v] F -# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit - lowerFidelity: - uR: -500 - uF: -2 - uC: -0.10 -# Utility: [^] R; [^] C; [^] F - raiseFidelity: - uR: +500 - uF: +2 - uC: +0.10 +# Created September 5, 2006 (Shang-Wen Cheng) +# +# Utility curves, defined as X:Y pairs, where X is value of the dimension and Y +# is the utility in the range [0,1] +# +# History: +# - [SWC 2006.09.05] Created file, defined utilities for ZNews. +# - [SWC 2007.03.13] Added utility dimension to incorporate strategy failure history. +# +utilities: + uR: + label: "Average Response Time" + mapping: "[EAvg]ClientT.experRespTime" + description: "Client experienced response time in milliseconds, R, defined as a float property 'ClientT.experRespTime' in the architecture" + utility: + 0: 1.00 + 100: 1.00 + 200: 0.99 + 500: 0.90 + 1000: 0.75 + 1500: 0.50 + 2000: 0.25 + 4000: 0.00 + uF: + label: "Average Fidelity" + mapping: "[EAvg]ServerT.fidelity" + description: "Server content fidelity in level, F, defined as an int property 'ServerT.fidelity' in the architecture, with some artificial range to be determined" + utility: + 1: 0.80 + 5: 1.00 + uC: + label: "Average Server Cost" + mapping: "[EAvg]ServerT.cost" + description: "Server cost in unit/hr, C, averaged from a float property 'ServerT.cost' in the architecture, and captures average cost across all servers" + utility: + 0: 1.00 + 1: 0.90 + 5: 0.20 + 10: 0.00 +# uD: +# label: "Service Disruption" +# mapping: "[EAvg]ServerT.rejectedRequests" +# description: "Service disruption measured by requests rejected" +# utility: +# 1: 1.00 +# 2: 0.98 +# 3: 0.00 +# 5: 0.00 + uSF: + label: "Historical Strategy Failure" + mapping: "[EAvg]Strategy.rateFailure" + description: "Rate of failure, in fraction, of a strategy; utility has no effect if strategy history is not kept" + utility: + 0: 1.00 + 0.5: 0.01 + 1: 0.00 + +# Weighted utility preferences, each set should sum to 1. +# Three scenarios: +# 1.) Nominal request rate -> Sustained, peak request rate -> Nominal request rate +# 2.) Nominal request rate -> Transient, peak request rate -> Nominal request rate +# 3.) Any request rate -> Abnormally high request rate (e.g., Ramsey case) -> Any request rate +# +weights: + scenario 1: + uR: 0.3 + uF: 0.4 + uC: 0.2 + uSF: 0.1 + scenario 2: + uR: 0.5 + uF: 0.25 + uC: 0.15 + uSF: 0.1 + scenario 3: + uR: 0.45 + uF: 0.3 + uC: 0.1 + uSF: 0.15 + +# Tactic quality attribute vectors +# +vectors: +# Utility: [v] R; [^] C; [<>] F +# assume each server will drop response time by 1000 ms and increase cost by 1 unit + enlistServers: + uR: -1000 + uF: 0 + uC: +1.00 +# Utility: [^] R; [v] C; [<>] F + dischargeServers: + uR: +1000 + uF: 0 + uC: -1.00 + +# Utility: [v] R; [v] C; [v] F +# assume each level of fidelity reduces response time by 500 ms, and reduce cost by 10% of unit + lowerFidelity: + uR: -500 + uF: -2 + uC: -0.10 +# Utility: [^] R; [^] C; [^] F + raiseFidelity: + uR: +500 + uF: +2 + uC: +0.10 diff --git a/targets/znews1-d/system/debpkgs.txt b/targets/znews1-d/system/debpkgs.txt index 96003b50f..544fb5fca 100644 --- a/targets/znews1-d/system/debpkgs.txt +++ b/targets/znews1-d/system/debpkgs.txt @@ -1,19 +1,19 @@ - -Debian packages required: -* sysstat - iostat, vmstat, etc. - -Nice packages: -* bc - calculator (under section "math") -* ganglia-monitor?? - for the Ganglia monitoring framework - -If compiling own Apache HTTPd 2.0.x, PHP, and MySQL... -Things to have in the system in order to compile/build: -- libncurses5 -- gcc/g++ 4.0 (3.3+ should work) -- pkg-config -- make/automake(1.8)/autoconf -- flex (lex generator) -- gettext -- openssl/libssl-dev -- zlib-dev -- libxml2/libxml2-dev + +Debian packages required: +* sysstat - iostat, vmstat, etc. + +Nice packages: +* bc - calculator (under section "math") +* ganglia-monitor?? - for the Ganglia monitoring framework + +If compiling own Apache HTTPd 2.0.x, PHP, and MySQL... +Things to have in the system in order to compile/build: +- libncurses5 +- gcc/g++ 4.0 (3.3+ should work) +- pkg-config +- make/automake(1.8)/autoconf +- flex (lex generator) +- gettext +- openssl/libssl-dev +- zlib-dev +- libxml2/libxml2-dev diff --git a/targets/znews1-d/system/effectors.yml b/targets/znews1-d/system/effectors.yml index 12501fe78..8a117feef 100644 --- a/targets/znews1-d/system/effectors.yml +++ b/targets/znews1-d/system/effectors.yml @@ -1,53 +1,53 @@ -# Created January 30, 2007 (Shang-Wen Cheng) -# -# Effector descriptions. -# -# History: -# - [SWC 2007.01.30] Created file, populated ZNews effector descriptions. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# -vars: - _effectors.commonPath: "${rainbow.path}/system/effectors" - -effectors: -# test from GUI with , SetFidelity, fidelity=<1|3|5> - setFidelity1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/changeFidelity.pl" - argument: "-l {fidelity}" - activateServer1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/turnServer.pl" - argument: "-s on" - deactivateServer1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/turnServer.pl" - argument: "-s off" -# test from GUI with , RandomReject, frequency=<0..?> - randomReject1: - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_effectors.commonPath}/setRandomReject.pl" - argument: "-r {frequency}" - killDelegate1: - location: "${customize.system.target.1}" - type: java - javaInfo: - class : org.sa.rainbow.translator.effectors.KillDelegateEffector - -unused-effectors: - killDelegate2: -# Causes the designated RainbowDelegate to exit process -# Illustrates effector time-out as well as tests executor execution - location: "${customize.system.target.3}" - type: java - javaInfo: - class : org.sa.rainbow.translator.effectors.KillDelegateEffector - +# Created January 30, 2007 (Shang-Wen Cheng) +# +# Effector descriptions. +# +# History: +# - [SWC 2007.01.30] Created file, populated ZNews effector descriptions. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# +vars: + _effectors.commonPath: "${rainbow.path}/system/effectors" + +effectors: +# test from GUI with , SetFidelity, fidelity=<1|3|5> + setFidelity1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/changeFidelity.pl" + argument: "-l {fidelity}" + activateServer1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/turnServer.pl" + argument: "-s on" + deactivateServer1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/turnServer.pl" + argument: "-s off" +# test from GUI with , RandomReject, frequency=<0..?> + randomReject1: + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_effectors.commonPath}/setRandomReject.pl" + argument: "-r {frequency}" + killDelegate1: + location: "${customize.system.target.1}" + type: java + javaInfo: + class : org.sa.rainbow.translator.effectors.KillDelegateEffector + +unused-effectors: + killDelegate2: +# Causes the designated RainbowDelegate to exit process +# Illustrates effector time-out as well as tests executor execution + location: "${customize.system.target.3}" + type: java + javaInfo: + class : org.sa.rainbow.translator.effectors.KillDelegateEffector + diff --git a/targets/znews1-d/system/effectors/changeFidelity.pl b/targets/znews1-d/system/effectors/changeFidelity.pl index a24df7cef..80123eba4 100644 --- a/targets/znews1-d/system/effectors/changeFidelity.pl +++ b/targets/znews1-d/system/effectors/changeFidelity.pl @@ -1,83 +1,83 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -my $isCygwin = 0; -my $uname; -if ( -e "/bin/uname" ) { - $uname = `/bin/uname`; -} elsif ( -e "/usr/bin/uname" ) { - $uname = `/usr/bin/uname`; -} else { - $uname = "UNKNOWN"; -} -if ($uname =~ /CYGWIN/i) { - $isCygwin = 1; -} - -chomp(my $SCRIPT_DIR = `/usr/bin/dirname "$0"`); -my $APACHE_CONF_DIR = ($isCygwin) ? - "/cygdrive/c/server/Apache2/conf" : - "/etc/apache2"; -my $APACHE_CONF_FILE = ($isCygwin) ? - "httpd.conf" : - "apache2.conf"; -my $APACHE_SITE_DIR = "$APACHE_CONF_DIR/sites-available"; -my $APACHE_SITE_FILE = "z.com"; -my $SOURCE_CONF_DIR = ($isCygwin) ? - "$SCRIPT_DIR/fidelity.conf/cygwin" : - "$SCRIPT_DIR/fidelity.conf/oracle"; - -sub usage() { - print STDERR << "EOF"; - -This effector program changes the webserver fidelity level (1,3,5). - - usage: $0 [option] -l level - - -h : this (help) message - -l level : the new fidelity setting, should be 1, 3, or 5 (0 for original) - -EOF - exit; -} - -# get options -my %opts; -getopts('hl:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{l})); - -my $level = $opts{l}; -usage() if ($level != 0 && $level != 1 && $level != 3 && $level != 5); - -my $fExt = "-f"; -if ($level == 0) { - if ($isCygwin) { - $fExt = ".default"; - } else { - $fExt .= "5"; - } -} else { - $fExt .= $level; -} - -if ($isCygwin) { - - print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; - print `/usr/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; - print "\nGracefully restarting Apache..."; - print `/cygdrive/c/server/Apache2/bin/Apache.exe -w -n "Apache2" -k restart`; - print "\nDone."; - -} else { - - print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; - print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; - print "\nSwapping site to level $level..."; - print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_SITE_FILE$fExt $APACHE_SITE_DIR/$APACHE_SITE_FILE`; - print "\nGracefully restarting Apache..."; - print `/etc/init.d/apache2 reload`; - print "\nDone."; - -} +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +my $isCygwin = 0; +my $uname; +if ( -e "/bin/uname" ) { + $uname = `/bin/uname`; +} elsif ( -e "/usr/bin/uname" ) { + $uname = `/usr/bin/uname`; +} else { + $uname = "UNKNOWN"; +} +if ($uname =~ /CYGWIN/i) { + $isCygwin = 1; +} + +chomp(my $SCRIPT_DIR = `/usr/bin/dirname "$0"`); +my $APACHE_CONF_DIR = ($isCygwin) ? + "/cygdrive/c/server/Apache2/conf" : + "/etc/apache2"; +my $APACHE_CONF_FILE = ($isCygwin) ? + "httpd.conf" : + "apache2.conf"; +my $APACHE_SITE_DIR = "$APACHE_CONF_DIR/sites-available"; +my $APACHE_SITE_FILE = "z.com"; +my $SOURCE_CONF_DIR = ($isCygwin) ? + "$SCRIPT_DIR/fidelity.conf/cygwin" : + "$SCRIPT_DIR/fidelity.conf/oracle"; + +sub usage() { + print STDERR << "EOF"; + +This effector program changes the webserver fidelity level (1,3,5). + + usage: $0 [option] -l level + + -h : this (help) message + -l level : the new fidelity setting, should be 1, 3, or 5 (0 for original) + +EOF + exit; +} + +# get options +my %opts; +getopts('hl:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{l})); + +my $level = $opts{l}; +usage() if ($level != 0 && $level != 1 && $level != 3 && $level != 5); + +my $fExt = "-f"; +if ($level == 0) { + if ($isCygwin) { + $fExt = ".default"; + } else { + $fExt .= "5"; + } +} else { + $fExt .= $level; +} + +if ($isCygwin) { + + print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; + print `/usr/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; + print "\nGracefully restarting Apache..."; + print `/cygdrive/c/server/Apache2/bin/Apache.exe -w -n "Apache2" -k restart`; + print "\nDone."; + +} else { + + print "Copying level $level $APACHE_CONF_FILE in $APACHE_CONF_DIR..."; + print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_CONF_FILE$fExt $APACHE_CONF_DIR/$APACHE_CONF_FILE`; + print "\nSwapping site to level $level..."; + print `/bin/cp -f $SOURCE_CONF_DIR/$APACHE_SITE_FILE$fExt $APACHE_SITE_DIR/$APACHE_SITE_FILE`; + print "\nGracefully restarting Apache..."; + print `/etc/init.d/apache2 reload`; + print "\nDone."; + +} diff --git a/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf b/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf index 4adbba299..5b13550db 100644 --- a/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf +++ b/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf @@ -1,967 +1,967 @@ -### Fidelity-5 Conf file -## - full featured -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -AddType application/x-httpd-php .php - -# configure the path to php.ini -PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.php index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -AddType text/html .shtml -AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-5 Conf file +## - full featured +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +AddType application/x-httpd-php .php + +# configure the path to php.ini +PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.php index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +AddType text/html .shtml +AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 b/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 index 95dd86268..6907bc89d 100644 --- a/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 +++ b/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f1 @@ -1,974 +1,974 @@ -### Fidelity-1 Conf file -## - reduced timeout from 300 to 30 sec -## - reduced max keep alive reqs from 100 to 10 -## - threads per child reduced from 250 to 10 -## - set an upper limit of max requests per child to 5 -## - excluded user dir function -## - excluded modules dav, imap, rewrite, userdir -## - reduced Directory Options to indexes & symlink only -## - reduced AllowOverride to None -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 30 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 10 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 10 -MaxRequestsPerChild 5 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -#LoadModule cgi_module modules/mod_cgi.so -#LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -#LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -#LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -#LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -#AddType application/x-httpd-php .php - -# configure the path to php.ini -#PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www1" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options Indexes SymLinksIfOwnerMatch - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride None - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -#UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - -# -# Options Indexes -# AllowOverride None -# Order allow,deny -# Allow from all -# -# -# SetHandler type-map -# -# -# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 -# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 -# - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# -# -# AllowOverride None -# Options None -# Order allow,deny -# Allow from all -# - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -#AddType application/x-compress .Z -#AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# -# -# Include conf/ssl.conf -# - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-1 Conf file +## - reduced timeout from 300 to 30 sec +## - reduced max keep alive reqs from 100 to 10 +## - threads per child reduced from 250 to 10 +## - set an upper limit of max requests per child to 5 +## - excluded user dir function +## - excluded modules dav, imap, rewrite, userdir +## - reduced Directory Options to indexes & symlink only +## - reduced AllowOverride to None +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 30 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 10 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 10 +MaxRequestsPerChild 5 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule cgi_module modules/mod_cgi.so +#LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +#LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +#LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +#LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +#AddType application/x-httpd-php .php + +# configure the path to php.ini +#PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www1" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options Indexes SymLinksIfOwnerMatch + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride None + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +#UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + +# +# Options Indexes +# AllowOverride None +# Order allow,deny +# Allow from all +# +# +# SetHandler type-map +# +# +# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 +# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 +# + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +# +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +# + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +#AddType application/x-compress .Z +#AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# +# +# Include conf/ssl.conf +# + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 b/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 index 7fd0f402b..eaab99348 100644 --- a/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 +++ b/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f3 @@ -1,971 +1,971 @@ -### Fidelity-3 Conf file -## - excluded CGI handling -## - excluded PHP module -## - excluded SSI -## - excluded compression type -## - excluded server manual -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -#LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -#AddType application/x-httpd-php .php - -# configure the path to php.ini -#PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www3" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - -# -# Options Indexes -# AllowOverride None -# Order allow,deny -# Allow from all -# -# -# SetHandler type-map -# -# -# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 -# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 -# - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# -# -# AllowOverride None -# Options None -# Order allow,deny -# Allow from all -# - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -#AddType application/x-compress .Z -#AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-3 Conf file +## - excluded CGI handling +## - excluded PHP module +## - excluded SSI +## - excluded compression type +## - excluded server manual +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +#LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +#AddType application/x-httpd-php .php + +# configure the path to php.ini +#PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www3" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +#AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + +# +# Options Indexes +# AllowOverride None +# Order allow,deny +# Allow from all +# +# +# SetHandler type-map +# +# +# SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 +# RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 +# + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +#ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +# +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +# + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +#AddType application/x-compress .Z +#AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 b/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 index 4adbba299..5b13550db 100644 --- a/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 +++ b/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf-f5 @@ -1,967 +1,967 @@ -### Fidelity-5 Conf file -## - full featured -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# For PHP 5 do something like this: -LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" -#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" -#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" -AddType application/x-httpd-php .php - -# configure the path to php.ini -PHPIniDir "C:/server/php-5.1" - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin sw.cheng@acm.org - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride Indexes Options FileInfo AuthConfig Limit - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var index.php index.asp - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -#- Left enabled to allow virtual CGI SSI from this directory, if needed -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -AddHandler cgi-script .cgi .pl - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -AddType text/html .shtml -AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# - -Alias /wiki "C:/server/www/w/index.php" -#Alias /index.php "C:/server/www/w/index.php" +### Fidelity-5 Conf file +## - full featured +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# For PHP 5 do something like this: +LoadModule php5_module "c:/server/php-5.1/php5apache2.dll" +#LoadModule dav_svn_module "C:/server/Subversion/bin/mod_dav_svn.so" +#LoadModule authz_svn_module "C:/server/Subversion/bin/mod_authz_svn.so" +AddType application/x-httpd-php .php + +# configure the path to php.ini +PHPIniDir "C:/server/php-5.1" + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin sw.cheng@acm.org + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/rainbow/oracle/targets/znews1-d/system/webpages/www5" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options ExecCGI MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride Indexes Options FileInfo AuthConfig Limit + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var index.php index.asp + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +#- Left enabled to allow virtual CGI SSI from this directory, if needed +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +AddHandler cgi-script .cgi .pl + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +AddType text/html .shtml +AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# + +Alias /wiki "C:/server/www/w/index.php" +#Alias /index.php "C:/server/www/w/index.php" diff --git a/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf.default b/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf.default index 20dd3c11d..ff8505b79 100644 --- a/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf.default +++ b/targets/znews1-d/system/effectors/fidelity.conf/cygwin/httpd.conf.default @@ -1,952 +1,952 @@ -# -# Based upon the NCSA server configuration files originally by Rob McCool. -# -# This is the main Apache server configuration file. It contains the -# configuration directives that give the server its instructions. -# See for detailed information about -# the directives. -# -# Do NOT simply read the instructions in here without understanding -# what they do. They're here only as hints or reminders. If you are unsure -# consult the online docs. You have been warned. -# -# The configuration directives are grouped into three basic sections: -# 1. Directives that control the operation of the Apache server process as a -# whole (the 'global environment'). -# 2. Directives that define the parameters of the 'main' or 'default' server, -# which responds to requests that aren't handled by a virtual host. -# These directives also provide default values for the settings -# of all virtual hosts. -# 3. Settings for virtual hosts, which allow Web requests to be sent to -# different IP addresses or hostnames and have them handled by the -# same Apache server process. -# -# Configuration and logfile names: If the filenames you specify for many -# of the server's control files begin with "/" (or "drive:/" for Win32), the -# server will use that explicit path. If the filenames do *not* begin -# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" -# with ServerRoot set to "C:/server/Apache2" will be interpreted by the -# server as "C:/server/Apache2/logs/foo.log". -# -# NOTE: Where filenames are specified, you must use forward slashes -# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). -# If a drive letter is omitted, the drive on which Apache.exe is located -# will be used by default. It is recommended that you always supply -# an explicit drive letter in absolute paths, however, to avoid -# confusion. -# - -### Section 1: Global Environment -# -# The directives in this section affect the overall operation of Apache, -# such as the number of concurrent requests it can handle or where it -# can find its configuration files. -# - -# -# ServerRoot: The top of the directory tree under which the server's -# configuration, error, and log files are kept. -# -# NOTE! If you intend to place this on an NFS (or otherwise network) -# mounted filesystem then please read the LockFile documentation (available -# at ); -# you will save yourself a lot of trouble. -# -# Do NOT add a slash at the end of the directory path. -# -ServerRoot "C:/server/Apache2" - -# -# ScoreBoardFile: File used to store internal server process information. -# If unspecified (the default), the scoreboard will be stored in an -# anonymous shared memory segment, and will be unavailable to third-party -# applications. -# If specified, ensure that no two invocations of Apache share the same -# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. -# -#ScoreBoardFile logs/apache_runtime_status - -# -# PidFile: The file in which the server should record its process -# identification number when it starts. -# -PidFile logs/httpd.pid - -# -# Timeout: The number of seconds before receives and sends time out. -# -Timeout 300 - -# -# KeepAlive: Whether or not to allow persistent connections (more than -# one request per connection). Set to "Off" to deactivate. -# -KeepAlive On - -# -# MaxKeepAliveRequests: The maximum number of requests to allow -# during a persistent connection. Set to 0 to allow an unlimited amount. -# We recommend you leave this number high, for maximum performance. -# -MaxKeepAliveRequests 100 - -# -# KeepAliveTimeout: Number of seconds to wait for the next request from the -# same client on the same connection. -# -KeepAliveTimeout 15 - -## -## Server-Pool Size Regulation (MPM specific) -## - -# WinNT MPM -# ThreadsPerChild: constant number of worker threads in the server process -# MaxRequestsPerChild: maximum number of requests a server process serves - -ThreadsPerChild 250 -MaxRequestsPerChild 0 - - -# -# Listen: Allows you to bind Apache to specific IP addresses and/or -# ports, instead of the default. See also the -# directive. -# -# Change this to Listen on specific IP addresses as shown below to -# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) -# -#Listen 12.34.56.78:80 -Listen 80 - -# -# Dynamic Shared Object (DSO) Support -# -# To be able to use the functionality of a module which was built as a DSO you -# have to place corresponding `LoadModule' lines at this location so the -# directives contained in it are actually available _before_ they are used. -# Statically compiled modules (those listed by `httpd -l') do not need -# to be loaded here. -# -# Example: -# LoadModule foo_module modules/mod_foo.so -# -LoadModule access_module modules/mod_access.so -LoadModule actions_module modules/mod_actions.so -LoadModule alias_module modules/mod_alias.so -LoadModule asis_module modules/mod_asis.so -LoadModule auth_module modules/mod_auth.so -#LoadModule auth_anon_module modules/mod_auth_anon.so -#LoadModule auth_dbm_module modules/mod_auth_dbm.so -#LoadModule auth_digest_module modules/mod_auth_digest.so -LoadModule autoindex_module modules/mod_autoindex.so -#LoadModule cern_meta_module modules/mod_cern_meta.so -LoadModule cgi_module modules/mod_cgi.so -#LoadModule dav_module modules/mod_dav.so -#LoadModule dav_fs_module modules/mod_dav_fs.so -LoadModule dir_module modules/mod_dir.so -LoadModule env_module modules/mod_env.so -#LoadModule expires_module modules/mod_expires.so -#LoadModule file_cache_module modules/mod_file_cache.so -#LoadModule headers_module modules/mod_headers.so -LoadModule imap_module modules/mod_imap.so -LoadModule include_module modules/mod_include.so -#LoadModule info_module modules/mod_info.so -LoadModule isapi_module modules/mod_isapi.so -LoadModule log_config_module modules/mod_log_config.so -LoadModule mime_module modules/mod_mime.so -#LoadModule mime_magic_module modules/mod_mime_magic.so -#LoadModule proxy_module modules/mod_proxy.so -#LoadModule proxy_connect_module modules/mod_proxy_connect.so -#LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so -LoadModule negotiation_module modules/mod_negotiation.so -#LoadModule rewrite_module modules/mod_rewrite.so -LoadModule setenvif_module modules/mod_setenvif.so -#LoadModule speling_module modules/mod_speling.so -#LoadModule status_module modules/mod_status.so -#LoadModule unique_id_module modules/mod_unique_id.so -LoadModule userdir_module modules/mod_userdir.so -#LoadModule usertrack_module modules/mod_usertrack.so -#LoadModule vhost_alias_module modules/mod_vhost_alias.so -#LoadModule ssl_module modules/mod_ssl.so - -# -# ExtendedStatus controls whether Apache will generate "full" status -# information (ExtendedStatus On) or just basic information (ExtendedStatus -# Off) when the "server-status" handler is called. The default is Off. -# -#ExtendedStatus On - -### Section 2: 'Main' server configuration -# -# The directives in this section set up the values used by the 'main' -# server, which responds to any requests that aren't handled by a -# definition. These values also provide defaults for -# any containers you may define later in the file. -# -# All of these directives may appear inside containers, -# in which case these default settings will be overridden for the -# virtual host being defined. -# - -# -# ServerAdmin: Your address, where problems with the server should be -# e-mailed. This address appears on some server-generated pages, such -# as error documents. e.g. admin@your-domain.com -# -ServerAdmin admin@able.cs.cmu.edu - -# -# ServerName gives the name and port that the server uses to identify itself. -# This can often be determined automatically, but we recommend you specify -# it explicitly to prevent problems during startup. -# -# If this is not set to valid DNS name for your host, server-generated -# redirections will not work. See also the UseCanonicalName directive. -# -# If your host doesn't have a registered DNS name, enter its IP address here. -# You will have to access it by its address anyway, and this will make -# redirections work in a sensible way. -# -ServerName fir.able.cs.cmu.edu:80 - -# -# UseCanonicalName: Determines how Apache constructs self-referencing -# URLs and the SERVER_NAME and SERVER_PORT variables. -# When set "Off", Apache will use the Hostname and Port supplied -# by the client. When set "On", Apache will use the value of the -# ServerName directive. -# -UseCanonicalName Off - -# -# DocumentRoot: The directory out of which you will serve your -# documents. By default, all requests are taken from this directory, but -# symbolic links and aliases may be used to point to other locations. -# -DocumentRoot "C:/server/Apache2/htdocs" - -# -# Each directory to which Apache has access can be configured with respect -# to which services and features are allowed and/or disabled in that -# directory (and its subdirectories). -# -# First, we configure the "default" to be a very restrictive set of -# features. -# - - Options FollowSymLinks - AllowOverride None - - -# -# Note that from this point forward you must specifically allow -# particular features to be enabled - so if something's not working as -# you might expect, make sure that you have specifically enabled it -# below. -# - -# -# This should be changed to whatever you set DocumentRoot to. -# - - -# -# Possible values for the Options directive are "None", "All", -# or any combination of: -# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews -# -# Note that "MultiViews" must be named *explicitly* --- "Options All" -# doesn't give it to you. -# -# The Options directive is both complicated and important. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#options -# for more information. -# - Options Indexes FollowSymLinks - -# -# AllowOverride controls what directives may be placed in .htaccess files. -# It can be "All", "None", or any combination of the keywords: -# Options FileInfo AuthConfig Limit -# - AllowOverride None - -# -# Controls who can get stuff from this server. -# - Order allow,deny - Allow from all - - - -# -# UserDir: The name of the directory that is appended onto a user's home -# directory if a ~user request is received. Be especially careful to use -# proper, forward slashes here. On Windows NT, "Personal/My Website" -# is a more appropriate choice. -# -UserDir "My Documents/My Website" - -# -# Control access to UserDir directories. The following is an example -# for a site where these directories are restricted to read-only. -# -# You must correct the path for the root to match your system's configured -# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" -# or whichever, as appropriate. -# -# -# AllowOverride FileInfo AuthConfig Limit -# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec -# -# Order allow,deny -# Allow from all -# -# -# Order deny,allow -# Deny from all -# -# - -# -# DirectoryIndex: sets the file that Apache will serve if a directory -# is requested. -# -# The index.html.var file (a type-map) is used to deliver content- -# negotiated documents. The MultiViews Option can be used for the -# same purpose, but it is much slower. -# -DirectoryIndex index.html index.html.var - -# -# AccessFileName: The name of the file to look for in each directory -# for additional configuration directives. See also the AllowOverride -# directive. -# -AccessFileName .htaccess - -# -# The following lines prevent .htaccess and .htpasswd files from being -# viewed by Web clients. -# - - Order allow,deny - Deny from all - - -# -# TypesConfig describes where the mime.types file (or equivalent) is -# to be found. -# -TypesConfig conf/mime.types - -# -# DefaultType is the default MIME type the server will use for a document -# if it cannot otherwise determine one, such as from filename extensions. -# If your server contains mostly text or HTML documents, "text/plain" is -# a good value. If most of your content is binary, such as applications -# or images, you may want to use "application/octet-stream" instead to -# keep browsers from trying to display binary files as though they are -# text. -# -DefaultType text/plain - -# -# The mod_mime_magic module allows the server to use various hints from the -# contents of the file itself to determine its type. The MIMEMagicFile -# directive tells the module where the hint definitions are located. -# - - MIMEMagicFile conf/magic - - -# -# HostnameLookups: Log the names of clients or just their IP addresses -# e.g., www.apache.org (on) or 204.62.129.132 (off). -# The default is off because it'd be overall better for the net if people -# had to knowingly turn this feature on, since enabling it means that -# each client request will result in AT LEAST one lookup request to the -# nameserver. -# -HostnameLookups Off - -# -# EnableMMAP: Control whether memory-mapping is used to deliver -# files (assuming that the underlying OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. On some systems, turning it off (regardless of -# filesystem) can improve performance; for details, please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap -# -#EnableMMAP off - -# -# EnableSendfile: Control whether the sendfile kernel support is -# used to deliver files (assuming that the OS supports it). -# The default is on; turn this off if you serve from NFS-mounted -# filesystems. Please see -# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile -# -#EnableSendfile off - -# -# ErrorLog: The location of the error log file. -# If you do not specify an ErrorLog directive within a -# container, error messages relating to that virtual host will be -# logged here. If you *do* define an error logfile for a -# container, that host's errors will be logged there and not here. -# -ErrorLog logs/error.log - -# -# LogLevel: Control the number of messages logged to the error.log. -# Possible values include: debug, info, notice, warn, error, crit, -# alert, emerg. -# -LogLevel warn - -# -# The following directives define some format nicknames for use with -# a CustomLog directive (see below). -# -LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined -LogFormat "%h %l %u %t \"%r\" %>s %b" common -LogFormat "%{Referer}i -> %U" referer -LogFormat "%{User-agent}i" agent - -# You need to enable mod_logio.c to use %I and %O -#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio - -# -# The location and format of the access logfile (Common Logfile Format). -# If you do not define any access logfiles within a -# container, they will be logged here. Contrariwise, if you *do* -# define per- access logfiles, transactions will be -# logged therein and *not* in this file. -# -CustomLog logs/access.log common - -# -# If you would like to have agent and referer logfiles, uncomment the -# following directives. -# -#CustomLog logs/referer.log referer -#CustomLog logs/agent.log agent - -# -# If you prefer a single logfile with access, agent, and referer information -# (Combined Logfile Format) you can use the following directive. -# -#CustomLog logs/access.log combined - -# -# ServerTokens -# This directive configures what you return as the Server HTTP response -# Header. The default is 'Full' which sends information about the OS-Type -# and compiled in modules. -# Set to one of: Full | OS | Minor | Minimal | Major | Prod -# where Full conveys the most information, and Prod the least. -# -ServerTokens Full - -# -# Optionally add a line containing the server version and virtual host -# name to server-generated pages (internal error documents, FTP directory -# listings, mod_status and mod_info output etc., but not CGI generated -# documents or custom error documents). -# Set to "EMail" to also include a mailto: link to the ServerAdmin. -# Set to one of: On | Off | EMail -# -ServerSignature On - -# -# Aliases: Add here as many aliases as you need (with no limit). The format is -# Alias fakename realname -# -# Note that if you include a trailing / on fakename then the server will -# require it to be present in the URL. So "/icons" isn't aliased in this -# example, only "/icons/". If the fakename is slash-terminated, then the -# realname must also be slash terminated, and if the fakename omits the -# trailing slash, the realname must also omit it. -# -# We include the /icons/ alias for FancyIndexed directory listings. If you -# do not use FancyIndexing, you may comment this out. -# -Alias /icons/ "C:/server/Apache2/icons/" - - - Options Indexes MultiViews - AllowOverride None - Order allow,deny - Allow from all - - -# -# This should be changed to the ServerRoot/manual/. The alias provides -# the manual, even if you choose to move your DocumentRoot. You may comment -# this out if you do not care for the documentation. -# -AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" - - - Options Indexes - AllowOverride None - Order allow,deny - Allow from all - - - SetHandler type-map - - - SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 - RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 - - -# -# ScriptAlias: This controls which directories contain server scripts. -# ScriptAliases are essentially the same as Aliases, except that -# documents in the realname directory are treated as applications and -# run by the server when requested rather than as documents sent to the client. -# The same rules about trailing "/" apply to ScriptAlias directives as to -# Alias. -# -ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" - -# -# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased -# CGI directory exists, if you have that configured. -# - - AllowOverride None - Options None - Order allow,deny - Allow from all - - -# -# Redirect allows you to tell clients about documents which used to exist in -# your server's namespace, but do not anymore. This allows you to tell the -# clients where to look for the relocated document. -# Example: -# Redirect permanent /foo http://www.example.com/bar - -# -# Directives controlling the display of server-generated directory listings. -# - -# -# IndexOptions: Controls the appearance of server-generated directory -# listings. -# -IndexOptions FancyIndexing VersionSort - -# -# AddIcon* directives tell the server which icon to show for different -# files or filename extensions. These are only displayed for -# FancyIndexed directories. -# -AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip - -AddIconByType (TXT,/icons/text.gif) text/* -AddIconByType (IMG,/icons/image2.gif) image/* -AddIconByType (SND,/icons/sound2.gif) audio/* -AddIconByType (VID,/icons/movie.gif) video/* - -AddIcon /icons/binary.gif .bin .exe -AddIcon /icons/binhex.gif .hqx -AddIcon /icons/tar.gif .tar -AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv -AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip -AddIcon /icons/a.gif .ps .ai .eps -AddIcon /icons/layout.gif .html .shtml .htm .pdf -AddIcon /icons/text.gif .txt -AddIcon /icons/c.gif .c -AddIcon /icons/p.gif .pl .py -AddIcon /icons/f.gif .for -AddIcon /icons/dvi.gif .dvi -AddIcon /icons/uuencoded.gif .uu -AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl -AddIcon /icons/tex.gif .tex -AddIcon /icons/bomb.gif core - -AddIcon /icons/back.gif .. -AddIcon /icons/hand.right.gif README -AddIcon /icons/folder.gif ^^DIRECTORY^^ -AddIcon /icons/blank.gif ^^BLANKICON^^ - -# -# DefaultIcon is which icon to show for files which do not have an icon -# explicitly set. -# -DefaultIcon /icons/unknown.gif - -# -# AddDescription allows you to place a short description after a file in -# server-generated indexes. These are only displayed for FancyIndexed -# directories. -# Format: AddDescription "description" filename -# -#AddDescription "GZIP compressed document" .gz -#AddDescription "tar archive" .tar -#AddDescription "GZIP compressed tar archive" .tgz - -# -# ReadmeName is the name of the README file the server will look for by -# default, and append to directory listings. -# -# HeaderName is the name of a file which should be prepended to -# directory indexes. -ReadmeName README.html -HeaderName HEADER.html - -# -# IndexIgnore is a set of filenames which directory indexing should ignore -# and not include in the listing. Shell-style wildcarding is permitted. -# -IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t - -# -# DefaultLanguage and AddLanguage allows you to specify the language of -# a document. You can then use content negotiation to give a browser a -# file in a language the user can understand. -# -# Specify a default language. This means that all data -# going out without a specific language tag (see below) will -# be marked with this one. You probably do NOT want to set -# this unless you are sure it is correct for all cases. -# -# * It is generally better to not mark a page as -# * being a certain language than marking it with the wrong -# * language! -# -# DefaultLanguage nl -# -# Note 1: The suffix does not have to be the same as the language -# keyword --- those with documents in Polish (whose net-standard -# language code is pl) may wish to use "AddLanguage pl .po" to -# avoid the ambiguity with the common suffix for perl scripts. -# -# Note 2: The example entries below illustrate that in some cases -# the two character 'Language' abbreviation is not identical to -# the two character 'Country' code for its country, -# E.g. 'Danmark/dk' versus 'Danish/da'. -# -# Note 3: In the case of 'ltz' we violate the RFC by using a three char -# specifier. There is 'work in progress' to fix this and get -# the reference data for rfc1766 cleaned up. -# -# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) -# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) -# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) -# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) -# Norwegian (no) - Polish (pl) - Portugese (pt) -# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) -# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) -# -AddLanguage ca .ca -AddLanguage cs .cz .cs -AddLanguage da .dk -AddLanguage de .de -AddLanguage el .el -AddLanguage en .en -AddLanguage eo .eo -AddLanguage es .es -AddLanguage et .et -AddLanguage fr .fr -AddLanguage he .he -AddLanguage hr .hr -AddLanguage it .it -AddLanguage ja .ja -AddLanguage ko .ko -AddLanguage ltz .ltz -AddLanguage nl .nl -AddLanguage nn .nn -AddLanguage no .no -AddLanguage pl .po -AddLanguage pt .pt -AddLanguage pt-BR .pt-br -AddLanguage ru .ru -AddLanguage sv .sv -AddLanguage zh-CN .zh-cn -AddLanguage zh-TW .zh-tw - -# -# LanguagePriority allows you to give precedence to some languages -# in case of a tie during content negotiation. -# -# Just list the languages in decreasing order of preference. We have -# more or less alphabetized them here. You probably want to change this. -# -LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW - -# -# ForceLanguagePriority allows you to serve a result page rather than -# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) -# [in case no accepted languages matched the available variants] -# -ForceLanguagePriority Prefer Fallback - -# -# Commonly used filename extensions to character sets. You probably -# want to avoid clashes with the language extensions, unless you -# are good at carefully testing your setup after each change. -# See http://www.iana.org/assignments/character-sets for the -# official list of charset names and their respective RFCs. -# -AddCharset ISO-8859-1 .iso8859-1 .latin1 -AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen -AddCharset ISO-8859-3 .iso8859-3 .latin3 -AddCharset ISO-8859-4 .iso8859-4 .latin4 -AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru -AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb -AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk -AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb -AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk -AddCharset ISO-2022-JP .iso2022-jp .jis -AddCharset ISO-2022-KR .iso2022-kr .kis -AddCharset ISO-2022-CN .iso2022-cn .cis -AddCharset Big5 .Big5 .big5 -# For russian, more than one charset is used (depends on client, mostly): -AddCharset WINDOWS-1251 .cp-1251 .win-1251 -AddCharset CP866 .cp866 -AddCharset KOI8-r .koi8-r .koi8-ru -AddCharset KOI8-ru .koi8-uk .ua -AddCharset ISO-10646-UCS-2 .ucs2 -AddCharset ISO-10646-UCS-4 .ucs4 -AddCharset UTF-8 .utf8 - -# The set below does not map to a specific (iso) standard -# but works on a fairly wide range of browsers. Note that -# capitalization actually matters (it should not, but it -# does for some browsers). -# -# See http://www.iana.org/assignments/character-sets -# for a list of sorts. But browsers support few. -# -AddCharset GB2312 .gb2312 .gb -AddCharset utf-7 .utf7 -AddCharset utf-8 .utf8 -AddCharset big5 .big5 .b5 -AddCharset EUC-TW .euc-tw -AddCharset EUC-JP .euc-jp -AddCharset EUC-KR .euc-kr -AddCharset shift_jis .sjis - -# -# AddType allows you to add to or override the MIME configuration -# file mime.types for specific file types. -# -#AddType application/x-tar .tgz -# -# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress -# information on the fly. Note: Not all browsers support this. -# Despite the name similarity, the following Add* directives have nothing -# to do with the FancyIndexing customization directives above. -# -#AddEncoding x-compress .Z -#AddEncoding x-gzip .gz .tgz -# -# If the AddEncoding directives above are commented-out, then you -# probably should define those extensions to indicate media types: -# -AddType application/x-compress .Z -AddType application/x-gzip .gz .tgz - -# -# AddHandler allows you to map certain file extensions to "handlers": -# actions unrelated to filetype. These can be either built into the server -# or added with the Action directive (see below) -# -# To use CGI scripts outside of ScriptAliased directories: -# (You will also need to add "ExecCGI" to the "Options" directive.) -# -#AddHandler cgi-script .cgi - -# -# For files that include their own HTTP headers: -# -#AddHandler send-as-is asis - -# -# For server-parsed imagemap files: -# -#AddHandler imap-file map - -# -# For type maps (negotiated resources): -# (This is enabled by default to allow the Apache "It Worked" page -# to be distributed in multiple languages.) -# -AddHandler type-map var - -# -# Filters allow you to process content before it is sent to the client. -# -# To parse .shtml files for server-side includes (SSI): -# (You will also need to add "Includes" to the "Options" directive.) -# -#AddType text/html .shtml -#AddOutputFilter INCLUDES .shtml - -# -# Action lets you define media types that will execute a script whenever -# a matching file is called. This eliminates the need for repeated URL -# pathnames for oft-used CGI file processors. -# Format: Action media/type /cgi-script/location -# Format: Action handler-name /cgi-script/location -# - -# -# Customizable error responses come in three flavors: -# 1) plain text 2) local redirects 3) external redirects -# -# Some examples: -#ErrorDocument 500 "The server made a boo boo." -#ErrorDocument 404 /missing.html -#ErrorDocument 404 "/cgi-bin/missing_handler.pl" -#ErrorDocument 402 http://www.example.com/subscription_info.html -# - -# -# Putting this all together, we can internationalize error responses. -# -# We use Alias to redirect any /error/HTTP_.html.var response to -# our collection of by-error message multi-language collections. We use -# includes to substitute the appropriate text. -# -# You can modify the messages' appearance without changing any of the -# default HTTP_.html.var files by adding the line: -# -# Alias /error/include/ "/your/include/path/" -# -# which allows you to create your own set of files by starting with the -# @exp_errordir@/include/ files and copying them to /your/include/path/, -# even on a per-VirtualHost basis. The default include files will display -# your Apache version number and your ServerAdmin email address regardless -# of the setting of ServerSignature. -# -# The internationalized error documents require mod_alias, mod_include -# and mod_negotiation. To activate them, uncomment the following 30 lines. - -# Alias /error/ "@exp_errordir@/" -# -# -# AllowOverride None -# Options IncludesNoExec -# AddOutputFilter Includes html -# AddHandler type-map var -# Order allow,deny -# Allow from all -# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr -# ForceLanguagePriority Prefer Fallback -# -# -# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var -# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var -# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var -# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var -# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var -# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var -# ErrorDocument 410 /error/HTTP_GONE.html.var -# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var -# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var -# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var -# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var -# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var -# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var -# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var -# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var -# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var -# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var - - - -# -# The following directives modify normal HTTP response behavior to -# handle known problems with browser implementations. -# -BrowserMatch "Mozilla/2" nokeepalive -BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 -BrowserMatch "RealPlayer 4\.0" force-response-1.0 -BrowserMatch "Java/1\.0" force-response-1.0 -BrowserMatch "JDK/1\.0" force-response-1.0 - -# -# The following directive disables redirects on non-GET requests for -# a directory that does not include the trailing slash. This fixes a -# problem with Microsoft WebFolders which does not appropriately handle -# redirects for folders with DAV methods. -# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. -# -BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully -BrowserMatch "^WebDrive" redirect-carefully -BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully -BrowserMatch "^gnome-vfs" redirect-carefully - -# -# Allow server status reports generated by mod_status, -# with the URL of http://servername/server-status -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-status -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - -# -# Allow remote server configuration reports, with the URL of -# http://servername/server-info (requires that mod_info.c be loaded). -# Change the ".able.cs.cmu.edu" to match your domain to enable. -# -# -# SetHandler server-info -# Order deny,allow -# Deny from all -# Allow from .able.cs.cmu.edu -# - - -# -# Bring in additional module-specific configurations -# - - Include conf/ssl.conf - - - -### Section 3: Virtual Hosts -# -# VirtualHost: If you want to maintain multiple domains/hostnames on your -# machine you can setup VirtualHost containers for them. Most configurations -# use only name-based virtual hosts so the server doesn't need to worry about -# IP addresses. This is indicated by the asterisks in the directives below. -# -# Please see the documentation at -# -# for further details before you try to setup virtual hosts. -# -# You may use the command line option '-S' to verify your virtual host -# configuration. - -# -# Use name-based virtual hosting. -# -#NameVirtualHost *:80 - -# -# VirtualHost example: -# Almost any Apache directive may go into a VirtualHost container. -# The first VirtualHost section is used for requests without a known -# server name. -# -# -# ServerAdmin webmaster@dummy-host.example.com -# DocumentRoot /www/docs/dummy-host.example.com -# ServerName dummy-host.example.com -# ErrorLog logs/dummy-host.example.com-error_log -# CustomLog logs/dummy-host.example.com-access_log common -# +# +# Based upon the NCSA server configuration files originally by Rob McCool. +# +# This is the main Apache server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information about +# the directives. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# The configuration directives are grouped into three basic sections: +# 1. Directives that control the operation of the Apache server process as a +# whole (the 'global environment'). +# 2. Directives that define the parameters of the 'main' or 'default' server, +# which responds to requests that aren't handled by a virtual host. +# These directives also provide default values for the settings +# of all virtual hosts. +# 3. Settings for virtual hosts, which allow Web requests to be sent to +# different IP addresses or hostnames and have them handled by the +# same Apache server process. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/foo.log" +# with ServerRoot set to "C:/server/Apache2" will be interpreted by the +# server as "C:/server/Apache2/logs/foo.log". +# +# NOTE: Where filenames are specified, you must use forward slashes +# instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). +# If a drive letter is omitted, the drive on which Apache.exe is located +# will be used by default. It is recommended that you always supply +# an explicit drive letter in absolute paths, however, to avoid +# confusion. +# + +### Section 1: Global Environment +# +# The directives in this section affect the overall operation of Apache, +# such as the number of concurrent requests it can handle or where it +# can find its configuration files. +# + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# NOTE! If you intend to place this on an NFS (or otherwise network) +# mounted filesystem then please read the LockFile documentation (available +# at ); +# you will save yourself a lot of trouble. +# +# Do NOT add a slash at the end of the directory path. +# +ServerRoot "C:/server/Apache2" + +# +# ScoreBoardFile: File used to store internal server process information. +# If unspecified (the default), the scoreboard will be stored in an +# anonymous shared memory segment, and will be unavailable to third-party +# applications. +# If specified, ensure that no two invocations of Apache share the same +# scoreboard file. The scoreboard file MUST BE STORED ON A LOCAL DISK. +# +#ScoreBoardFile logs/apache_runtime_status + +# +# PidFile: The file in which the server should record its process +# identification number when it starts. +# +PidFile logs/httpd.pid + +# +# Timeout: The number of seconds before receives and sends time out. +# +Timeout 300 + +# +# KeepAlive: Whether or not to allow persistent connections (more than +# one request per connection). Set to "Off" to deactivate. +# +KeepAlive On + +# +# MaxKeepAliveRequests: The maximum number of requests to allow +# during a persistent connection. Set to 0 to allow an unlimited amount. +# We recommend you leave this number high, for maximum performance. +# +MaxKeepAliveRequests 100 + +# +# KeepAliveTimeout: Number of seconds to wait for the next request from the +# same client on the same connection. +# +KeepAliveTimeout 15 + +## +## Server-Pool Size Regulation (MPM specific) +## + +# WinNT MPM +# ThreadsPerChild: constant number of worker threads in the server process +# MaxRequestsPerChild: maximum number of requests a server process serves + +ThreadsPerChild 250 +MaxRequestsPerChild 0 + + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses (0.0.0.0) +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule access_module modules/mod_access.so +LoadModule actions_module modules/mod_actions.so +LoadModule alias_module modules/mod_alias.so +LoadModule asis_module modules/mod_asis.so +LoadModule auth_module modules/mod_auth.so +#LoadModule auth_anon_module modules/mod_auth_anon.so +#LoadModule auth_dbm_module modules/mod_auth_dbm.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +LoadModule cgi_module modules/mod_cgi.so +#LoadModule dav_module modules/mod_dav.so +#LoadModule dav_fs_module modules/mod_dav_fs.so +LoadModule dir_module modules/mod_dir.so +LoadModule env_module modules/mod_env.so +#LoadModule expires_module modules/mod_expires.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule headers_module modules/mod_headers.so +LoadModule imap_module modules/mod_imap.so +LoadModule include_module modules/mod_include.so +#LoadModule info_module modules/mod_info.so +LoadModule isapi_module modules/mod_isapi.so +LoadModule log_config_module modules/mod_log_config.so +LoadModule mime_module modules/mod_mime.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +LoadModule negotiation_module modules/mod_negotiation.so +#LoadModule rewrite_module modules/mod_rewrite.so +LoadModule setenvif_module modules/mod_setenvif.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule status_module modules/mod_status.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule userdir_module modules/mod_userdir.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule ssl_module modules/mod_ssl.so + +# +# ExtendedStatus controls whether Apache will generate "full" status +# information (ExtendedStatus On) or just basic information (ExtendedStatus +# Off) when the "server-status" handler is called. The default is Off. +# +#ExtendedStatus On + +### Section 2: 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin admin@able.cs.cmu.edu + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If this is not set to valid DNS name for your host, server-generated +# redirections will not work. See also the UseCanonicalName directive. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# You will have to access it by its address anyway, and this will make +# redirections work in a sensible way. +# +ServerName fir.able.cs.cmu.edu:80 + +# +# UseCanonicalName: Determines how Apache constructs self-referencing +# URLs and the SERVER_NAME and SERVER_PORT variables. +# When set "Off", Apache will use the Hostname and Port supplied +# by the client. When set "On", Apache will use the value of the +# ServerName directive. +# +UseCanonicalName Off + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "C:/server/Apache2/htdocs" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# + + Options FollowSymLinks + AllowOverride None + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# + + +# +# Possible values for the Options directive are "None", "All", +# or any combination of: +# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# +# Note that "MultiViews" must be named *explicitly* --- "Options All" +# doesn't give it to you. +# +# The Options directive is both complicated and important. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#options +# for more information. +# + Options Indexes FollowSymLinks + +# +# AllowOverride controls what directives may be placed in .htaccess files. +# It can be "All", "None", or any combination of the keywords: +# Options FileInfo AuthConfig Limit +# + AllowOverride None + +# +# Controls who can get stuff from this server. +# + Order allow,deny + Allow from all + + + +# +# UserDir: The name of the directory that is appended onto a user's home +# directory if a ~user request is received. Be especially careful to use +# proper, forward slashes here. On Windows NT, "Personal/My Website" +# is a more appropriate choice. +# +UserDir "My Documents/My Website" + +# +# Control access to UserDir directories. The following is an example +# for a site where these directories are restricted to read-only. +# +# You must correct the path for the root to match your system's configured +# user directory location, e.g. "C:/WinNT/profiles/*/My Documents/My Website" +# or whichever, as appropriate. +# +# +# AllowOverride FileInfo AuthConfig Limit +# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec +# +# Order allow,deny +# Allow from all +# +# +# Order deny,allow +# Deny from all +# +# + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +# The index.html.var file (a type-map) is used to deliver content- +# negotiated documents. The MultiViews Option can be used for the +# same purpose, but it is much slower. +# +DirectoryIndex index.html index.html.var + +# +# AccessFileName: The name of the file to look for in each directory +# for additional configuration directives. See also the AllowOverride +# directive. +# +AccessFileName .htaccess + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Order allow,deny + Deny from all + + +# +# TypesConfig describes where the mime.types file (or equivalent) is +# to be found. +# +TypesConfig conf/mime.types + +# +# DefaultType is the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plain + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# + + MIMEMagicFile conf/magic + + +# +# HostnameLookups: Log the names of clients or just their IP addresses +# e.g., www.apache.org (on) or 204.62.129.132 (off). +# The default is off because it'd be overall better for the net if people +# had to knowingly turn this feature on, since enabling it means that +# each client request will result in AT LEAST one lookup request to the +# nameserver. +# +HostnameLookups Off + +# +# EnableMMAP: Control whether memory-mapping is used to deliver +# files (assuming that the underlying OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. On some systems, turning it off (regardless of +# filesystem) can improve performance; for details, please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablemmap +# +#EnableMMAP off + +# +# EnableSendfile: Control whether the sendfile kernel support is +# used to deliver files (assuming that the OS supports it). +# The default is on; turn this off if you serve from NFS-mounted +# filesystems. Please see +# http://httpd.apache.org/docs-2.0/mod/core.html#enablesendfile +# +#EnableSendfile off + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog logs/error.log + +# +# LogLevel: Control the number of messages logged to the error.log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +# +# The following directives define some format nicknames for use with +# a CustomLog directive (see below). +# +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined +LogFormat "%h %l %u %t \"%r\" %>s %b" common +LogFormat "%{Referer}i -> %U" referer +LogFormat "%{User-agent}i" agent + +# You need to enable mod_logio.c to use %I and %O +#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + +# +# The location and format of the access logfile (Common Logfile Format). +# If you do not define any access logfiles within a +# container, they will be logged here. Contrariwise, if you *do* +# define per- access logfiles, transactions will be +# logged therein and *not* in this file. +# +CustomLog logs/access.log common + +# +# If you would like to have agent and referer logfiles, uncomment the +# following directives. +# +#CustomLog logs/referer.log referer +#CustomLog logs/agent.log agent + +# +# If you prefer a single logfile with access, agent, and referer information +# (Combined Logfile Format) you can use the following directive. +# +#CustomLog logs/access.log combined + +# +# ServerTokens +# This directive configures what you return as the Server HTTP response +# Header. The default is 'Full' which sends information about the OS-Type +# and compiled in modules. +# Set to one of: Full | OS | Minor | Minimal | Major | Prod +# where Full conveys the most information, and Prod the least. +# +ServerTokens Full + +# +# Optionally add a line containing the server version and virtual host +# name to server-generated pages (internal error documents, FTP directory +# listings, mod_status and mod_info output etc., but not CGI generated +# documents or custom error documents). +# Set to "EMail" to also include a mailto: link to the ServerAdmin. +# Set to one of: On | Off | EMail +# +ServerSignature On + +# +# Aliases: Add here as many aliases as you need (with no limit). The format is +# Alias fakename realname +# +# Note that if you include a trailing / on fakename then the server will +# require it to be present in the URL. So "/icons" isn't aliased in this +# example, only "/icons/". If the fakename is slash-terminated, then the +# realname must also be slash terminated, and if the fakename omits the +# trailing slash, the realname must also omit it. +# +# We include the /icons/ alias for FancyIndexed directory listings. If you +# do not use FancyIndexing, you may comment this out. +# +Alias /icons/ "C:/server/Apache2/icons/" + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + +# +# This should be changed to the ServerRoot/manual/. The alias provides +# the manual, even if you choose to move your DocumentRoot. You may comment +# this out if you do not care for the documentation. +# +AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|ru))?(/.*)?$ "C:/server/Apache2/manual$1" + + + Options Indexes + AllowOverride None + Order allow,deny + Allow from all + + + SetHandler type-map + + + SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|ru)/ prefer-language=$1 + RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|ru)){2,}(/.*)?$ /manual/$1$2 + + +# +# ScriptAlias: This controls which directories contain server scripts. +# ScriptAliases are essentially the same as Aliases, except that +# documents in the realname directory are treated as applications and +# run by the server when requested rather than as documents sent to the client. +# The same rules about trailing "/" apply to ScriptAlias directives as to +# Alias. +# +ScriptAlias /cgi-bin/ "C:/server/Apache2/cgi-bin/" + +# +# "C:/server/Apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Order allow,deny + Allow from all + + +# +# Redirect allows you to tell clients about documents which used to exist in +# your server's namespace, but do not anymore. This allows you to tell the +# clients where to look for the relocated document. +# Example: +# Redirect permanent /foo http://www.example.com/bar + +# +# Directives controlling the display of server-generated directory listings. +# + +# +# IndexOptions: Controls the appearance of server-generated directory +# listings. +# +IndexOptions FancyIndexing VersionSort + +# +# AddIcon* directives tell the server which icon to show for different +# files or filename extensions. These are only displayed for +# FancyIndexed directories. +# +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +# +# DefaultIcon is which icon to show for files which do not have an icon +# explicitly set. +# +DefaultIcon /icons/unknown.gif + +# +# AddDescription allows you to place a short description after a file in +# server-generated indexes. These are only displayed for FancyIndexed +# directories. +# Format: AddDescription "description" filename +# +#AddDescription "GZIP compressed document" .gz +#AddDescription "tar archive" .tar +#AddDescription "GZIP compressed tar archive" .tgz + +# +# ReadmeName is the name of the README file the server will look for by +# default, and append to directory listings. +# +# HeaderName is the name of a file which should be prepended to +# directory indexes. +ReadmeName README.html +HeaderName HEADER.html + +# +# IndexIgnore is a set of filenames which directory indexing should ignore +# and not include in the listing. Shell-style wildcarding is permitted. +# +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +# +# DefaultLanguage and AddLanguage allows you to specify the language of +# a document. You can then use content negotiation to give a browser a +# file in a language the user can understand. +# +# Specify a default language. This means that all data +# going out without a specific language tag (see below) will +# be marked with this one. You probably do NOT want to set +# this unless you are sure it is correct for all cases. +# +# * It is generally better to not mark a page as +# * being a certain language than marking it with the wrong +# * language! +# +# DefaultLanguage nl +# +# Note 1: The suffix does not have to be the same as the language +# keyword --- those with documents in Polish (whose net-standard +# language code is pl) may wish to use "AddLanguage pl .po" to +# avoid the ambiguity with the common suffix for perl scripts. +# +# Note 2: The example entries below illustrate that in some cases +# the two character 'Language' abbreviation is not identical to +# the two character 'Country' code for its country, +# E.g. 'Danmark/dk' versus 'Danish/da'. +# +# Note 3: In the case of 'ltz' we violate the RFC by using a three char +# specifier. There is 'work in progress' to fix this and get +# the reference data for rfc1766 cleaned up. +# +# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) +# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) +# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) +# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) +# Norwegian (no) - Polish (pl) - Portugese (pt) +# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) +# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) +# +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +# +# LanguagePriority allows you to give precedence to some languages +# in case of a tie during content negotiation. +# +# Just list the languages in decreasing order of preference. We have +# more or less alphabetized them here. You probably want to change this. +# +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +# +# ForceLanguagePriority allows you to serve a result page rather than +# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) +# [in case no accepted languages matched the available variants] +# +ForceLanguagePriority Prefer Fallback + +# +# Commonly used filename extensions to character sets. You probably +# want to avoid clashes with the language extensions, unless you +# are good at carefully testing your setup after each change. +# See http://www.iana.org/assignments/character-sets for the +# official list of charset names and their respective RFCs. +# +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +# For russian, more than one charset is used (depends on client, mostly): +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +# The set below does not map to a specific (iso) standard +# but works on a fairly wide range of browsers. Note that +# capitalization actually matters (it should not, but it +# does for some browsers). +# +# See http://www.iana.org/assignments/character-sets +# for a list of sorts. But browsers support few. +# +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +# +# AddType allows you to add to or override the MIME configuration +# file mime.types for specific file types. +# +#AddType application/x-tar .tgz +# +# AddEncoding allows you to have certain browsers (Mosaic/X 2.1+) uncompress +# information on the fly. Note: Not all browsers support this. +# Despite the name similarity, the following Add* directives have nothing +# to do with the FancyIndexing customization directives above. +# +#AddEncoding x-compress .Z +#AddEncoding x-gzip .gz .tgz +# +# If the AddEncoding directives above are commented-out, then you +# probably should define those extensions to indicate media types: +# +AddType application/x-compress .Z +AddType application/x-gzip .gz .tgz + +# +# AddHandler allows you to map certain file extensions to "handlers": +# actions unrelated to filetype. These can be either built into the server +# or added with the Action directive (see below) +# +# To use CGI scripts outside of ScriptAliased directories: +# (You will also need to add "ExecCGI" to the "Options" directive.) +# +#AddHandler cgi-script .cgi + +# +# For files that include their own HTTP headers: +# +#AddHandler send-as-is asis + +# +# For server-parsed imagemap files: +# +#AddHandler imap-file map + +# +# For type maps (negotiated resources): +# (This is enabled by default to allow the Apache "It Worked" page +# to be distributed in multiple languages.) +# +AddHandler type-map var + +# +# Filters allow you to process content before it is sent to the client. +# +# To parse .shtml files for server-side includes (SSI): +# (You will also need to add "Includes" to the "Options" directive.) +# +#AddType text/html .shtml +#AddOutputFilter INCLUDES .shtml + +# +# Action lets you define media types that will execute a script whenever +# a matching file is called. This eliminates the need for repeated URL +# pathnames for oft-used CGI file processors. +# Format: Action media/type /cgi-script/location +# Format: Action handler-name /cgi-script/location +# + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# Putting this all together, we can internationalize error responses. +# +# We use Alias to redirect any /error/HTTP_.html.var response to +# our collection of by-error message multi-language collections. We use +# includes to substitute the appropriate text. +# +# You can modify the messages' appearance without changing any of the +# default HTTP_.html.var files by adding the line: +# +# Alias /error/include/ "/your/include/path/" +# +# which allows you to create your own set of files by starting with the +# @exp_errordir@/include/ files and copying them to /your/include/path/, +# even on a per-VirtualHost basis. The default include files will display +# your Apache version number and your ServerAdmin email address regardless +# of the setting of ServerSignature. +# +# The internationalized error documents require mod_alias, mod_include +# and mod_negotiation. To activate them, uncomment the following 30 lines. + +# Alias /error/ "@exp_errordir@/" +# +# +# AllowOverride None +# Options IncludesNoExec +# AddOutputFilter Includes html +# AddHandler type-map var +# Order allow,deny +# Allow from all +# LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr +# ForceLanguagePriority Prefer Fallback +# +# +# ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var +# ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var +# ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var +# ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var +# ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var +# ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var +# ErrorDocument 410 /error/HTTP_GONE.html.var +# ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var +# ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var +# ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var +# ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var +# ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var +# ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var +# ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var +# ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var +# ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var +# ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var + + + +# +# The following directives modify normal HTTP response behavior to +# handle known problems with browser implementations. +# +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +# +# The following directive disables redirects on non-GET requests for +# a directory that does not include the trailing slash. This fixes a +# problem with Microsoft WebFolders which does not appropriately handle +# redirects for folders with DAV methods. +# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. +# +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully +BrowserMatch "^gnome-vfs" redirect-carefully + +# +# Allow server status reports generated by mod_status, +# with the URL of http://servername/server-status +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-status +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + +# +# Allow remote server configuration reports, with the URL of +# http://servername/server-info (requires that mod_info.c be loaded). +# Change the ".able.cs.cmu.edu" to match your domain to enable. +# +# +# SetHandler server-info +# Order deny,allow +# Deny from all +# Allow from .able.cs.cmu.edu +# + + +# +# Bring in additional module-specific configurations +# + + Include conf/ssl.conf + + + +### Section 3: Virtual Hosts +# +# VirtualHost: If you want to maintain multiple domains/hostnames on your +# machine you can setup VirtualHost containers for them. Most configurations +# use only name-based virtual hosts so the server doesn't need to worry about +# IP addresses. This is indicated by the asterisks in the directives below. +# +# Please see the documentation at +# +# for further details before you try to setup virtual hosts. +# +# You may use the command line option '-S' to verify your virtual host +# configuration. + +# +# Use name-based virtual hosting. +# +#NameVirtualHost *:80 + +# +# VirtualHost example: +# Almost any Apache directive may go into a VirtualHost container. +# The first VirtualHost section is used for requests without a known +# server name. +# +# +# ServerAdmin webmaster@dummy-host.example.com +# DocumentRoot /www/docs/dummy-host.example.com +# ServerName dummy-host.example.com +# ErrorLog logs/dummy-host.example.com-error_log +# CustomLog logs/dummy-host.example.com-access_log common +# diff --git a/targets/znews1-d/system/effectors/setRandomReject.pl b/targets/znews1-d/system/effectors/setRandomReject.pl index 5d6b91697..58f70c7b0 100644 --- a/targets/znews1-d/system/effectors/setRandomReject.pl +++ b/targets/znews1-d/system/effectors/setRandomReject.pl @@ -1,35 +1,35 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; - -my $APACHE_WWW_DIR = "/home/owen/project/rainbow/delegate/targets/znews1-d/system/webpages/www5"; - -sub usage() { - print STDERR << "EOF"; - -This effector program affects random reject frequency (0 or mod over seconds). - - usage: $0 [option] -r [0|modval] - - -h : this (help) message - -r 0|mod : the modulus value for request rejection (0 for NO reject) - -EOF - exit; -} - -# get options -my %opts; -getopts('hr:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{r})); - -my $modVal = $opts{r}; -usage() if ($modVal < 0 && $modVal > 10); - -my $file = "reject.mod"; -print "Setting reject modulus value to $modVal..."; -open(FOUT, ">$APACHE_WWW_DIR/$file"); -print FOUT $modVal; -close(FOUT); -print "\nDone."; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; + +my $APACHE_WWW_DIR = "/home/owen/project/rainbow/delegate/targets/znews1-d/system/webpages/www5"; + +sub usage() { + print STDERR << "EOF"; + +This effector program affects random reject frequency (0 or mod over seconds). + + usage: $0 [option] -r [0|modval] + + -h : this (help) message + -r 0|mod : the modulus value for request rejection (0 for NO reject) + +EOF + exit; +} + +# get options +my %opts; +getopts('hr:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{r})); + +my $modVal = $opts{r}; +usage() if ($modVal < 0 && $modVal > 10); + +my $file = "reject.mod"; +print "Setting reject modulus value to $modVal..."; +open(FOUT, ">$APACHE_WWW_DIR/$file"); +print FOUT $modVal; +close(FOUT); +print "\nDone."; diff --git a/targets/znews1-d/system/effectors/turnServer.pl b/targets/znews1-d/system/effectors/turnServer.pl index 8cc10dd33..9d46f681e 100644 --- a/targets/znews1-d/system/effectors/turnServer.pl +++ b/targets/znews1-d/system/effectors/turnServer.pl @@ -1,36 +1,36 @@ -#!/usr/bin/perl -w - -use strict; -use Getopt::Std; -use IO::Handle; - -sub usage() { - print STDERR << "EOF"; - -This effector program turns the webserver on or off - - usage: $0 [option] -s on|off - - -h : this (help) message - -s on|off : on or off to start/stop webserver - -EOF - exit; -} - -# get options -my %opts; -getopts('hs:', \%opts) or usage(); -usage() if ($opts{h} || !defined($opts{s})); - -my $switch = $opts{s}; -usage() if ($switch ne "on" && $switch ne "off"); - -if ($switch eq "on") { - print "\nStarting Apache..."; - print `/etc/init.d/apache2 start`; -} else { - print "\nStopping Apache..."; - print `/etc/init.d/apache2 stop`; -} -print "\nDone."; +#!/usr/bin/perl -w + +use strict; +use Getopt::Std; +use IO::Handle; + +sub usage() { + print STDERR << "EOF"; + +This effector program turns the webserver on or off + + usage: $0 [option] -s on|off + + -h : this (help) message + -s on|off : on or off to start/stop webserver + +EOF + exit; +} + +# get options +my %opts; +getopts('hs:', \%opts) or usage(); +usage() if ($opts{h} || !defined($opts{s})); + +my $switch = $opts{s}; +usage() if ($switch ne "on" && $switch ne "off"); + +if ($switch eq "on") { + print "\nStarting Apache..."; + print `/etc/init.d/apache2 start`; +} else { + print "\nStopping Apache..."; + print `/etc/init.d/apache2 stop`; +} +print "\nDone."; diff --git a/targets/znews1-d/system/probes.yml b/targets/znews1-d/system/probes.yml index 097ca065e..405388994 100644 --- a/targets/znews1-d/system/probes.yml +++ b/targets/znews1-d/system/probes.yml @@ -1,99 +1,99 @@ -# -# Probe descriptions. -# -# History: -# - [SWC 2007.03.18] Created file, populated new probe descriptions. -# - [SWC 2007.04.09] Added array of host names as arguments to PingRTTProbe. -# - [SWC 2007.04.10] Modified descriptions for different target locations. -# - [SWC 2007.04.11] Added ClientProxyProbe -# -vars: - _probes.commonPath: "${rainbow.path}/system/probes" - -probes: - ClientProxyProbe0: - alias: clientproxy - location: "${customize.system.target.0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znews.probes.ClientProxyProbe - period: 2000 - args.length: 1 - args.0: "http://delegate.oracle/" - PingRTTProbe1: - alias: pingrtt - location: "${customize.system.target.1}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znews.probes.PingRTTProbe -# sample period in milliseconds - period: 1500 - args.length: 1 - args.0: "${rainbow.master.location.host}" -# args.1: "${customize.system.target.2}" - LoadProbe1: - alias: load - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" - FidelityProbe1: - alias: fidelity - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_probes.commonPath}/fidelityProbe.pl" - argument: "-k -s" - ApacheTopProbe1: - alias: apachetop - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_probes.commonPath}/apachetopProbe.pl" - argument: "-k -s" - DiskIOProbe1: - alias: diskio - location: "${customize.system.target.1}" - type: script - scriptInfo: - path : "${_probes.commonPath}/diskIOProbe.pl" - argument: "-k -s" - -unused-probes: - NullProbe0: - alias: NIL - location: "${customize.system.target.0}" - type: java - javaInfo: - class: org.sa.rainbow.translator.probes.NullProbe - ApacheTopProbe0: - alias: apachetop - location: "${customize.system.target.0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/apachetopProbe.pl" - argument: "-k -s" - LoadProbe0: - alias: load - location: "${customize.system.target.0}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" - PingRTTProbe3: - alias: pingrtt - location: "${customize.system.target.3}" - type: java - javaInfo: - class: org.sa.rainbow.translator.znews.probes.PingRTTProbe - period: 1500 - args.length: 1 - args.0: "${rainbow.master.location.host}" - LoadProbe3: - alias: load - location: "${customize.system.target.3}" - type: script - scriptInfo: - path : "${_probes.commonPath}/loadProbe.pl" - argument: "-k -s" +# +# Probe descriptions. +# +# History: +# - [SWC 2007.03.18] Created file, populated new probe descriptions. +# - [SWC 2007.04.09] Added array of host names as arguments to PingRTTProbe. +# - [SWC 2007.04.10] Modified descriptions for different target locations. +# - [SWC 2007.04.11] Added ClientProxyProbe +# +vars: + _probes.commonPath: "${rainbow.path}/system/probes" + +probes: + ClientProxyProbe0: + alias: clientproxy + location: "${customize.system.target.0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znews.probes.ClientProxyProbe + period: 2000 + args.length: 1 + args.0: "http://delegate.oracle/" + PingRTTProbe1: + alias: pingrtt + location: "${customize.system.target.1}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znews.probes.PingRTTProbe +# sample period in milliseconds + period: 1500 + args.length: 1 + args.0: "${rainbow.master.location.host}" +# args.1: "${customize.system.target.2}" + LoadProbe1: + alias: load + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" + FidelityProbe1: + alias: fidelity + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_probes.commonPath}/fidelityProbe.pl" + argument: "-k -s" + ApacheTopProbe1: + alias: apachetop + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_probes.commonPath}/apachetopProbe.pl" + argument: "-k -s" + DiskIOProbe1: + alias: diskio + location: "${customize.system.target.1}" + type: script + scriptInfo: + path : "${_probes.commonPath}/diskIOProbe.pl" + argument: "-k -s" + +unused-probes: + NullProbe0: + alias: NIL + location: "${customize.system.target.0}" + type: java + javaInfo: + class: org.sa.rainbow.translator.probes.NullProbe + ApacheTopProbe0: + alias: apachetop + location: "${customize.system.target.0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/apachetopProbe.pl" + argument: "-k -s" + LoadProbe0: + alias: load + location: "${customize.system.target.0}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" + PingRTTProbe3: + alias: pingrtt + location: "${customize.system.target.3}" + type: java + javaInfo: + class: org.sa.rainbow.translator.znews.probes.PingRTTProbe + period: 1500 + args.length: 1 + args.0: "${rainbow.master.location.host}" + LoadProbe3: + alias: load + location: "${customize.system.target.3}" + type: script + scriptInfo: + path : "${_probes.commonPath}/loadProbe.pl" + argument: "-k -s" diff --git a/targets/znews1-d/system/probes/apachetopProbe.pl b/targets/znews1-d/system/probes/apachetopProbe.pl index 79ba71042..9f8989f04 100644 --- a/targets/znews1-d/system/probes/apachetopProbe.pl +++ b/targets/znews1-d/system/probes/apachetopProbe.pl @@ -1,90 +1,90 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 5000; # 5 sec delay -my $APACHETOP_LOG = "../../log/apachetop.log"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -if (! -e $APACHETOP_LOG) { # create empty file - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line,$sendBeacon); -while (!shouldTerminate($sock)) { - $sendBeacon = 1; - while ($line = ) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - $sendBeacon = 0; - } - if ($sendBeacon) { # announce something to be alive - announce($ALIAS, "\n", [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 5000; # 5 sec delay +my $APACHETOP_LOG = "../../log/apachetop.log"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +if (! -e $APACHETOP_LOG) { # create empty file + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line,$sendBeacon); +while (!shouldTerminate($sock)) { + $sendBeacon = 1; + while ($line = ) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + $sendBeacon = 0; + } + if ($sendBeacon) { # announce something to be alive + announce($ALIAS, "\n", [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews1-d/system/probes/cygwin/apachetopProbe-single.pl b/targets/znews1-d/system/probes/cygwin/apachetopProbe-single.pl index 966358241..762a0686a 100644 --- a/targets/znews1-d/system/probes/cygwin/apachetopProbe-single.pl +++ b/targets/znews1-d/system/probes/cygwin/apachetopProbe-single.pl @@ -1,98 +1,98 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 10; -my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; -my $APACHETOP_LOG = "apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# fork to the apachetop program -my $pid = fork(); -if ($pid == 0) { ### child process - if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); - } - exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; - exit(0); -} - -### parent process - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line); -while (!shouldTerminate($sock)) { - $line = ; - if (defined($line)) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 10; +my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; +my $APACHETOP_LOG = "apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# fork to the apachetop program +my $pid = fork(); +if ($pid == 0) { ### child process + if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); + } + exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; + exit(0); +} + +### parent process + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line); +while (!shouldTerminate($sock)) { + $line = ; + if (defined($line)) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews1-d/system/probes/cygwin/apachetopProbe.pl b/targets/znews1-d/system/probes/cygwin/apachetopProbe.pl index 79ba71042..9f8989f04 100644 --- a/targets/znews1-d/system/probes/cygwin/apachetopProbe.pl +++ b/targets/znews1-d/system/probes/cygwin/apachetopProbe.pl @@ -1,90 +1,90 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "apachetop"; -my $NAME = "ApacheTopProbe"; -my $DELAY = 5000; # 5 sec delay -my $APACHETOP_LOG = "../../log/apachetop.log"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps apachetop output to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output apachetop info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -# obtain apachetop's log file -if (! -e $APACHETOP_LOG) { # create empty file - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -open(FIN, "<$APACHETOP_LOG"); -seek(FIN, 0, 2); -my $curpos = tell(FIN); -print "Seek to end of file $curpos\n" if ($doPrint); -seek(FIN, $curpos, 0); -my($line,$sendBeacon); -while (!shouldTerminate($sock)) { - $sendBeacon = 1; - while ($line = ) { - $curpos = tell(FIN); -# print "Updated position $curpos\n" if ($doPrint); - announce($ALIAS, $line, [$sock,$fout]); - $sendBeacon = 0; - } - if ($sendBeacon) { # announce something to be alive - announce($ALIAS, "\n", [$sock,$fout]); - } - seek(FIN, $curpos, 0); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "apachetop"; +my $NAME = "ApacheTopProbe"; +my $DELAY = 5000; # 5 sec delay +my $APACHETOP_LOG = "../../log/apachetop.log"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps apachetop output to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output apachetop info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +# obtain apachetop's log file +if (! -e $APACHETOP_LOG) { # create empty file + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +open(FIN, "<$APACHETOP_LOG"); +seek(FIN, 0, 2); +my $curpos = tell(FIN); +print "Seek to end of file $curpos\n" if ($doPrint); +seek(FIN, $curpos, 0); +my($line,$sendBeacon); +while (!shouldTerminate($sock)) { + $sendBeacon = 1; + while ($line = ) { + $curpos = tell(FIN); +# print "Updated position $curpos\n" if ($doPrint); + announce($ALIAS, $line, [$sock,$fout]); + $sendBeacon = 0; + } + if ($sendBeacon) { # announce something to be alive + announce($ALIAS, "\n", [$sock,$fout]); + } + seek(FIN, $curpos, 0); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews1-d/system/probes/cygwin/fidelityProbe.pl b/targets/znews1-d/system/probes/cygwin/fidelityProbe.pl index 21dc6255d..abb411a4d 100644 --- a/targets/znews1-d/system/probes/cygwin/fidelityProbe.pl +++ b/targets/znews1-d/system/probes/cygwin/fidelityProbe.pl @@ -1,100 +1,100 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "fidelity"; -my $NAME = "FidelityProbe"; -my $DELAY = 1000; -my $REPEATEVERY = 5; -my $APACHE_CONF_DIR = "/cygdrive/c/server/Apache2/conf"; -my $APACHE_CONF_FILE = "httpd.conf"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current server fidelity (1,3,5) to Probe Relay file/socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic server fidelity info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub determineFidelity () { - my $fid = 0; - - open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); - my $firstLine = ; # read the first line - if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { - $fid = $1; - } - close(FIN); - - return $fid; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -my $repeatCnt = $REPEATEVERY; -my $savedFidelity = 0; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # compute new fidelity status - my $fidelity = determineFidelity(); - if ($fidelity != $savedFidelity || $repeatCnt == 0) { - $savedFidelity = $fidelity; #store new fidelity - my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - - if ($repeatCnt == 0) { - $repeatCnt = $REPEATEVERY; - } - } else { - $repeatCnt--; - } -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "fidelity"; +my $NAME = "FidelityProbe"; +my $DELAY = 1000; +my $REPEATEVERY = 5; +my $APACHE_CONF_DIR = "/cygdrive/c/server/Apache2/conf"; +my $APACHE_CONF_FILE = "httpd.conf"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current server fidelity (1,3,5) to Probe Relay file/socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic server fidelity info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub determineFidelity () { + my $fid = 0; + + open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); + my $firstLine = ; # read the first line + if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { + $fid = $1; + } + close(FIN); + + return $fid; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +my $repeatCnt = $REPEATEVERY; +my $savedFidelity = 0; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # compute new fidelity status + my $fidelity = determineFidelity(); + if ($fidelity != $savedFidelity || $repeatCnt == 0) { + $savedFidelity = $fidelity; #store new fidelity + my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + + if ($repeatCnt == 0) { + $repeatCnt = $REPEATEVERY; + } + } else { + $repeatCnt--; + } +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews1-d/system/probes/cygwin/loadProbe.pl b/targets/znews1-d/system/probes/cygwin/loadProbe.pl index b50e32b17..0ff60debb 100644 --- a/targets/znews1-d/system/probes/cygwin/loadProbe.pl +++ b/targets/znews1-d/system/probes/cygwin/loadProbe.pl @@ -1,98 +1,98 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "load"; -my $NAME = "LoadProbe"; -my $DELAY = 1000; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current CPU usage to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic CPU usage info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub cpuTime () { - my ($user, $nice, $sys, $idle); - - local(*FIN); - open(FIN, ") { - chomp; - if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/o) { - ($user, $nice, $sys, $idle) = ($1, $2, $3, $4); - last; - } - } - close(FIN); - return ($user, $nice, $sys, $idle); -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# save current cpu ticks -my($userSv, $niceSv, $sysSv, $idleSv) = cpuTime(); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # retrieve new cpu ticks - my ($userN, $niceN, $sysN, $idleN) = cpuTime(); - # compute delta cpu ticks - my ($user, $nice, $sys, $idle) = - ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv); - # store the new saved ticks - ($userSv, $niceSv, $sysSv, $idleSv) = ($userN, $niceN, $sysN, $idleN); - my $total = $user + $nice + $sys + $idle; - my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), - $user/$total, $nice/$total, $sys/$total, $idle/$total); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "load"; +my $NAME = "LoadProbe"; +my $DELAY = 1000; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current CPU usage to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic CPU usage info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub cpuTime () { + my ($user, $nice, $sys, $idle); + + local(*FIN); + open(FIN, ") { + chomp; + if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/o) { + ($user, $nice, $sys, $idle) = ($1, $2, $3, $4); + last; + } + } + close(FIN); + return ($user, $nice, $sys, $idle); +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# save current cpu ticks +my($userSv, $niceSv, $sysSv, $idleSv) = cpuTime(); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # retrieve new cpu ticks + my ($userN, $niceN, $sysN, $idleN) = cpuTime(); + # compute delta cpu ticks + my ($user, $nice, $sys, $idle) = + ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv); + # store the new saved ticks + ($userSv, $niceSv, $sysSv, $idleSv) = ($userN, $niceN, $sysN, $idleN); + my $total = $user + $nice + $sys + $idle; + my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), + $user/$total, $nice/$total, $sys/$total, $idle/$total); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews1-d/system/probes/cygwin/probe-cygwin.bat b/targets/znews1-d/system/probes/cygwin/probe-cygwin.bat index 4f192949d..b912671dd 100644 --- a/targets/znews1-d/system/probes/cygwin/probe-cygwin.bat +++ b/targets/znews1-d/system/probes/cygwin/probe-cygwin.bat @@ -1,8 +1,8 @@ -@echo off - -C: -chdir C:\server\cygwin\bin -set DEMO_MODE=%1 -set DEMO_TITLE=%2 - -bash --login -i +@echo off + +C: +chdir C:\server\cygwin\bin +set DEMO_MODE=%1 +set DEMO_TITLE=%2 + +bash --login -i diff --git a/targets/znews1-d/system/probes/cygwin/runApachetop.pl b/targets/znews1-d/system/probes/cygwin/runApachetop.pl index aca341ab9..0970d810f 100644 --- a/targets/znews1-d/system/probes/cygwin/runApachetop.pl +++ b/targets/znews1-d/system/probes/cygwin/runApachetop.pl @@ -1,16 +1,16 @@ -#!/usr/bin/perl -w - -use strict; - -############################# -my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; -my $APACHETOP_LOG = "/cygdrive/c/server/rainbow/oracle/targets/znews1/log/apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - -if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; +#!/usr/bin/perl -w + +use strict; + +############################# +my $APACHE_LOG = "/cygdrive/c/server/Apache2/logs/access.log"; +my $APACHETOP_LOG = "/cygdrive/c/server/rainbow/oracle/targets/znews1/log/apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + +if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; diff --git a/targets/znews1-d/system/probes/diskIOProbe-diskstats.pl b/targets/znews1-d/system/probes/diskIOProbe-diskstats.pl index e4a1e3ba5..a40e58938 100644 --- a/targets/znews1-d/system/probes/diskIOProbe-diskstats.pl +++ b/targets/znews1-d/system/probes/diskIOProbe-diskstats.pl @@ -1,125 +1,125 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "diskio"; -my $NAME = "DiskIOProbe"; -my $DELAY = 4000; -############################# - -# Determine diskstats format -my $statfile; -my $uname = `uname -a`; -if ($uname =~ /Linux\s+(.+?)\s+(\d+[.]\d+)/) { - if ($2 eq "2.6") { - $statfile = "/proc/diskstats"; -# } elsif ($2 <= 2.5) { -# $statfile = "/proc/partitions"; # granularity of info more coarse - } -} else { - print "Linux version unsupported for diskstat access! Unable to continue probing\n"; - exit -1; -} - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current accumulated Disk IO to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic Disk IO info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub diskUsage () { - my ($MINOR, $FIRST, $TMIO) = (2, 4, 14); # index to stat entry - my (@accumStat) = (0,0,0,0,0,0,0,0,0,0,0); - my (@dstat); #$rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio - - open(FIN, "< $statfile"); - while () { - chomp; - @dstat = split(/\s+/); # blank zeroth element due to space(s) in beginning - if ($dstat[$MINOR] == 0 && $dstat[$TMIO] > 0) { # accum reading from device - for my $i ($FIRST..$#dstat) { - $accumStat[$i-$FIRST] += $dstat[$i]; - } - #print "Accumulated @accumStat\n"; - } - } - close(FIN); - return @accumStat; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# zero out disk IO stats -my($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) - = (0,0,0,0,0,0,0,0,0,0,0); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - # retrieve new disk IO stats - my ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN) = diskUsage(); - # compute delta stats for all except 9th and 10th - my ($rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio) = - ($rcmpN-$rcmpS, $rmrgN-$rmrgS, $rsectN-$rsectS, $rmsN-$rmsS, $wcmpN-$wcmpS, - $wmrgN-$wmrgS, $wsectN-$wsectS, $wmsN-$wmsS, $curioN, $curmsN, $tmioN-$tmioS); - # store the new saved ticks - ($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) = - ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN); - # each sector is 512 bytes as of kernel 2.4, so divide 2 to get kb - #print "D: $rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio\n" if ($doPrint); - my $kbRead = $rsect/2.0; - my $kbRps = ($rms == 0) ? 0 : ($kbRead / $rms) * 1000; # sec = 1000 ms - my $kbWritten = $wsect/2.0; - my $kbWps = ($wms == 0) ? 0 : ($kbWritten / $wms) * 1000; - my $tps = ($rms+$wms == 0) ? 0 : ($rcmp+$wcmp)/($rms+$wms) * 1000; - my $rpt = sprintf("[%s] %9.2f %9.2f %9.2f %9d %9d %9d %9d %9d\n", "".localtime(), - $tps, $kbRps, $kbWps, $kbRead, $kbWritten, $curio, $curms, $tmio); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "diskio"; +my $NAME = "DiskIOProbe"; +my $DELAY = 4000; +############################# + +# Determine diskstats format +my $statfile; +my $uname = `uname -a`; +if ($uname =~ /Linux\s+(.+?)\s+(\d+[.]\d+)/) { + if ($2 eq "2.6") { + $statfile = "/proc/diskstats"; +# } elsif ($2 <= 2.5) { +# $statfile = "/proc/partitions"; # granularity of info more coarse + } +} else { + print "Linux version unsupported for diskstat access! Unable to continue probing\n"; + exit -1; +} + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current accumulated Disk IO to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic Disk IO info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub diskUsage () { + my ($MINOR, $FIRST, $TMIO) = (2, 4, 14); # index to stat entry + my (@accumStat) = (0,0,0,0,0,0,0,0,0,0,0); + my (@dstat); #$rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio + + open(FIN, "< $statfile"); + while () { + chomp; + @dstat = split(/\s+/); # blank zeroth element due to space(s) in beginning + if ($dstat[$MINOR] == 0 && $dstat[$TMIO] > 0) { # accum reading from device + for my $i ($FIRST..$#dstat) { + $accumStat[$i-$FIRST] += $dstat[$i]; + } + #print "Accumulated @accumStat\n"; + } + } + close(FIN); + return @accumStat; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# zero out disk IO stats +my($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) + = (0,0,0,0,0,0,0,0,0,0,0); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + # retrieve new disk IO stats + my ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN) = diskUsage(); + # compute delta stats for all except 9th and 10th + my ($rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio) = + ($rcmpN-$rcmpS, $rmrgN-$rmrgS, $rsectN-$rsectS, $rmsN-$rmsS, $wcmpN-$wcmpS, + $wmrgN-$wmrgS, $wsectN-$wsectS, $wmsN-$wmsS, $curioN, $curmsN, $tmioN-$tmioS); + # store the new saved ticks + ($rcmpS,$rmrgS,$rsectS,$rmsS,$wcmpS,$wmrgS,$wsectS,$wmsS,$curioS,$curmsS,$tmioS) = + ($rcmpN,$rmrgN,$rsectN,$rmsN,$wcmpN,$wmrgN,$wsectN,$wmsN,$curioN,$curmsN,$tmioN); + # each sector is 512 bytes as of kernel 2.4, so divide 2 to get kb + #print "D: $rcmp,$rmrg,$rsect,$rms,$wcmp,$wmrg,$wsect,$wms,$curio,$curms,$tmio\n" if ($doPrint); + my $kbRead = $rsect/2.0; + my $kbRps = ($rms == 0) ? 0 : ($kbRead / $rms) * 1000; # sec = 1000 ms + my $kbWritten = $wsect/2.0; + my $kbWps = ($wms == 0) ? 0 : ($kbWritten / $wms) * 1000; + my $tps = ($rms+$wms == 0) ? 0 : ($rcmp+$wcmp)/($rms+$wms) * 1000; + my $rpt = sprintf("[%s] %9.2f %9.2f %9.2f %9d %9d %9d %9d %9d\n", "".localtime(), + $tps, $kbRps, $kbWps, $kbRead, $kbWritten, $curio, $curms, $tmio); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews1-d/system/probes/diskIOProbe.pl b/targets/znews1-d/system/probes/diskIOProbe.pl index ec3391891..fe4b002b3 100644 --- a/targets/znews1-d/system/probes/diskIOProbe.pl +++ b/targets/znews1-d/system/probes/diskIOProbe.pl @@ -1,101 +1,101 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "diskio"; -my $NAME = "DiskIOProbe"; -my $DELAY = 5000; -############################# - -# Determine diskstats format -my $IOSTAT = "/usr/bin/iostat"; -if (! -e $IOSTAT) { - print "No iostat found, please install the sysstat package to continue!\n"; - exit -1; -} -my $IOSTAT_ARGS = "-k " . ($DELAY/1000); # period, with indefinite ouput - -sub usage() { - print STDERR << "EOF"; - -This program dumps periodic Disk IO status to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic Disk IO info - -s : be silent, no period info to stdout - -EOF - exit; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# init disk IO stats vars -my($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); -my($isInitial, $cntCycle) = (1, 0); -open(FIN, "$IOSTAT $IOSTAT_ARGS |") - || die "Can't fork $IOSTAT: $!"; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - # retrieve new disk IO stats - while () { - chomp; - if (/^Device:/i) { - ++$cntCycle; - if ($isInitial && $cntCycle > 1) { # no longer initial - print "Filtered initial round!\n" if ($doPrint); - $isInitial = 0; - } - } - if (!$isInitial && - /^(\w+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/) { - ($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB) = ($1, $2, $3, $4, $5, $6); - last; - } - } - my $rpt = sprintf("[%s] %s %.2f %.2f %.2f %d %d\n", "".localtime(), - $dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - usleep($delay); -} - -deregister($ALIAS, [$sock,$fout]); -close(FIN) || die "Bad $IOSTAT: $! $?"; -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "diskio"; +my $NAME = "DiskIOProbe"; +my $DELAY = 5000; +############################# + +# Determine diskstats format +my $IOSTAT = "/usr/bin/iostat"; +if (! -e $IOSTAT) { + print "No iostat found, please install the sysstat package to continue!\n"; + exit -1; +} +my $IOSTAT_ARGS = "-k " . ($DELAY/1000); # period, with indefinite ouput + +sub usage() { + print STDERR << "EOF"; + +This program dumps periodic Disk IO status to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic Disk IO info + -s : be silent, no period info to stdout + +EOF + exit; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# init disk IO stats vars +my($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); +my($isInitial, $cntCycle) = (1, 0); +open(FIN, "$IOSTAT $IOSTAT_ARGS |") + || die "Can't fork $IOSTAT: $!"; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + # retrieve new disk IO stats + while () { + chomp; + if (/^Device:/i) { + ++$cntCycle; + if ($isInitial && $cntCycle > 1) { # no longer initial + print "Filtered initial round!\n" if ($doPrint); + $isInitial = 0; + } + } + if (!$isInitial && + /^(\w+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/) { + ($dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB) = ($1, $2, $3, $4, $5, $6); + last; + } + } + my $rpt = sprintf("[%s] %s %.2f %.2f %.2f %d %d\n", "".localtime(), + $dev, $tps, $rdKBps, $wrKBps, $rdKB, $wrKB); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + usleep($delay); +} + +deregister($ALIAS, [$sock,$fout]); +close(FIN) || die "Bad $IOSTAT: $! $?"; +cleanup($sock, [$fout]); diff --git a/targets/znews1-d/system/probes/fidelityProbe.pl b/targets/znews1-d/system/probes/fidelityProbe.pl index d5a8214ff..d22e3f086 100644 --- a/targets/znews1-d/system/probes/fidelityProbe.pl +++ b/targets/znews1-d/system/probes/fidelityProbe.pl @@ -1,100 +1,100 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "fidelity"; -my $NAME = "FidelityProbe"; -my $DELAY = 1000; -my $REPEATEVERY = 5; -my $APACHE_CONF_DIR = "/etc/apache2"; -my $APACHE_CONF_FILE = "apache2.conf"; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current server fidelity (1,3,5) to Probe Relay file/socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic server fidelity info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub determineFidelity () { - my $fid = 0; - - open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); - my $firstLine = ; # read the first line - if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { - $fid = $1; - } - close(FIN); - - return $fid; -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -my $repeatCnt = $REPEATEVERY; -my $savedFidelity = 0; - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # compute new fidelity status - my $fidelity = determineFidelity(); - if ($fidelity != $savedFidelity || $repeatCnt == 0) { - $savedFidelity = $fidelity; #store new fidelity - my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); - - if ($repeatCnt == 0) { - $repeatCnt = $REPEATEVERY; - } - } else { - $repeatCnt--; - } -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "fidelity"; +my $NAME = "FidelityProbe"; +my $DELAY = 1000; +my $REPEATEVERY = 5; +my $APACHE_CONF_DIR = "/etc/apache2"; +my $APACHE_CONF_FILE = "apache2.conf"; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current server fidelity (1,3,5) to Probe Relay file/socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic server fidelity info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub determineFidelity () { + my $fid = 0; + + open(FIN, "$APACHE_CONF_DIR/$APACHE_CONF_FILE"); + my $firstLine = ; # read the first line + if ($firstLine =~ /[\#]{3} Fidelity-(\d+)/) { + $fid = $1; + } + close(FIN); + + return $fid; +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +my $repeatCnt = $REPEATEVERY; +my $savedFidelity = 0; + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # compute new fidelity status + my $fidelity = determineFidelity(); + if ($fidelity != $savedFidelity || $repeatCnt == 0) { + $savedFidelity = $fidelity; #store new fidelity + my $rpt = sprintf("[%s] %1d\n", "".localtime(), $fidelity); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); + + if ($repeatCnt == 0) { + $repeatCnt = $REPEATEVERY; + } + } else { + $repeatCnt--; + } +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews1-d/system/probes/iostat.c b/targets/znews1-d/system/probes/iostat.c index 2b4e6fab9..13daca2ec 100644 --- a/targets/znews1-d/system/probes/iostat.c +++ b/targets/znews1-d/system/probes/iostat.c @@ -1,1177 +1,1177 @@ -/* - * iostat: report CPU and I/O statistics - * (C) 1998-2004 by Sebastien GODARD - * - *************************************************************************** - * This program is free software; you can redistribute it and/or modify it * - * under the terms of the GNU General Public License as published by the * - * Free Software Foundation; either version 2 of the License, or (at your * - * option) any later version. * - * * - * This program is distributed in the hope that it will be useful, but * - * WITHOUT ANY WARRANTY; without the implied warranty of MERCHANTABILITY * - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * - * for more details. * - * * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 675 Mass Ave, Cambridge, MA 02139, USA. * - *************************************************************************** - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include /* for HZ */ - -#include "version.h" -#include "iostat.h" -#include "common.h" - - -#ifdef USE_NLS -#include -#include -#define _(string) gettext(string) -#else -#define _(string) (string) -#endif - - -struct comm_stats comm_stats[2]; -struct io_stats *st_iodev[2]; -struct io_hdr_stats *st_hdr_iodev; -struct io_dlist *st_dev_list; - -/* Nb of devices (and possibly partitions if -p option was used) found */ -int iodev_nr = 0; - -/* Nb of devices entered on the command line */ -int dlist_idx = 0; - -long interval = 0; -unsigned char timestamp[64]; - -/* - * Nb of processors on the machine. - * A value of 1 means two procs... - */ -int cpu_nr = -1; - - -/* - *************************************************************************** - * Print usage and exit - *************************************************************************** - */ -void usage(char *progname) -{ - fprintf(stderr, _("sysstat version %s\n" - "(C) Sebastien Godard\n" - "Usage: %s [ options... ] [ [ ] ]\n" - "Options are:\n" - "[ -c | -d ] [ -k ] [ -t ] [ -V ] [ -x ]\n" - "[ { [ ... ] | ALL } ] [ -p [ { | ALL } ] ]\n"), - VERSION, progname); - exit(1); -} - - -/* - *************************************************************************** - * SIGALRM signal handler - *************************************************************************** - */ -void alarm_handler(int sig) -{ - signal(SIGALRM, alarm_handler); - alarm(interval); -} - - -/* - *************************************************************************** - * Initialize stats common structures - *************************************************************************** - */ -void init_stats(void) -{ - memset(&comm_stats[0], 0, COMM_STATS_SIZE); - memset(&comm_stats[1], 0, COMM_STATS_SIZE); -} - - -/* - *************************************************************************** - * Set every disk_io entry to inactive state - *************************************************************************** - */ -void set_entries_inactive(int iodev_nr) -{ - int i; - struct io_hdr_stats *st_hdr_iodev_i; - - for (i = 0; i < iodev_nr; i++) { - st_hdr_iodev_i = st_hdr_iodev + i; - st_hdr_iodev_i->active = FALSE; - } -} - - -/* - *************************************************************************** - * Set structures's state to free for inactive entries - *************************************************************************** - */ -void free_inactive_entries(int iodev_nr) -{ - int i; - struct io_hdr_stats *st_hdr_iodev_i; - - for (i = 0; i < iodev_nr; i++) { - st_hdr_iodev_i = st_hdr_iodev + i; - if (!st_hdr_iodev_i->active) - st_hdr_iodev_i->major = 0; - } -} - - -/* - *************************************************************************** - * Allocate and init I/O devices structures - *************************************************************************** - */ -void salloc_device(int iodev_nr) -{ - int i; - struct io_hdr_stats *st_hdr_iodev_i; - - for (i = 0; i < 2; i++) { - if ((st_iodev[i] = (struct io_stats *) malloc(IO_STATS_SIZE * iodev_nr)) == NULL) { - perror("malloc"); - exit(4); - } - memset(st_iodev[i], 0, IO_STATS_SIZE * iodev_nr); - } - - if ((st_hdr_iodev = (struct io_hdr_stats *) malloc(IO_HDR_STATS_SIZE * iodev_nr)) == NULL) { - perror("malloc"); - exit(4); - } - memset(st_hdr_iodev, 0, IO_HDR_STATS_SIZE * iodev_nr); - - if (iodev_nr == 4) { - /* - * We may have an old kernel with the stats for the first four disks - * in /proc/stat: reset the devices name. Anyway, if we are wrong, - * the names will be read from disk_io entry in /proc/stat or from - * /sys. - */ - for (i = 0; i < 4; i++) { - st_hdr_iodev_i = st_hdr_iodev + i; - sprintf(st_hdr_iodev_i->name, "hdisk%d", i); - } - } -} - - -/* - *************************************************************************** - * Allocate structures for devices entered on the command line - *************************************************************************** - */ -void salloc_dev_list(int list_len) -{ - if ((st_dev_list = (struct io_dlist *) malloc(IO_DLIST_SIZE * list_len)) == NULL) { - perror("malloc"); - exit(4); - } - memset(st_dev_list, 0, IO_DLIST_SIZE * list_len); -} - - -/* - *************************************************************************** - * Look for the device in the device list - * and store it if necessary. - *************************************************************************** - */ -int update_dev_list(int *dlist_idx, char *device_name) -{ - int i; - struct io_dlist *st_dev_list_i; - - st_dev_list_i = st_dev_list; - - for (i = 0; i < *dlist_idx; i++) { - st_dev_list_i = st_dev_list + i; - if (!strcmp(st_dev_list_i->dev_name, device_name)) - break; - } - - if (i == *dlist_idx) { - (*dlist_idx)++; - st_dev_list_i = st_dev_list + i; - strncpy(st_dev_list_i->dev_name, device_name, MAX_NAME_LEN - 1); - } - - return i; -} - - -/* - *************************************************************************** - * Allocate and init structures, according to system state - *************************************************************************** - */ -void io_sys_init(int *flags) -{ - /* Init stat common counters */ - init_stats(); - - /* How many processors on this machine ? */ - get_cpu_nr(&cpu_nr, ~0); - - /* Get number of block devices and partitions in /proc/diskstats */ - if ((iodev_nr = get_diskstats_dev_nr(CNT_PART)) > 0) { - *flags |= F_HAS_DISKSTATS; - iodev_nr += NR_DEV_PREALLOC; - } - - if (!HAS_DISKSTATS(*flags) || - (DISPLAY_PARTITIONS(*flags) && !DISPLAY_PART_ALL(*flags))) { - /* - * If /proc/diskstats exists but we also want stats for the partitions - * of a particular device, stats will have to be found in /sys. So we - * need to know if /sys is mounted or not, and set *flags accordingly. - */ - - /* Get number of block devices (and partitions) in sysfs */ - if ((iodev_nr = get_sysfs_dev_nr(*flags)) > 0) { - *flags |= F_HAS_SYSFS; - iodev_nr += NR_DEV_PREALLOC; - } - /* Get number of "disk_io:" entries in /proc/stat */ - else if ((iodev_nr = get_disk_io_nr()) > 0) - iodev_nr += NR_DISK_PREALLOC; - else { - /* Assume we have an old kernel: stats for 4 disks are in /proc/stat */ - iodev_nr = 4; - *flags |= F_OLD_KERNEL; - } - } - /* Allocate structures for number of disks found */ - salloc_device(iodev_nr); -} - - -/* - *************************************************************************** - * Save stats for current device or partition - *************************************************************************** - */ -void save_dev_stats(char *dev_name, int curr, struct io_stats *sdev) -{ - int i; - struct io_hdr_stats *st_hdr_iodev_i; - struct io_stats *st_iodev_i; - - /* Look for device in data table */ - for (i = 0; i < iodev_nr; i++) { - st_hdr_iodev_i = st_hdr_iodev + i; - if (!strcmp(st_hdr_iodev_i->name, dev_name)) { - break; - } - } - - if (i == iodev_nr) { - /* - * This is a new device: look for an unused entry to store it. - * Thus we are able to handle dynamically registered devices. - */ - for (i = 0; i < iodev_nr; i++) { - st_hdr_iodev_i = st_hdr_iodev + i; - if (!st_hdr_iodev_i->major) { - /* Unused entry found... */ - st_hdr_iodev_i->major = 1; /* Just to indicate it is now used! */ - strcpy(st_hdr_iodev_i->name, dev_name); - st_iodev_i = st_iodev[!curr] + i; - memset(st_iodev_i, 0, IO_STATS_SIZE); - break; - } - } - } - if (i < iodev_nr) { - st_hdr_iodev_i = st_hdr_iodev + i; - st_hdr_iodev_i->active = TRUE; - st_iodev_i = st_iodev[curr] + i; - *st_iodev_i = *sdev; - } -} - - -/* - *************************************************************************** - * Read stats from /proc/stat file... - * (see linux source file linux/fs/proc/array.c) - * Useful at least for CPU utilization. - * May be useful to get disk stats if /sys not available. - *************************************************************************** - */ -void read_stat(int curr, int flags) -{ - FILE *statfp; - char line[8192]; - int pos, i; - unsigned int v_tmp[3], v_major, v_index; - struct io_stats *st_iodev_tmp[4], *st_iodev_i; - struct io_hdr_stats *st_hdr_iodev_i; - unsigned long cc_idle, cc_iowait; - unsigned int cc_user, cc_nice, cc_system, cc_hardirq, cc_softirq; - - - /* - * Prepare pointers on the 4 disk structures in case we have a - * /proc/stat file with "disk_rblk", etc. entries. - */ - for (i = 0; i < 4; i++) - st_iodev_tmp[i] = st_iodev[curr] + i; - - /* Open stat file */ - if ((statfp = fopen(STAT, "r")) == NULL) { - perror("fopen"); - exit(2); - } - - while (fgets(line, 8192, statfp) != NULL) { - - if (!strncmp(line, "cpu ", 4)) { - /* - * Read the number of jiffies spent in the different modes, - * and compute system uptime in jiffies (1/100ths of a second - * if HZ=100). - * Some fields are only presnt in 2.6 kernels. - */ - comm_stats[curr].cpu_iowait = 0; /* For pre 2.6 kernels */ - cc_hardirq = cc_softirq = 0; - sscanf(line + 5, "%u %u %u %lu %lu %u %u", - &(comm_stats[curr].cpu_user), &(comm_stats[curr].cpu_nice), - &(comm_stats[curr].cpu_system), &(comm_stats[curr].cpu_idle), - &(comm_stats[curr].cpu_iowait), &cc_hardirq, &cc_softirq); - - /* - * Time spent in system mode also includes time spent servicing - * interrupts and softirqs. - */ - comm_stats[curr].cpu_system += cc_hardirq + cc_softirq; - - /* - * Compute system uptime in jiffies. - * Uptime is multiplied by the number of processors. - */ - comm_stats[curr].uptime = comm_stats[curr].cpu_user + - comm_stats[curr].cpu_nice + - comm_stats[curr].cpu_system + - comm_stats[curr].cpu_idle + - comm_stats[curr].cpu_iowait; - } - - else if ((!strncmp(line, "cpu0", 4)) && cpu_nr) { - /* - * Read CPU line for proc#0 (if available). - * Useful to compute uptime reduced to one processor on SMP machines, - * with fewer risks to get an overflow... - */ - cc_iowait = cc_hardirq = cc_softirq = 0; - sscanf(line + 5, "%u %u %u %lu %lu %u %u", - &cc_user, &cc_nice, &cc_system, &cc_idle, &cc_iowait, - &cc_hardirq, &cc_softirq); - comm_stats[curr].uptime0 = cc_user + cc_nice + cc_system + - cc_idle + cc_iowait + - cc_hardirq + cc_softirq; - } - - else if (DISPLAY_EXTENDED(flags) || HAS_DISKSTATS(flags) || HAS_SYSFS(flags)) - /* - * When displaying extended statistics, or if /proc/diskstats exists or /sys is mounted, - * we just need to get CPU info from /proc/stat. - */ - continue; - - else if (!strncmp(line, "disk_rblk ", 10)) { - /* - * Read the number of blocks read from disk. - * A block is of indeterminate size. - * The size may vary depending on the device type. - */ - sscanf(line + 10, "%u %u %u %u", - &v_tmp[0], &v_tmp[1], &v_tmp[2], &v_tmp[3]); - - st_iodev_tmp[0]->dk_drive_rblk = v_tmp[0]; - st_iodev_tmp[1]->dk_drive_rblk = v_tmp[1]; - st_iodev_tmp[2]->dk_drive_rblk = v_tmp[2]; - st_iodev_tmp[3]->dk_drive_rblk = v_tmp[3]; - } - - else if (!strncmp(line, "disk_wblk ", 10)) { - /* Read the number of blocks written to disk */ - sscanf(line + 10, "%u %u %u %u", - &v_tmp[0], &v_tmp[1], &v_tmp[2], &v_tmp[3]); - - st_iodev_tmp[0]->dk_drive_wblk = v_tmp[0]; - st_iodev_tmp[1]->dk_drive_wblk = v_tmp[1]; - st_iodev_tmp[2]->dk_drive_wblk = v_tmp[2]; - st_iodev_tmp[3]->dk_drive_wblk = v_tmp[3]; - } - - else if (!strncmp(line, "disk ", 5)) { - /* Read the number of I/O done since the last reboot */ - sscanf(line + 5, "%u %u %u %u", - &v_tmp[0], &v_tmp[1], &v_tmp[2], &v_tmp[3]); - - st_iodev_tmp[0]->dk_drive = v_tmp[0]; - st_iodev_tmp[1]->dk_drive = v_tmp[1]; - st_iodev_tmp[2]->dk_drive = v_tmp[2]; - st_iodev_tmp[3]->dk_drive = v_tmp[3]; - } - - else if (!strncmp(line, "disk_io: ", 9)) { - pos = 9; - - /* Every disk_io entry is potentially unregistered */ - set_entries_inactive(iodev_nr); - - /* Read disks I/O statistics (for 2.4 kernels) */ - while (pos < strlen(line) - 1) { - /* Beware: a CR is already included in the line */ - sscanf(line + pos, "(%u,%u):(%u,%*u,%u,%*u,%u) ", - &v_major, &v_index, &v_tmp[0], &v_tmp[1], &v_tmp[2]); - - /* Look for disk entry */ - for (i = 0; i < iodev_nr; i++) { - st_hdr_iodev_i = st_hdr_iodev + i; - if ((st_hdr_iodev_i->major == v_major) && - (st_hdr_iodev_i->index == v_index)) - break; - } - - if (i == iodev_nr) { - /* - * New disk registered. Assume that disks may be registered, - * *and* unregistered dynamically... - * Look for a free structure to store it. - */ - for (i = 0; i < iodev_nr; i++) { - st_hdr_iodev_i = st_hdr_iodev + i; - if (!st_hdr_iodev_i->major) { - /* Free structure found! */ - st_hdr_iodev_i->major = v_major; - st_hdr_iodev_i->index = v_index; - sprintf(st_hdr_iodev_i->name, "dev%d-%d", v_major, v_index); - st_iodev_i = st_iodev[!curr] + i; - memset(st_iodev_i, 0, IO_STATS_SIZE); - break; - } - } - } - - if (i < iodev_nr) { - st_hdr_iodev_i = st_hdr_iodev + i; - st_hdr_iodev_i->active = TRUE; - st_iodev_i = st_iodev[curr] + i; - st_iodev_i->dk_drive = v_tmp[0]; - st_iodev_i->dk_drive_rblk = v_tmp[1]; - st_iodev_i->dk_drive_wblk = v_tmp[2]; - } - /* else the disk_io entry was not found, - * and there was no free structure to store it */ - - pos += strcspn(line + pos, " ") + 1; - } - - /* Free structures corresponding to unregistered disks */ - free_inactive_entries(iodev_nr); - } - } - - /* Close stat file */ - fclose(statfp); -} - - -/* - *************************************************************************** - * Read sysfs stat for current block device or partition - *************************************************************************** - */ -int read_sysfs_file_stat(int curr, char *filename, char *dev_name, - int dev_type) -{ - FILE *sysfp; - struct io_stats sdev; - int i; - - /* Try to read given stat file */ - if ((sysfp = fopen(filename, "r")) == NULL) - return 0; - - if (dev_type == DT_DEVICE) - i = (fscanf(sysfp, "%d %d %d %d %d %d %d %d %d %d %d", - &sdev.rd_ios, &sdev.rd_merges, - &sdev.rd_sectors, &sdev.rd_ticks, - &sdev.wr_ios, &sdev.wr_merges, - &sdev.wr_sectors, &sdev.wr_ticks, - &sdev.ios_pgr, &sdev.tot_ticks, &sdev.rq_ticks) == 11); - else - i = (fscanf(sysfp, "%d %d %d %d", - &sdev.rd_ios, &sdev.rd_sectors, - &sdev.wr_ios, &sdev.wr_sectors) == 4); - - if (i) - save_dev_stats(dev_name, curr, &sdev); - - fclose(sysfp); - - return 1; -} - - -/* - *************************************************************************** - * Read sysfs stats for all the partitions of a device - *************************************************************************** - */ -void read_sysfs_dlist_part_stat(int curr, char *dev_name) -{ - DIR *dir; - struct dirent *drd; - char dfile[MAX_PF_NAME], filename[MAX_PF_NAME]; - - sprintf(dfile, "%s/%s", SYSFS_BLOCK, dev_name); - - /* Open current device directory in /sys/block */ - if ((dir = opendir(dfile)) == NULL) - return; - - /* Get current entry */ - while ((drd = readdir(dir)) != NULL) { - if (!strcmp(drd->d_name, ".") || !strcmp(drd->d_name, "..")) - continue; - sprintf(filename, "%s/%s/%s", dfile, drd->d_name, S_STAT); - - /* Read current partition stats */ - read_sysfs_file_stat(curr, filename, drd->d_name, DT_PARTITION); - } - - /* Close device directory */ - (void) closedir(dir); -} - - -/* - *************************************************************************** - * Read stats from the sysfs filesystem - * for the devices entered on the command line - *************************************************************************** - */ -void read_sysfs_dlist_stat(int curr, int flags) -{ - int dev, ok; - char filename[MAX_PF_NAME]; - struct io_dlist *st_dev_list_i; - - /* Every I/O device (or partition) is potentially unregistered */ - set_entries_inactive(iodev_nr); - - for (dev = 0; dev < dlist_idx; dev++) { - st_dev_list_i = st_dev_list + dev; - sprintf(filename, "%s/%s/%s", - SYSFS_BLOCK, st_dev_list_i->dev_name, S_STAT); - - /* Read device stats */ - ok = read_sysfs_file_stat(curr, filename, st_dev_list_i->dev_name, DT_DEVICE); - - if (ok && st_dev_list_i->disp_part) - /* Also read stats for its partitions */ - read_sysfs_dlist_part_stat(curr, st_dev_list_i->dev_name); - } - - /* Free structures corresponding to unregistered devices */ - free_inactive_entries(iodev_nr); -} - - -/* - *************************************************************************** - * Read stats from the sysfs filesystem - * for every block devices found - *************************************************************************** - */ -void read_sysfs_stat(int curr, int flags) -{ - DIR *dir; - struct dirent *drd; - char filename[MAX_PF_NAME]; - int ok; - - /* Every I/O device entry is potentially unregistered */ - set_entries_inactive(iodev_nr); - - /* Open /sys/block directory */ - if ((dir = opendir(SYSFS_BLOCK)) != NULL) { - - /* Get current entry */ - while ((drd = readdir(dir)) != NULL) { - if (!strcmp(drd->d_name, ".") || !strcmp(drd->d_name, "..")) - continue; - sprintf(filename, "%s/%s/%s", SYSFS_BLOCK, drd->d_name, S_STAT); - - /* If current entry is a directory, try to read its stat file */ - ok = read_sysfs_file_stat(curr, filename, drd->d_name, DT_DEVICE); - - /* - * If '-p ALL' was entered on the command line, - * also try to read stats for its partitions - */ - if (ok && DISPLAY_PART_ALL(flags)) - read_sysfs_dlist_part_stat(curr, drd->d_name); - } - - /* Close /sys/block directory */ - (void) closedir(dir); - } - - /* Free structures corresponding to unregistered devices */ - free_inactive_entries(iodev_nr); -} - - -/* - *************************************************************************** - * Read stats from /proc/diskstats - *************************************************************************** - */ -void read_diskstats_stat(int curr, int flags) -{ - FILE *dstatsfp; - char line[256], dev_name[MAX_NAME_LEN]; - struct io_stats sdev; - int i; - int tmp[11]; - - /* Every I/O device entry is potentially unregistered */ - set_entries_inactive(iodev_nr); - - /* Open /proc/diskstats file */ - if ((dstatsfp = fopen(DISKSTATS, "r")) == NULL) - return; - - while (fgets(line, 256, dstatsfp) != NULL) { - - i = sscanf(line, "%*d %*d %s %d %d %d %d %d %d %d %d %d %d %d", - dev_name, - &tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5], - &tmp[6], &tmp[7], &tmp[8], &tmp[9], &tmp[10]); - - if (i == 12) { - /* Device */ - sdev.rd_ios = tmp[0]; sdev.rd_merges = tmp[1]; - sdev.rd_sectors = tmp[2]; sdev.rd_ticks = tmp[3]; - sdev.wr_ios = tmp[4]; sdev.wr_merges = tmp[5]; - sdev.wr_sectors = tmp[6]; sdev.wr_ticks = tmp[7]; - sdev.ios_pgr = tmp[8]; sdev.tot_ticks = tmp[9]; - sdev.rq_ticks = tmp[10]; - } - else if (i == 5) { - /* Partition */ - if (DISPLAY_EXTENDED(flags) || (!dlist_idx && !DISPLAY_PARTITIONS(flags))) - continue; - sdev.rd_ios = tmp[0]; sdev.rd_sectors = tmp[1]; - sdev.wr_ios = tmp[2]; sdev.wr_sectors = tmp[3]; - } - else - /* Unknown entry: ignore it */ - continue; - - save_dev_stats(dev_name, curr, &sdev); - } - - fclose(dstatsfp); - - /* Free structures corresponding to unregistered devices */ - free_inactive_entries(iodev_nr); -} - - -/* - *************************************************************************** - * Display CPU utilization - *************************************************************************** - */ -void write_cpu_stat(int curr, unsigned long itv) -{ - printf(_("avg-cpu: %%user %%nice %%sys %%iowait %%idle\n")); - - printf(" %6.2f %6.2f %6.2f %6.2f", - SP_VALUE(comm_stats[!curr].cpu_user, comm_stats[curr].cpu_user, itv), - SP_VALUE(comm_stats[!curr].cpu_nice, comm_stats[curr].cpu_nice, itv), - SP_VALUE(comm_stats[!curr].cpu_system, comm_stats[curr].cpu_system, itv), - SP_VALUE(comm_stats[!curr].cpu_iowait, comm_stats[curr].cpu_iowait, itv)); - - if (comm_stats[curr].cpu_idle < comm_stats[!curr].cpu_idle) - printf(" %.2f", 0.0); - else - printf(" %6.2f", - SP_VALUE(comm_stats[!curr].cpu_idle, comm_stats[curr].cpu_idle, itv)); - - printf("\n\n"); -} - - -/* - *************************************************************************** - * Display extended stats (those read from /proc/diskstats or /sys) - *************************************************************************** - */ -void write_ext_stat(int curr, unsigned long itv, int flags) -{ - int dev, i; - struct io_stats sdev; - struct io_hdr_stats *st_hdr_iodev_i; - struct io_stats *st_iodev_i, *st_iodev_j; - struct io_dlist *st_dev_list_i; - double tput, util, await, svctm, arqsz, nr_ios; - - printf(_("Device: rrqm/s wrqm/s r/s w/s rsec/s wsec/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %%util\n")); - /* "xxxxxxxxxx 999.99 999.99 99.99 99.99 9999.99 9999.99 99999.99 99999.99 99999.99 99999.99 9999.99 999.99 %999.99\n" */ - - for (i = 0; i < iodev_nr; i++) { - st_hdr_iodev_i = st_hdr_iodev + i; - if (st_hdr_iodev_i->major) { - - if (HAS_DISKSTATS(flags) && dlist_idx) { - /* - * With sysfs, only stats for the requested devices are read. - * With /proc/diskstats, stats for every devices are read. - * Thus we need to check if stats for current device are to - * be displayed. - */ - for (dev = 0; dev < dlist_idx; dev++) { - st_dev_list_i = st_dev_list + dev; - if (!strcmp(st_hdr_iodev_i->name, st_dev_list_i->dev_name)) - break; - } - if (dev == dlist_idx) - /* Device not found in list: don't display it */ - continue; - } - - st_iodev_i = st_iodev[curr] + i; - st_iodev_j = st_iodev[!curr] + i; - - if (!DISPLAY_UNFILTERED(flags)) { - if (!st_iodev_i->rd_ios && !st_iodev_i->wr_ios) - continue; - } - - sdev.rd_ios = st_iodev_i->rd_ios - st_iodev_j->rd_ios; - sdev.wr_ios = st_iodev_i->wr_ios - st_iodev_j->wr_ios; - sdev.rd_ticks = st_iodev_i->rd_ticks - st_iodev_j->rd_ticks; - sdev.wr_ticks = st_iodev_i->wr_ticks - st_iodev_j->wr_ticks; - sdev.rd_merges = st_iodev_i->rd_merges - st_iodev_j->rd_merges; - sdev.wr_merges = st_iodev_i->wr_merges - st_iodev_j->wr_merges; - sdev.rd_sectors = st_iodev_i->rd_sectors - st_iodev_j->rd_sectors; - sdev.wr_sectors = st_iodev_i->wr_sectors - st_iodev_j->wr_sectors; - sdev.tot_ticks = st_iodev_i->tot_ticks - st_iodev_j->tot_ticks; - sdev.rq_ticks = st_iodev_i->rq_ticks - st_iodev_j->rq_ticks; - - nr_ios = sdev.rd_ios + sdev.wr_ios; - tput = nr_ios * HZ / itv; - util = ((double) sdev.tot_ticks) / itv * HZ; - svctm = tput ? util / tput : 0.0; - /* - * kernel gives ticks already in milliseconds for all platforms - * => no need for further scaling. - */ - await = nr_ios ? - (sdev.rd_ticks + sdev.wr_ticks) / nr_ios : 0.0; - arqsz = nr_ios ? - (sdev.rd_sectors + sdev.wr_sectors) / nr_ios : 0.0; - - printf("%-10s", st_hdr_iodev_i->name); - if (strlen(st_hdr_iodev_i->name) > 10) - printf("\n "); - /* rrq/s wrq/s r/s w/s rsec wsec rkB wkB rqsz qusz await svctm %util */ - printf(" %6.2f %6.2f %5.2f %5.2f %7.2f %7.2f %8.2f %8.2f %8.2f %8.2f %7.2f %6.2f %6.2f\n", - ((double) sdev.rd_merges) / itv * HZ, - ((double) sdev.wr_merges) / itv * HZ, - ((double) sdev.rd_ios) / itv * HZ, - ((double) sdev.wr_ios) / itv * HZ, - ((double) sdev.rd_sectors) / itv * HZ, - ((double) sdev.wr_sectors) / itv * HZ, - ((double) sdev.rd_sectors) / itv * HZ / 2, - ((double) sdev.wr_sectors) / itv * HZ / 2, - arqsz, - ((double) sdev.rq_ticks) / itv * HZ / 1000.0, - await, - /* The ticks output is biased to output 1000 ticks per second */ - svctm, - /* Again: ticks in milliseconds */ - util / 10.0); - } - } -} - - -/* - *************************************************************************** - * Write basic stats, read from /proc/stat file or from sysfs - *************************************************************************** - */ -void write_basic_stat(int curr, unsigned long itv, int flags) -{ - int fctr = 1; - int i, j; - struct io_hdr_stats *st_hdr_iodev_i; - struct io_stats *st_iodev_i, *st_iodev_j; - struct io_dlist *st_dev_list_j; - - if (DISPLAY_KILOBYTES(flags)) { - printf(_("Device: tps kB_read/s kB_wrtn/s kB_read kB_wrtn\n")); - fctr = 2; - } - else - printf(_("Device: tps Blk_read/s Blk_wrtn/s Blk_read Blk_wrtn\n")); - - for (i = 0; i < iodev_nr; i++) { - st_hdr_iodev_i = st_hdr_iodev + i; - if (st_hdr_iodev_i->major || HAS_OLD_KERNEL(flags)) { - - if (dlist_idx && !HAS_SYSFS(flags)) { - /* - * If devices have been entered on the command line, display the - * stats only for them. - * No problem if sysfs is mounted, since in this case only the - * requested devices have been read... - */ - for (j = 0; j < dlist_idx; j++) { - st_dev_list_j = st_dev_list + j; - if (!strcmp(st_hdr_iodev_i->name, st_dev_list_j->dev_name)) - break; - } - if (j == dlist_idx) - /* Device not found in list: skip it */ - continue; - } - - st_iodev_i = st_iodev[curr] + i; - st_iodev_j = st_iodev[!curr] + i; - - if (!DISPLAY_UNFILTERED(flags)) { - if (HAS_SYSFS(flags) || HAS_DISKSTATS(flags)) { - if (!st_iodev_i->rd_ios && !st_iodev_i->wr_ios) - continue; - } - else if (!st_iodev_i->dk_drive) - continue; - } - - printf("%-13s", st_hdr_iodev_i->name); - if (strlen(st_hdr_iodev_i->name) > 13) - printf("\n "); - - if (HAS_SYSFS(flags) || HAS_DISKSTATS(flags)) { - /* Print stats coming from /sys or /proc/diskstats */ - printf(" %8.2f %12.2f %12.2f %10u %10u\n", - S_VALUE(st_iodev_j->rd_ios + st_iodev_j->wr_ios, - st_iodev_i->rd_ios + st_iodev_i->wr_ios, itv), - S_VALUE(st_iodev_j->rd_sectors, - st_iodev_i->rd_sectors, itv) / fctr, - S_VALUE(st_iodev_j->wr_sectors, - st_iodev_i->wr_sectors, itv) / fctr, - (st_iodev_i->rd_sectors - - st_iodev_j->rd_sectors) / fctr, - (st_iodev_i->wr_sectors - - st_iodev_j->wr_sectors) / fctr); - } - else { - /* Print stats coming from /proc/stat */ - printf(" %8.2f %12.2f %12.2f %10u %10u\n", - S_VALUE(st_iodev_j->dk_drive, - st_iodev_i->dk_drive, itv), - S_VALUE(st_iodev_j->dk_drive_rblk, - st_iodev_i->dk_drive_rblk, itv) / fctr, - S_VALUE(st_iodev_j->dk_drive_wblk, - st_iodev_i->dk_drive_wblk, itv) / fctr, - (st_iodev_i->dk_drive_rblk - - st_iodev_j->dk_drive_rblk) / fctr, - (st_iodev_i->dk_drive_wblk - - st_iodev_j->dk_drive_wblk) / fctr); - } - } - } -} - - -/* - *************************************************************************** - * Print everything now (stats and uptime) - *************************************************************************** - */ -int write_stat(int curr, int flags, struct tm *loc_time) -{ - unsigned long itv; - - /* - * Under very special circumstances, STDOUT may become unavailable, - * This is what we try to guess here - */ - if (write(STDOUT_FILENO, "", 0) == -1) { - perror("stdout"); - exit(6); - } - - /* Print time stamp */ - if (DISPLAY_TIMESTAMP(flags)) { - strftime(timestamp, sizeof(timestamp), "%X ", loc_time); - printf(_("Time: %s\n"), timestamp); - } - - /* - * itv is multiplied by the number of processors. - * This is OK to compute CPU usage since the number of jiffies spent in the - * different modes (user, nice, etc.) is the sum of all the processors. - * But itv should be reduced to one processor before displaying disk - * utilization. - */ - itv = comm_stats[curr].uptime - comm_stats[!curr].uptime; /* uptime in jiffies */ - if (!itv) - itv = 1; - - if (!DISPLAY_DISK_ONLY(flags)) - /* Display CPU utilization */ - write_cpu_stat(curr, itv); - - if (cpu_nr) { - /* On SMP machines, reduce itv to one processor (see note above) */ - itv = comm_stats[curr].uptime0 - comm_stats[!curr].uptime0; - if (!itv) - itv = 1; - } - - if (!DISPLAY_CPU_ONLY(flags)) { - - if (DISPLAY_EXTENDED(flags)) - /* Write extended stats, read from /proc/diskstats or /sys */ - write_ext_stat(curr, itv, flags); - else - /* Write basic stats, read from /proc/stat, /proc/diskstats or /sys */ - write_basic_stat(curr, itv, flags); - - printf("\n"); - } - return 1; -} - - -/* - *************************************************************************** - * Main loop: read I/O stats from the relevant sources, - * and display them. - *************************************************************************** - */ -void rw_io_stat_loop(int flags, long int count, struct tm *loc_time) -{ - int curr = 1; - int next; - - do { - /* Read kernel statistics (CPU, and possibly disks for old kernels) */ - read_stat(curr, flags); - - if (dlist_idx) { - /* - * A device or partition name was entered on the command line, - * with or without -p option (but not -p ALL). - */ - if (HAS_DISKSTATS(flags) && !DISPLAY_PARTITIONS(flags)) - read_diskstats_stat(curr, flags); - else if (HAS_SYSFS(flags)) - read_sysfs_dlist_stat(curr, flags); - } - else { - /* - * No devices nor partitions entered on the command line - * (for example if -p ALL was used). - */ - if (HAS_DISKSTATS(flags)) - read_diskstats_stat(curr, flags); - else if (HAS_SYSFS(flags)) - read_sysfs_stat(curr,flags); - } - - /* Save time */ - get_localtime(loc_time); - - /* Print results */ - if ((next = write_stat(curr, flags, loc_time)) - && (count > 0)) - count--; - fflush(stdout); - - if (count) { - pause(); - - if (next) - curr ^= 1; - } - } - while (count); -} - - -/* - *************************************************************************** - * Main entry to the iostat program - *************************************************************************** - */ -int main(int argc, char **argv) -{ - int it = 0, flags = 0; - int opt = 1; - int i; - long count = 1; - struct utsname header; - struct io_dlist *st_dev_list_i; - struct tm loc_time; - -#ifdef USE_NLS - /* Init National Language Support */ - init_nls(); -#endif - - /* Allocate structures for device list */ - if (argc > 1) - salloc_dev_list(argc - 1); - - /* Process args... */ - while (opt < argc) { - - if (!strcmp(argv[opt], "-p")) { - flags |= D_PARTITIONS; - if (argv[++opt] && (strspn(argv[opt], DIGITS) != strlen(argv[opt])) && - (strncmp(argv[opt], "-", 1))) { - flags |= D_UNFILTERED; - if (!strcmp(argv[opt], K_ALL)) { - flags |= D_PART_ALL; - opt++; - } - else { - /* Store device name */ - i = update_dev_list(&dlist_idx, device_name(argv[opt++])); - st_dev_list_i = st_dev_list + i; - st_dev_list_i->disp_part = TRUE; - } - } - else - flags |= D_PART_ALL; - } - - else if (!strncmp(argv[opt], "-", 1)) { - for (i = 1; *(argv[opt] + i); i++) { - - switch (*(argv[opt] + i)) { - - case 'c': - flags |= D_CPU_ONLY; /* Display cpu usage only */ - flags &= ~D_DISK_ONLY; - break; - - case 'd': - flags |= D_DISK_ONLY; /* Display disk utilization only */ - flags &= ~D_CPU_ONLY; - break; - - case 'k': - flags |= D_KILOBYTES; /* Display stats in kB/s */ - break; - - case 't': - flags |= D_TIMESTAMP; /* Display timestamp */ - break; - - case 'x': - flags |= D_EXTENDED; /* Display extended stats */ - break; - - case 'V': /* Print usage and exit */ - default: - usage(argv[0]); - } - } - opt++; - } - - else if (!isdigit(argv[opt][0])) { - flags |= D_UNFILTERED; - if (strcmp(argv[opt], K_ALL)) - /* Store device name */ - update_dev_list(&dlist_idx, device_name(argv[opt++])); - else - opt++; - } - - else if (!it) { - interval = atol(argv[opt++]); - if (interval < 1) - usage(argv[0]); - count = -1; - it = 1; - } - - else { - count = atol(argv[opt++]); - if (count < 1) - usage(argv[0]); - } - } - - /* Linux does not provide extended stats for partitions */ - if (DISPLAY_PARTITIONS(flags) && DISPLAY_EXTENDED(flags)) { - fprintf(stderr, _("-x and -p options are mutually exclusive\n")); - exit(1); - } - - /* Ignore device list if '-p ALL' entered on the command line */ - if (DISPLAY_PART_ALL(flags)) - dlist_idx = 0; - - /* Init structures according to machine architecture */ - io_sys_init(&flags); - - get_localtime(&loc_time); - - /* Get system name, release number and hostname */ - uname(&header); - print_gal_header(&loc_time, - header.sysname, header.release, header.nodename); - printf("\n"); - - /* Set a handler for SIGALRM */ - alarm_handler(0); - - /* Main loop */ - rw_io_stat_loop(flags, count, &loc_time); - - return 0; -} +/* + * iostat: report CPU and I/O statistics + * (C) 1998-2004 by Sebastien GODARD + * + *************************************************************************** + * This program is free software; you can redistribute it and/or modify it * + * under the terms of the GNU General Public License as published by the * + * Free Software Foundation; either version 2 of the License, or (at your * + * option) any later version. * + * * + * This program is distributed in the hope that it will be useful, but * + * WITHOUT ANY WARRANTY; without the implied warranty of MERCHANTABILITY * + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * + * for more details. * + * * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 675 Mass Ave, Cambridge, MA 02139, USA. * + *************************************************************************** + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* for HZ */ + +#include "version.h" +#include "iostat.h" +#include "common.h" + + +#ifdef USE_NLS +#include +#include +#define _(string) gettext(string) +#else +#define _(string) (string) +#endif + + +struct comm_stats comm_stats[2]; +struct io_stats *st_iodev[2]; +struct io_hdr_stats *st_hdr_iodev; +struct io_dlist *st_dev_list; + +/* Nb of devices (and possibly partitions if -p option was used) found */ +int iodev_nr = 0; + +/* Nb of devices entered on the command line */ +int dlist_idx = 0; + +long interval = 0; +unsigned char timestamp[64]; + +/* + * Nb of processors on the machine. + * A value of 1 means two procs... + */ +int cpu_nr = -1; + + +/* + *************************************************************************** + * Print usage and exit + *************************************************************************** + */ +void usage(char *progname) +{ + fprintf(stderr, _("sysstat version %s\n" + "(C) Sebastien Godard\n" + "Usage: %s [ options... ] [ [ ] ]\n" + "Options are:\n" + "[ -c | -d ] [ -k ] [ -t ] [ -V ] [ -x ]\n" + "[ { [ ... ] | ALL } ] [ -p [ { | ALL } ] ]\n"), + VERSION, progname); + exit(1); +} + + +/* + *************************************************************************** + * SIGALRM signal handler + *************************************************************************** + */ +void alarm_handler(int sig) +{ + signal(SIGALRM, alarm_handler); + alarm(interval); +} + + +/* + *************************************************************************** + * Initialize stats common structures + *************************************************************************** + */ +void init_stats(void) +{ + memset(&comm_stats[0], 0, COMM_STATS_SIZE); + memset(&comm_stats[1], 0, COMM_STATS_SIZE); +} + + +/* + *************************************************************************** + * Set every disk_io entry to inactive state + *************************************************************************** + */ +void set_entries_inactive(int iodev_nr) +{ + int i; + struct io_hdr_stats *st_hdr_iodev_i; + + for (i = 0; i < iodev_nr; i++) { + st_hdr_iodev_i = st_hdr_iodev + i; + st_hdr_iodev_i->active = FALSE; + } +} + + +/* + *************************************************************************** + * Set structures's state to free for inactive entries + *************************************************************************** + */ +void free_inactive_entries(int iodev_nr) +{ + int i; + struct io_hdr_stats *st_hdr_iodev_i; + + for (i = 0; i < iodev_nr; i++) { + st_hdr_iodev_i = st_hdr_iodev + i; + if (!st_hdr_iodev_i->active) + st_hdr_iodev_i->major = 0; + } +} + + +/* + *************************************************************************** + * Allocate and init I/O devices structures + *************************************************************************** + */ +void salloc_device(int iodev_nr) +{ + int i; + struct io_hdr_stats *st_hdr_iodev_i; + + for (i = 0; i < 2; i++) { + if ((st_iodev[i] = (struct io_stats *) malloc(IO_STATS_SIZE * iodev_nr)) == NULL) { + perror("malloc"); + exit(4); + } + memset(st_iodev[i], 0, IO_STATS_SIZE * iodev_nr); + } + + if ((st_hdr_iodev = (struct io_hdr_stats *) malloc(IO_HDR_STATS_SIZE * iodev_nr)) == NULL) { + perror("malloc"); + exit(4); + } + memset(st_hdr_iodev, 0, IO_HDR_STATS_SIZE * iodev_nr); + + if (iodev_nr == 4) { + /* + * We may have an old kernel with the stats for the first four disks + * in /proc/stat: reset the devices name. Anyway, if we are wrong, + * the names will be read from disk_io entry in /proc/stat or from + * /sys. + */ + for (i = 0; i < 4; i++) { + st_hdr_iodev_i = st_hdr_iodev + i; + sprintf(st_hdr_iodev_i->name, "hdisk%d", i); + } + } +} + + +/* + *************************************************************************** + * Allocate structures for devices entered on the command line + *************************************************************************** + */ +void salloc_dev_list(int list_len) +{ + if ((st_dev_list = (struct io_dlist *) malloc(IO_DLIST_SIZE * list_len)) == NULL) { + perror("malloc"); + exit(4); + } + memset(st_dev_list, 0, IO_DLIST_SIZE * list_len); +} + + +/* + *************************************************************************** + * Look for the device in the device list + * and store it if necessary. + *************************************************************************** + */ +int update_dev_list(int *dlist_idx, char *device_name) +{ + int i; + struct io_dlist *st_dev_list_i; + + st_dev_list_i = st_dev_list; + + for (i = 0; i < *dlist_idx; i++) { + st_dev_list_i = st_dev_list + i; + if (!strcmp(st_dev_list_i->dev_name, device_name)) + break; + } + + if (i == *dlist_idx) { + (*dlist_idx)++; + st_dev_list_i = st_dev_list + i; + strncpy(st_dev_list_i->dev_name, device_name, MAX_NAME_LEN - 1); + } + + return i; +} + + +/* + *************************************************************************** + * Allocate and init structures, according to system state + *************************************************************************** + */ +void io_sys_init(int *flags) +{ + /* Init stat common counters */ + init_stats(); + + /* How many processors on this machine ? */ + get_cpu_nr(&cpu_nr, ~0); + + /* Get number of block devices and partitions in /proc/diskstats */ + if ((iodev_nr = get_diskstats_dev_nr(CNT_PART)) > 0) { + *flags |= F_HAS_DISKSTATS; + iodev_nr += NR_DEV_PREALLOC; + } + + if (!HAS_DISKSTATS(*flags) || + (DISPLAY_PARTITIONS(*flags) && !DISPLAY_PART_ALL(*flags))) { + /* + * If /proc/diskstats exists but we also want stats for the partitions + * of a particular device, stats will have to be found in /sys. So we + * need to know if /sys is mounted or not, and set *flags accordingly. + */ + + /* Get number of block devices (and partitions) in sysfs */ + if ((iodev_nr = get_sysfs_dev_nr(*flags)) > 0) { + *flags |= F_HAS_SYSFS; + iodev_nr += NR_DEV_PREALLOC; + } + /* Get number of "disk_io:" entries in /proc/stat */ + else if ((iodev_nr = get_disk_io_nr()) > 0) + iodev_nr += NR_DISK_PREALLOC; + else { + /* Assume we have an old kernel: stats for 4 disks are in /proc/stat */ + iodev_nr = 4; + *flags |= F_OLD_KERNEL; + } + } + /* Allocate structures for number of disks found */ + salloc_device(iodev_nr); +} + + +/* + *************************************************************************** + * Save stats for current device or partition + *************************************************************************** + */ +void save_dev_stats(char *dev_name, int curr, struct io_stats *sdev) +{ + int i; + struct io_hdr_stats *st_hdr_iodev_i; + struct io_stats *st_iodev_i; + + /* Look for device in data table */ + for (i = 0; i < iodev_nr; i++) { + st_hdr_iodev_i = st_hdr_iodev + i; + if (!strcmp(st_hdr_iodev_i->name, dev_name)) { + break; + } + } + + if (i == iodev_nr) { + /* + * This is a new device: look for an unused entry to store it. + * Thus we are able to handle dynamically registered devices. + */ + for (i = 0; i < iodev_nr; i++) { + st_hdr_iodev_i = st_hdr_iodev + i; + if (!st_hdr_iodev_i->major) { + /* Unused entry found... */ + st_hdr_iodev_i->major = 1; /* Just to indicate it is now used! */ + strcpy(st_hdr_iodev_i->name, dev_name); + st_iodev_i = st_iodev[!curr] + i; + memset(st_iodev_i, 0, IO_STATS_SIZE); + break; + } + } + } + if (i < iodev_nr) { + st_hdr_iodev_i = st_hdr_iodev + i; + st_hdr_iodev_i->active = TRUE; + st_iodev_i = st_iodev[curr] + i; + *st_iodev_i = *sdev; + } +} + + +/* + *************************************************************************** + * Read stats from /proc/stat file... + * (see linux source file linux/fs/proc/array.c) + * Useful at least for CPU utilization. + * May be useful to get disk stats if /sys not available. + *************************************************************************** + */ +void read_stat(int curr, int flags) +{ + FILE *statfp; + char line[8192]; + int pos, i; + unsigned int v_tmp[3], v_major, v_index; + struct io_stats *st_iodev_tmp[4], *st_iodev_i; + struct io_hdr_stats *st_hdr_iodev_i; + unsigned long cc_idle, cc_iowait; + unsigned int cc_user, cc_nice, cc_system, cc_hardirq, cc_softirq; + + + /* + * Prepare pointers on the 4 disk structures in case we have a + * /proc/stat file with "disk_rblk", etc. entries. + */ + for (i = 0; i < 4; i++) + st_iodev_tmp[i] = st_iodev[curr] + i; + + /* Open stat file */ + if ((statfp = fopen(STAT, "r")) == NULL) { + perror("fopen"); + exit(2); + } + + while (fgets(line, 8192, statfp) != NULL) { + + if (!strncmp(line, "cpu ", 4)) { + /* + * Read the number of jiffies spent in the different modes, + * and compute system uptime in jiffies (1/100ths of a second + * if HZ=100). + * Some fields are only presnt in 2.6 kernels. + */ + comm_stats[curr].cpu_iowait = 0; /* For pre 2.6 kernels */ + cc_hardirq = cc_softirq = 0; + sscanf(line + 5, "%u %u %u %lu %lu %u %u", + &(comm_stats[curr].cpu_user), &(comm_stats[curr].cpu_nice), + &(comm_stats[curr].cpu_system), &(comm_stats[curr].cpu_idle), + &(comm_stats[curr].cpu_iowait), &cc_hardirq, &cc_softirq); + + /* + * Time spent in system mode also includes time spent servicing + * interrupts and softirqs. + */ + comm_stats[curr].cpu_system += cc_hardirq + cc_softirq; + + /* + * Compute system uptime in jiffies. + * Uptime is multiplied by the number of processors. + */ + comm_stats[curr].uptime = comm_stats[curr].cpu_user + + comm_stats[curr].cpu_nice + + comm_stats[curr].cpu_system + + comm_stats[curr].cpu_idle + + comm_stats[curr].cpu_iowait; + } + + else if ((!strncmp(line, "cpu0", 4)) && cpu_nr) { + /* + * Read CPU line for proc#0 (if available). + * Useful to compute uptime reduced to one processor on SMP machines, + * with fewer risks to get an overflow... + */ + cc_iowait = cc_hardirq = cc_softirq = 0; + sscanf(line + 5, "%u %u %u %lu %lu %u %u", + &cc_user, &cc_nice, &cc_system, &cc_idle, &cc_iowait, + &cc_hardirq, &cc_softirq); + comm_stats[curr].uptime0 = cc_user + cc_nice + cc_system + + cc_idle + cc_iowait + + cc_hardirq + cc_softirq; + } + + else if (DISPLAY_EXTENDED(flags) || HAS_DISKSTATS(flags) || HAS_SYSFS(flags)) + /* + * When displaying extended statistics, or if /proc/diskstats exists or /sys is mounted, + * we just need to get CPU info from /proc/stat. + */ + continue; + + else if (!strncmp(line, "disk_rblk ", 10)) { + /* + * Read the number of blocks read from disk. + * A block is of indeterminate size. + * The size may vary depending on the device type. + */ + sscanf(line + 10, "%u %u %u %u", + &v_tmp[0], &v_tmp[1], &v_tmp[2], &v_tmp[3]); + + st_iodev_tmp[0]->dk_drive_rblk = v_tmp[0]; + st_iodev_tmp[1]->dk_drive_rblk = v_tmp[1]; + st_iodev_tmp[2]->dk_drive_rblk = v_tmp[2]; + st_iodev_tmp[3]->dk_drive_rblk = v_tmp[3]; + } + + else if (!strncmp(line, "disk_wblk ", 10)) { + /* Read the number of blocks written to disk */ + sscanf(line + 10, "%u %u %u %u", + &v_tmp[0], &v_tmp[1], &v_tmp[2], &v_tmp[3]); + + st_iodev_tmp[0]->dk_drive_wblk = v_tmp[0]; + st_iodev_tmp[1]->dk_drive_wblk = v_tmp[1]; + st_iodev_tmp[2]->dk_drive_wblk = v_tmp[2]; + st_iodev_tmp[3]->dk_drive_wblk = v_tmp[3]; + } + + else if (!strncmp(line, "disk ", 5)) { + /* Read the number of I/O done since the last reboot */ + sscanf(line + 5, "%u %u %u %u", + &v_tmp[0], &v_tmp[1], &v_tmp[2], &v_tmp[3]); + + st_iodev_tmp[0]->dk_drive = v_tmp[0]; + st_iodev_tmp[1]->dk_drive = v_tmp[1]; + st_iodev_tmp[2]->dk_drive = v_tmp[2]; + st_iodev_tmp[3]->dk_drive = v_tmp[3]; + } + + else if (!strncmp(line, "disk_io: ", 9)) { + pos = 9; + + /* Every disk_io entry is potentially unregistered */ + set_entries_inactive(iodev_nr); + + /* Read disks I/O statistics (for 2.4 kernels) */ + while (pos < strlen(line) - 1) { + /* Beware: a CR is already included in the line */ + sscanf(line + pos, "(%u,%u):(%u,%*u,%u,%*u,%u) ", + &v_major, &v_index, &v_tmp[0], &v_tmp[1], &v_tmp[2]); + + /* Look for disk entry */ + for (i = 0; i < iodev_nr; i++) { + st_hdr_iodev_i = st_hdr_iodev + i; + if ((st_hdr_iodev_i->major == v_major) && + (st_hdr_iodev_i->index == v_index)) + break; + } + + if (i == iodev_nr) { + /* + * New disk registered. Assume that disks may be registered, + * *and* unregistered dynamically... + * Look for a free structure to store it. + */ + for (i = 0; i < iodev_nr; i++) { + st_hdr_iodev_i = st_hdr_iodev + i; + if (!st_hdr_iodev_i->major) { + /* Free structure found! */ + st_hdr_iodev_i->major = v_major; + st_hdr_iodev_i->index = v_index; + sprintf(st_hdr_iodev_i->name, "dev%d-%d", v_major, v_index); + st_iodev_i = st_iodev[!curr] + i; + memset(st_iodev_i, 0, IO_STATS_SIZE); + break; + } + } + } + + if (i < iodev_nr) { + st_hdr_iodev_i = st_hdr_iodev + i; + st_hdr_iodev_i->active = TRUE; + st_iodev_i = st_iodev[curr] + i; + st_iodev_i->dk_drive = v_tmp[0]; + st_iodev_i->dk_drive_rblk = v_tmp[1]; + st_iodev_i->dk_drive_wblk = v_tmp[2]; + } + /* else the disk_io entry was not found, + * and there was no free structure to store it */ + + pos += strcspn(line + pos, " ") + 1; + } + + /* Free structures corresponding to unregistered disks */ + free_inactive_entries(iodev_nr); + } + } + + /* Close stat file */ + fclose(statfp); +} + + +/* + *************************************************************************** + * Read sysfs stat for current block device or partition + *************************************************************************** + */ +int read_sysfs_file_stat(int curr, char *filename, char *dev_name, + int dev_type) +{ + FILE *sysfp; + struct io_stats sdev; + int i; + + /* Try to read given stat file */ + if ((sysfp = fopen(filename, "r")) == NULL) + return 0; + + if (dev_type == DT_DEVICE) + i = (fscanf(sysfp, "%d %d %d %d %d %d %d %d %d %d %d", + &sdev.rd_ios, &sdev.rd_merges, + &sdev.rd_sectors, &sdev.rd_ticks, + &sdev.wr_ios, &sdev.wr_merges, + &sdev.wr_sectors, &sdev.wr_ticks, + &sdev.ios_pgr, &sdev.tot_ticks, &sdev.rq_ticks) == 11); + else + i = (fscanf(sysfp, "%d %d %d %d", + &sdev.rd_ios, &sdev.rd_sectors, + &sdev.wr_ios, &sdev.wr_sectors) == 4); + + if (i) + save_dev_stats(dev_name, curr, &sdev); + + fclose(sysfp); + + return 1; +} + + +/* + *************************************************************************** + * Read sysfs stats for all the partitions of a device + *************************************************************************** + */ +void read_sysfs_dlist_part_stat(int curr, char *dev_name) +{ + DIR *dir; + struct dirent *drd; + char dfile[MAX_PF_NAME], filename[MAX_PF_NAME]; + + sprintf(dfile, "%s/%s", SYSFS_BLOCK, dev_name); + + /* Open current device directory in /sys/block */ + if ((dir = opendir(dfile)) == NULL) + return; + + /* Get current entry */ + while ((drd = readdir(dir)) != NULL) { + if (!strcmp(drd->d_name, ".") || !strcmp(drd->d_name, "..")) + continue; + sprintf(filename, "%s/%s/%s", dfile, drd->d_name, S_STAT); + + /* Read current partition stats */ + read_sysfs_file_stat(curr, filename, drd->d_name, DT_PARTITION); + } + + /* Close device directory */ + (void) closedir(dir); +} + + +/* + *************************************************************************** + * Read stats from the sysfs filesystem + * for the devices entered on the command line + *************************************************************************** + */ +void read_sysfs_dlist_stat(int curr, int flags) +{ + int dev, ok; + char filename[MAX_PF_NAME]; + struct io_dlist *st_dev_list_i; + + /* Every I/O device (or partition) is potentially unregistered */ + set_entries_inactive(iodev_nr); + + for (dev = 0; dev < dlist_idx; dev++) { + st_dev_list_i = st_dev_list + dev; + sprintf(filename, "%s/%s/%s", + SYSFS_BLOCK, st_dev_list_i->dev_name, S_STAT); + + /* Read device stats */ + ok = read_sysfs_file_stat(curr, filename, st_dev_list_i->dev_name, DT_DEVICE); + + if (ok && st_dev_list_i->disp_part) + /* Also read stats for its partitions */ + read_sysfs_dlist_part_stat(curr, st_dev_list_i->dev_name); + } + + /* Free structures corresponding to unregistered devices */ + free_inactive_entries(iodev_nr); +} + + +/* + *************************************************************************** + * Read stats from the sysfs filesystem + * for every block devices found + *************************************************************************** + */ +void read_sysfs_stat(int curr, int flags) +{ + DIR *dir; + struct dirent *drd; + char filename[MAX_PF_NAME]; + int ok; + + /* Every I/O device entry is potentially unregistered */ + set_entries_inactive(iodev_nr); + + /* Open /sys/block directory */ + if ((dir = opendir(SYSFS_BLOCK)) != NULL) { + + /* Get current entry */ + while ((drd = readdir(dir)) != NULL) { + if (!strcmp(drd->d_name, ".") || !strcmp(drd->d_name, "..")) + continue; + sprintf(filename, "%s/%s/%s", SYSFS_BLOCK, drd->d_name, S_STAT); + + /* If current entry is a directory, try to read its stat file */ + ok = read_sysfs_file_stat(curr, filename, drd->d_name, DT_DEVICE); + + /* + * If '-p ALL' was entered on the command line, + * also try to read stats for its partitions + */ + if (ok && DISPLAY_PART_ALL(flags)) + read_sysfs_dlist_part_stat(curr, drd->d_name); + } + + /* Close /sys/block directory */ + (void) closedir(dir); + } + + /* Free structures corresponding to unregistered devices */ + free_inactive_entries(iodev_nr); +} + + +/* + *************************************************************************** + * Read stats from /proc/diskstats + *************************************************************************** + */ +void read_diskstats_stat(int curr, int flags) +{ + FILE *dstatsfp; + char line[256], dev_name[MAX_NAME_LEN]; + struct io_stats sdev; + int i; + int tmp[11]; + + /* Every I/O device entry is potentially unregistered */ + set_entries_inactive(iodev_nr); + + /* Open /proc/diskstats file */ + if ((dstatsfp = fopen(DISKSTATS, "r")) == NULL) + return; + + while (fgets(line, 256, dstatsfp) != NULL) { + + i = sscanf(line, "%*d %*d %s %d %d %d %d %d %d %d %d %d %d %d", + dev_name, + &tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5], + &tmp[6], &tmp[7], &tmp[8], &tmp[9], &tmp[10]); + + if (i == 12) { + /* Device */ + sdev.rd_ios = tmp[0]; sdev.rd_merges = tmp[1]; + sdev.rd_sectors = tmp[2]; sdev.rd_ticks = tmp[3]; + sdev.wr_ios = tmp[4]; sdev.wr_merges = tmp[5]; + sdev.wr_sectors = tmp[6]; sdev.wr_ticks = tmp[7]; + sdev.ios_pgr = tmp[8]; sdev.tot_ticks = tmp[9]; + sdev.rq_ticks = tmp[10]; + } + else if (i == 5) { + /* Partition */ + if (DISPLAY_EXTENDED(flags) || (!dlist_idx && !DISPLAY_PARTITIONS(flags))) + continue; + sdev.rd_ios = tmp[0]; sdev.rd_sectors = tmp[1]; + sdev.wr_ios = tmp[2]; sdev.wr_sectors = tmp[3]; + } + else + /* Unknown entry: ignore it */ + continue; + + save_dev_stats(dev_name, curr, &sdev); + } + + fclose(dstatsfp); + + /* Free structures corresponding to unregistered devices */ + free_inactive_entries(iodev_nr); +} + + +/* + *************************************************************************** + * Display CPU utilization + *************************************************************************** + */ +void write_cpu_stat(int curr, unsigned long itv) +{ + printf(_("avg-cpu: %%user %%nice %%sys %%iowait %%idle\n")); + + printf(" %6.2f %6.2f %6.2f %6.2f", + SP_VALUE(comm_stats[!curr].cpu_user, comm_stats[curr].cpu_user, itv), + SP_VALUE(comm_stats[!curr].cpu_nice, comm_stats[curr].cpu_nice, itv), + SP_VALUE(comm_stats[!curr].cpu_system, comm_stats[curr].cpu_system, itv), + SP_VALUE(comm_stats[!curr].cpu_iowait, comm_stats[curr].cpu_iowait, itv)); + + if (comm_stats[curr].cpu_idle < comm_stats[!curr].cpu_idle) + printf(" %.2f", 0.0); + else + printf(" %6.2f", + SP_VALUE(comm_stats[!curr].cpu_idle, comm_stats[curr].cpu_idle, itv)); + + printf("\n\n"); +} + + +/* + *************************************************************************** + * Display extended stats (those read from /proc/diskstats or /sys) + *************************************************************************** + */ +void write_ext_stat(int curr, unsigned long itv, int flags) +{ + int dev, i; + struct io_stats sdev; + struct io_hdr_stats *st_hdr_iodev_i; + struct io_stats *st_iodev_i, *st_iodev_j; + struct io_dlist *st_dev_list_i; + double tput, util, await, svctm, arqsz, nr_ios; + + printf(_("Device: rrqm/s wrqm/s r/s w/s rsec/s wsec/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %%util\n")); + /* "xxxxxxxxxx 999.99 999.99 99.99 99.99 9999.99 9999.99 99999.99 99999.99 99999.99 99999.99 9999.99 999.99 %999.99\n" */ + + for (i = 0; i < iodev_nr; i++) { + st_hdr_iodev_i = st_hdr_iodev + i; + if (st_hdr_iodev_i->major) { + + if (HAS_DISKSTATS(flags) && dlist_idx) { + /* + * With sysfs, only stats for the requested devices are read. + * With /proc/diskstats, stats for every devices are read. + * Thus we need to check if stats for current device are to + * be displayed. + */ + for (dev = 0; dev < dlist_idx; dev++) { + st_dev_list_i = st_dev_list + dev; + if (!strcmp(st_hdr_iodev_i->name, st_dev_list_i->dev_name)) + break; + } + if (dev == dlist_idx) + /* Device not found in list: don't display it */ + continue; + } + + st_iodev_i = st_iodev[curr] + i; + st_iodev_j = st_iodev[!curr] + i; + + if (!DISPLAY_UNFILTERED(flags)) { + if (!st_iodev_i->rd_ios && !st_iodev_i->wr_ios) + continue; + } + + sdev.rd_ios = st_iodev_i->rd_ios - st_iodev_j->rd_ios; + sdev.wr_ios = st_iodev_i->wr_ios - st_iodev_j->wr_ios; + sdev.rd_ticks = st_iodev_i->rd_ticks - st_iodev_j->rd_ticks; + sdev.wr_ticks = st_iodev_i->wr_ticks - st_iodev_j->wr_ticks; + sdev.rd_merges = st_iodev_i->rd_merges - st_iodev_j->rd_merges; + sdev.wr_merges = st_iodev_i->wr_merges - st_iodev_j->wr_merges; + sdev.rd_sectors = st_iodev_i->rd_sectors - st_iodev_j->rd_sectors; + sdev.wr_sectors = st_iodev_i->wr_sectors - st_iodev_j->wr_sectors; + sdev.tot_ticks = st_iodev_i->tot_ticks - st_iodev_j->tot_ticks; + sdev.rq_ticks = st_iodev_i->rq_ticks - st_iodev_j->rq_ticks; + + nr_ios = sdev.rd_ios + sdev.wr_ios; + tput = nr_ios * HZ / itv; + util = ((double) sdev.tot_ticks) / itv * HZ; + svctm = tput ? util / tput : 0.0; + /* + * kernel gives ticks already in milliseconds for all platforms + * => no need for further scaling. + */ + await = nr_ios ? + (sdev.rd_ticks + sdev.wr_ticks) / nr_ios : 0.0; + arqsz = nr_ios ? + (sdev.rd_sectors + sdev.wr_sectors) / nr_ios : 0.0; + + printf("%-10s", st_hdr_iodev_i->name); + if (strlen(st_hdr_iodev_i->name) > 10) + printf("\n "); + /* rrq/s wrq/s r/s w/s rsec wsec rkB wkB rqsz qusz await svctm %util */ + printf(" %6.2f %6.2f %5.2f %5.2f %7.2f %7.2f %8.2f %8.2f %8.2f %8.2f %7.2f %6.2f %6.2f\n", + ((double) sdev.rd_merges) / itv * HZ, + ((double) sdev.wr_merges) / itv * HZ, + ((double) sdev.rd_ios) / itv * HZ, + ((double) sdev.wr_ios) / itv * HZ, + ((double) sdev.rd_sectors) / itv * HZ, + ((double) sdev.wr_sectors) / itv * HZ, + ((double) sdev.rd_sectors) / itv * HZ / 2, + ((double) sdev.wr_sectors) / itv * HZ / 2, + arqsz, + ((double) sdev.rq_ticks) / itv * HZ / 1000.0, + await, + /* The ticks output is biased to output 1000 ticks per second */ + svctm, + /* Again: ticks in milliseconds */ + util / 10.0); + } + } +} + + +/* + *************************************************************************** + * Write basic stats, read from /proc/stat file or from sysfs + *************************************************************************** + */ +void write_basic_stat(int curr, unsigned long itv, int flags) +{ + int fctr = 1; + int i, j; + struct io_hdr_stats *st_hdr_iodev_i; + struct io_stats *st_iodev_i, *st_iodev_j; + struct io_dlist *st_dev_list_j; + + if (DISPLAY_KILOBYTES(flags)) { + printf(_("Device: tps kB_read/s kB_wrtn/s kB_read kB_wrtn\n")); + fctr = 2; + } + else + printf(_("Device: tps Blk_read/s Blk_wrtn/s Blk_read Blk_wrtn\n")); + + for (i = 0; i < iodev_nr; i++) { + st_hdr_iodev_i = st_hdr_iodev + i; + if (st_hdr_iodev_i->major || HAS_OLD_KERNEL(flags)) { + + if (dlist_idx && !HAS_SYSFS(flags)) { + /* + * If devices have been entered on the command line, display the + * stats only for them. + * No problem if sysfs is mounted, since in this case only the + * requested devices have been read... + */ + for (j = 0; j < dlist_idx; j++) { + st_dev_list_j = st_dev_list + j; + if (!strcmp(st_hdr_iodev_i->name, st_dev_list_j->dev_name)) + break; + } + if (j == dlist_idx) + /* Device not found in list: skip it */ + continue; + } + + st_iodev_i = st_iodev[curr] + i; + st_iodev_j = st_iodev[!curr] + i; + + if (!DISPLAY_UNFILTERED(flags)) { + if (HAS_SYSFS(flags) || HAS_DISKSTATS(flags)) { + if (!st_iodev_i->rd_ios && !st_iodev_i->wr_ios) + continue; + } + else if (!st_iodev_i->dk_drive) + continue; + } + + printf("%-13s", st_hdr_iodev_i->name); + if (strlen(st_hdr_iodev_i->name) > 13) + printf("\n "); + + if (HAS_SYSFS(flags) || HAS_DISKSTATS(flags)) { + /* Print stats coming from /sys or /proc/diskstats */ + printf(" %8.2f %12.2f %12.2f %10u %10u\n", + S_VALUE(st_iodev_j->rd_ios + st_iodev_j->wr_ios, + st_iodev_i->rd_ios + st_iodev_i->wr_ios, itv), + S_VALUE(st_iodev_j->rd_sectors, + st_iodev_i->rd_sectors, itv) / fctr, + S_VALUE(st_iodev_j->wr_sectors, + st_iodev_i->wr_sectors, itv) / fctr, + (st_iodev_i->rd_sectors - + st_iodev_j->rd_sectors) / fctr, + (st_iodev_i->wr_sectors - + st_iodev_j->wr_sectors) / fctr); + } + else { + /* Print stats coming from /proc/stat */ + printf(" %8.2f %12.2f %12.2f %10u %10u\n", + S_VALUE(st_iodev_j->dk_drive, + st_iodev_i->dk_drive, itv), + S_VALUE(st_iodev_j->dk_drive_rblk, + st_iodev_i->dk_drive_rblk, itv) / fctr, + S_VALUE(st_iodev_j->dk_drive_wblk, + st_iodev_i->dk_drive_wblk, itv) / fctr, + (st_iodev_i->dk_drive_rblk - + st_iodev_j->dk_drive_rblk) / fctr, + (st_iodev_i->dk_drive_wblk - + st_iodev_j->dk_drive_wblk) / fctr); + } + } + } +} + + +/* + *************************************************************************** + * Print everything now (stats and uptime) + *************************************************************************** + */ +int write_stat(int curr, int flags, struct tm *loc_time) +{ + unsigned long itv; + + /* + * Under very special circumstances, STDOUT may become unavailable, + * This is what we try to guess here + */ + if (write(STDOUT_FILENO, "", 0) == -1) { + perror("stdout"); + exit(6); + } + + /* Print time stamp */ + if (DISPLAY_TIMESTAMP(flags)) { + strftime(timestamp, sizeof(timestamp), "%X ", loc_time); + printf(_("Time: %s\n"), timestamp); + } + + /* + * itv is multiplied by the number of processors. + * This is OK to compute CPU usage since the number of jiffies spent in the + * different modes (user, nice, etc.) is the sum of all the processors. + * But itv should be reduced to one processor before displaying disk + * utilization. + */ + itv = comm_stats[curr].uptime - comm_stats[!curr].uptime; /* uptime in jiffies */ + if (!itv) + itv = 1; + + if (!DISPLAY_DISK_ONLY(flags)) + /* Display CPU utilization */ + write_cpu_stat(curr, itv); + + if (cpu_nr) { + /* On SMP machines, reduce itv to one processor (see note above) */ + itv = comm_stats[curr].uptime0 - comm_stats[!curr].uptime0; + if (!itv) + itv = 1; + } + + if (!DISPLAY_CPU_ONLY(flags)) { + + if (DISPLAY_EXTENDED(flags)) + /* Write extended stats, read from /proc/diskstats or /sys */ + write_ext_stat(curr, itv, flags); + else + /* Write basic stats, read from /proc/stat, /proc/diskstats or /sys */ + write_basic_stat(curr, itv, flags); + + printf("\n"); + } + return 1; +} + + +/* + *************************************************************************** + * Main loop: read I/O stats from the relevant sources, + * and display them. + *************************************************************************** + */ +void rw_io_stat_loop(int flags, long int count, struct tm *loc_time) +{ + int curr = 1; + int next; + + do { + /* Read kernel statistics (CPU, and possibly disks for old kernels) */ + read_stat(curr, flags); + + if (dlist_idx) { + /* + * A device or partition name was entered on the command line, + * with or without -p option (but not -p ALL). + */ + if (HAS_DISKSTATS(flags) && !DISPLAY_PARTITIONS(flags)) + read_diskstats_stat(curr, flags); + else if (HAS_SYSFS(flags)) + read_sysfs_dlist_stat(curr, flags); + } + else { + /* + * No devices nor partitions entered on the command line + * (for example if -p ALL was used). + */ + if (HAS_DISKSTATS(flags)) + read_diskstats_stat(curr, flags); + else if (HAS_SYSFS(flags)) + read_sysfs_stat(curr,flags); + } + + /* Save time */ + get_localtime(loc_time); + + /* Print results */ + if ((next = write_stat(curr, flags, loc_time)) + && (count > 0)) + count--; + fflush(stdout); + + if (count) { + pause(); + + if (next) + curr ^= 1; + } + } + while (count); +} + + +/* + *************************************************************************** + * Main entry to the iostat program + *************************************************************************** + */ +int main(int argc, char **argv) +{ + int it = 0, flags = 0; + int opt = 1; + int i; + long count = 1; + struct utsname header; + struct io_dlist *st_dev_list_i; + struct tm loc_time; + +#ifdef USE_NLS + /* Init National Language Support */ + init_nls(); +#endif + + /* Allocate structures for device list */ + if (argc > 1) + salloc_dev_list(argc - 1); + + /* Process args... */ + while (opt < argc) { + + if (!strcmp(argv[opt], "-p")) { + flags |= D_PARTITIONS; + if (argv[++opt] && (strspn(argv[opt], DIGITS) != strlen(argv[opt])) && + (strncmp(argv[opt], "-", 1))) { + flags |= D_UNFILTERED; + if (!strcmp(argv[opt], K_ALL)) { + flags |= D_PART_ALL; + opt++; + } + else { + /* Store device name */ + i = update_dev_list(&dlist_idx, device_name(argv[opt++])); + st_dev_list_i = st_dev_list + i; + st_dev_list_i->disp_part = TRUE; + } + } + else + flags |= D_PART_ALL; + } + + else if (!strncmp(argv[opt], "-", 1)) { + for (i = 1; *(argv[opt] + i); i++) { + + switch (*(argv[opt] + i)) { + + case 'c': + flags |= D_CPU_ONLY; /* Display cpu usage only */ + flags &= ~D_DISK_ONLY; + break; + + case 'd': + flags |= D_DISK_ONLY; /* Display disk utilization only */ + flags &= ~D_CPU_ONLY; + break; + + case 'k': + flags |= D_KILOBYTES; /* Display stats in kB/s */ + break; + + case 't': + flags |= D_TIMESTAMP; /* Display timestamp */ + break; + + case 'x': + flags |= D_EXTENDED; /* Display extended stats */ + break; + + case 'V': /* Print usage and exit */ + default: + usage(argv[0]); + } + } + opt++; + } + + else if (!isdigit(argv[opt][0])) { + flags |= D_UNFILTERED; + if (strcmp(argv[opt], K_ALL)) + /* Store device name */ + update_dev_list(&dlist_idx, device_name(argv[opt++])); + else + opt++; + } + + else if (!it) { + interval = atol(argv[opt++]); + if (interval < 1) + usage(argv[0]); + count = -1; + it = 1; + } + + else { + count = atol(argv[opt++]); + if (count < 1) + usage(argv[0]); + } + } + + /* Linux does not provide extended stats for partitions */ + if (DISPLAY_PARTITIONS(flags) && DISPLAY_EXTENDED(flags)) { + fprintf(stderr, _("-x and -p options are mutually exclusive\n")); + exit(1); + } + + /* Ignore device list if '-p ALL' entered on the command line */ + if (DISPLAY_PART_ALL(flags)) + dlist_idx = 0; + + /* Init structures according to machine architecture */ + io_sys_init(&flags); + + get_localtime(&loc_time); + + /* Get system name, release number and hostname */ + uname(&header); + print_gal_header(&loc_time, + header.sysname, header.release, header.nodename); + printf("\n"); + + /* Set a handler for SIGALRM */ + alarm_handler(0); + + /* Main loop */ + rw_io_stat_loop(flags, count, &loc_time); + + return 0; +} diff --git a/targets/znews1-d/system/probes/iostat.h b/targets/znews1-d/system/probes/iostat.h index 14abd66ec..644e9af0a 100644 --- a/targets/znews1-d/system/probes/iostat.h +++ b/targets/znews1-d/system/probes/iostat.h @@ -1,116 +1,116 @@ -/* - * iostat: report CPU and I/O statistics - * (C) 1999-2004 by Sebastien Godard - */ - -#ifndef _IOSTAT_H -#define _IOSTAT_H - -#include "common.h" - -#define MAX_NAME_LEN 72 - -#define D_CPU_ONLY 0x001 -#define D_DISK_ONLY 0x002 -#define D_TIMESTAMP 0x004 -#define D_EXTENDED 0x008 -#define D_PART_ALL 0x010 -#define D_KILOBYTES 0x020 -#define F_HAS_SYSFS 0x040 -#define F_OLD_KERNEL 0x080 -#define D_UNFILTERED 0x100 -/* 0x100000:0x800000 -> reserved (cf. common.h) */ - -#define DISPLAY_CPU_ONLY(m) (((m) & D_CPU_ONLY) == D_CPU_ONLY) -#define DISPLAY_DISK_ONLY(m) (((m) & D_DISK_ONLY) == D_DISK_ONLY) -#define DISPLAY_TIMESTAMP(m) (((m) & D_TIMESTAMP) == D_TIMESTAMP) -#define DISPLAY_EXTENDED(m) (((m) & D_EXTENDED) == D_EXTENDED) -#define DISPLAY_PART_ALL(m) (((m) & D_PART_ALL) == D_PART_ALL) -#define DISPLAY_KILOBYTES(m) (((m) & D_KILOBYTES) == D_KILOBYTES) -#define HAS_SYSFS(m) (((m) & F_HAS_SYSFS) == F_HAS_SYSFS) -#define HAS_OLD_KERNEL(m) (((m) & F_OLD_KERNEL) == F_OLD_KERNEL) -#define DISPLAY_UNFILTERED(m) (((m) & D_UNFILTERED) == D_UNFILTERED) - -#define DT_DEVICE 0 -#define DT_PARTITION 1 - - -struct comm_stats { - unsigned long uptime; - unsigned long uptime0; - unsigned long cpu_iowait; - unsigned long cpu_idle; - unsigned int cpu_user; - unsigned int cpu_nice; - unsigned int cpu_system; -}; - -#define COMM_STATS_SIZE (sizeof(struct comm_stats)) - -/* - * Structures for I/O stats. - * The number of structures allocated corresponds to the number of devices - * present in the system, plus a preallocation number to handle those - * that can be registered dynamically. - * The number of devices is found by using /sys filesystem (if mounted), - * or the number of "disk_io:" entries in /proc/stat (2.4 kernels), - * else the default value is 4 (for old kernels, which maintained stats - * for the first four devices in /proc/stat). - * For each io_stats structure allocated corresponds a io_hdr_stats structure. - * A io_stats structure is considered as unused or "free" (containing no stats - * for a particular device) if the 'major' field of the io_hdr_stats - * structure is set to 0. - */ -struct io_stats { - /* # of read operations issued to the device */ - unsigned int rd_ios __attribute__ ((aligned (8))); - /* # of read requests merged */ - unsigned int rd_merges __attribute__ ((packed)); - /* # of sectors read */ - unsigned int rd_sectors __attribute__ ((packed)); - /* Time of read requests in queue */ - unsigned int rd_ticks __attribute__ ((packed)); - /* # of write operations issued to the device */ - unsigned int wr_ios __attribute__ ((packed)); - /* # of write requests merged */ - unsigned int wr_merges __attribute__ ((packed)); - /* # of sectors written */ - unsigned int wr_sectors __attribute__ ((packed)); - /* Time of write requests in queue */ - unsigned int wr_ticks __attribute__ ((packed)); - /* # of I/Os in progress */ - unsigned int ios_pgr __attribute__ ((packed)); - /* # of ticks total (for this device) for I/O */ - unsigned int tot_ticks __attribute__ ((packed)); - /* # of ticks requests spent in queue */ - unsigned int rq_ticks __attribute__ ((packed)); - /* # of I/O done since last reboot */ - unsigned int dk_drive __attribute__ ((packed)); - /* # of blocks read */ - unsigned int dk_drive_rblk __attribute__ ((packed)); - /* # of blocks written */ - unsigned int dk_drive_wblk __attribute__ ((packed)); -}; - -#define IO_STATS_SIZE (sizeof(struct io_stats)) - -struct io_hdr_stats { - unsigned int active __attribute__ ((aligned (8))); - unsigned int major __attribute__ ((packed)); - unsigned int index __attribute__ ((packed)); - char name[MAX_NAME_LEN] __attribute__ ((packed)); -}; - -#define IO_HDR_STATS_SIZE (sizeof(struct io_hdr_stats)) - -/* List of devices entered on the command line */ -struct io_dlist { - /* Indicate whether its partitions are to be displayed or not */ - int disp_part __attribute__ ((aligned (8))); - /* Device name */ - char dev_name[MAX_NAME_LEN] __attribute__ ((packed)); -}; - -#define IO_DLIST_SIZE (sizeof(struct io_dlist)) - -#endif /* _IOSTAT_H */ +/* + * iostat: report CPU and I/O statistics + * (C) 1999-2004 by Sebastien Godard + */ + +#ifndef _IOSTAT_H +#define _IOSTAT_H + +#include "common.h" + +#define MAX_NAME_LEN 72 + +#define D_CPU_ONLY 0x001 +#define D_DISK_ONLY 0x002 +#define D_TIMESTAMP 0x004 +#define D_EXTENDED 0x008 +#define D_PART_ALL 0x010 +#define D_KILOBYTES 0x020 +#define F_HAS_SYSFS 0x040 +#define F_OLD_KERNEL 0x080 +#define D_UNFILTERED 0x100 +/* 0x100000:0x800000 -> reserved (cf. common.h) */ + +#define DISPLAY_CPU_ONLY(m) (((m) & D_CPU_ONLY) == D_CPU_ONLY) +#define DISPLAY_DISK_ONLY(m) (((m) & D_DISK_ONLY) == D_DISK_ONLY) +#define DISPLAY_TIMESTAMP(m) (((m) & D_TIMESTAMP) == D_TIMESTAMP) +#define DISPLAY_EXTENDED(m) (((m) & D_EXTENDED) == D_EXTENDED) +#define DISPLAY_PART_ALL(m) (((m) & D_PART_ALL) == D_PART_ALL) +#define DISPLAY_KILOBYTES(m) (((m) & D_KILOBYTES) == D_KILOBYTES) +#define HAS_SYSFS(m) (((m) & F_HAS_SYSFS) == F_HAS_SYSFS) +#define HAS_OLD_KERNEL(m) (((m) & F_OLD_KERNEL) == F_OLD_KERNEL) +#define DISPLAY_UNFILTERED(m) (((m) & D_UNFILTERED) == D_UNFILTERED) + +#define DT_DEVICE 0 +#define DT_PARTITION 1 + + +struct comm_stats { + unsigned long uptime; + unsigned long uptime0; + unsigned long cpu_iowait; + unsigned long cpu_idle; + unsigned int cpu_user; + unsigned int cpu_nice; + unsigned int cpu_system; +}; + +#define COMM_STATS_SIZE (sizeof(struct comm_stats)) + +/* + * Structures for I/O stats. + * The number of structures allocated corresponds to the number of devices + * present in the system, plus a preallocation number to handle those + * that can be registered dynamically. + * The number of devices is found by using /sys filesystem (if mounted), + * or the number of "disk_io:" entries in /proc/stat (2.4 kernels), + * else the default value is 4 (for old kernels, which maintained stats + * for the first four devices in /proc/stat). + * For each io_stats structure allocated corresponds a io_hdr_stats structure. + * A io_stats structure is considered as unused or "free" (containing no stats + * for a particular device) if the 'major' field of the io_hdr_stats + * structure is set to 0. + */ +struct io_stats { + /* # of read operations issued to the device */ + unsigned int rd_ios __attribute__ ((aligned (8))); + /* # of read requests merged */ + unsigned int rd_merges __attribute__ ((packed)); + /* # of sectors read */ + unsigned int rd_sectors __attribute__ ((packed)); + /* Time of read requests in queue */ + unsigned int rd_ticks __attribute__ ((packed)); + /* # of write operations issued to the device */ + unsigned int wr_ios __attribute__ ((packed)); + /* # of write requests merged */ + unsigned int wr_merges __attribute__ ((packed)); + /* # of sectors written */ + unsigned int wr_sectors __attribute__ ((packed)); + /* Time of write requests in queue */ + unsigned int wr_ticks __attribute__ ((packed)); + /* # of I/Os in progress */ + unsigned int ios_pgr __attribute__ ((packed)); + /* # of ticks total (for this device) for I/O */ + unsigned int tot_ticks __attribute__ ((packed)); + /* # of ticks requests spent in queue */ + unsigned int rq_ticks __attribute__ ((packed)); + /* # of I/O done since last reboot */ + unsigned int dk_drive __attribute__ ((packed)); + /* # of blocks read */ + unsigned int dk_drive_rblk __attribute__ ((packed)); + /* # of blocks written */ + unsigned int dk_drive_wblk __attribute__ ((packed)); +}; + +#define IO_STATS_SIZE (sizeof(struct io_stats)) + +struct io_hdr_stats { + unsigned int active __attribute__ ((aligned (8))); + unsigned int major __attribute__ ((packed)); + unsigned int index __attribute__ ((packed)); + char name[MAX_NAME_LEN] __attribute__ ((packed)); +}; + +#define IO_HDR_STATS_SIZE (sizeof(struct io_hdr_stats)) + +/* List of devices entered on the command line */ +struct io_dlist { + /* Indicate whether its partitions are to be displayed or not */ + int disp_part __attribute__ ((aligned (8))); + /* Device name */ + char dev_name[MAX_NAME_LEN] __attribute__ ((packed)); +}; + +#define IO_DLIST_SIZE (sizeof(struct io_dlist)) + +#endif /* _IOSTAT_H */ diff --git a/targets/znews1-d/system/probes/loadProbe.pl b/targets/znews1-d/system/probes/loadProbe.pl index 7f2e12dc8..3b648fd9c 100644 --- a/targets/znews1-d/system/probes/loadProbe.pl +++ b/targets/znews1-d/system/probes/loadProbe.pl @@ -1,101 +1,101 @@ -#!/usr/bin/perl -w - -use lib "."; -use strict; -use Getopt::Std; -use Time::HiRes qw(usleep); -use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate - register announce deregister); - -############################# -# Probe Defining Attributes -############################# -my $ALIAS = "load"; -my $NAME = "LoadProbe"; -my $DELAY = 2500; -############################# - - -sub usage() { - print STDERR << "EOF"; - -This program dumps current CPU usage to the Probe Relay file or socket - - usage: $0 [option] -o file|-k - - -h : this (help) message - -d delay : in milliseconds, the delay between each update [$DELAY] - -k : indicate to use socket to relay updates - -o file : file to which to output periodic CPU usage info - -s : be silent, no period info to stdout - -EOF - exit; -} - -sub cpuTime () { - my ($user, $nice, $sys, $idle, $iowait); - - local(*FIN); - open(FIN, ") { - chomp; - if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(\s+(\d+))?/o) { - ($user, $nice, $sys, $idle, $iowait) = ($1, $2, $3, $4, $6); - if (!defined($iowait)) { - $iowait = 0; - } - last; - } - } - close(FIN); - return ($user, $nice, $sys, $idle, $iowait); -} - -# get options -my %opts; -getopts('hkso:d:', \%opts) or usage(); -usage() if ($opts{h} || (!$opts{o} && !$opts{k})); - -my($fout, $sock); -if ($opts{o}) { - $fout = openFile($opts{o}); -} -if ($opts{k}) { - $sock = openSocket(); -} - -my $delay = $DELAY; -if ($opts{d}) { - $delay = $opts{d}; -} -$delay *= 1000; - -my $doPrint = 1; -if ($opts{s}) { - $doPrint = 0; -} - -# save current cpu ticks -my($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = cpuTime(); - -register($ALIAS, $NAME, location(), [$sock,$fout]); - -while (!shouldTerminate($sock)) { - usleep($delay); - # retrieve new cpu ticks - my ($userN, $niceN, $sysN, $idleN, $iowaitN) = cpuTime(); - # compute delta cpu ticks - my ($user, $nice, $sys, $idle, $iowait) = - ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv, $iowaitN - $iowaitSv); - # store the new saved ticks - ($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = ($userN, $niceN, $sysN, $idleN, $iowaitN); - my $total = $user + $nice + $sys + $idle + $iowait; - my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), - $user/$total, $nice/$total, $sys/$total, $idle/$total, $iowait/$total); - print $rpt if ($doPrint); - announce($ALIAS, $rpt, [$sock,$fout]); -} - -deregister($ALIAS, [$sock,$fout]); -cleanup($sock, [$fout]); +#!/usr/bin/perl -w + +use lib "."; +use strict; +use Getopt::Std; +use Time::HiRes qw(usleep); +use Rainbow::Probe qw(location openFile openSocket cleanup shouldTerminate + register announce deregister); + +############################# +# Probe Defining Attributes +############################# +my $ALIAS = "load"; +my $NAME = "LoadProbe"; +my $DELAY = 2500; +############################# + + +sub usage() { + print STDERR << "EOF"; + +This program dumps current CPU usage to the Probe Relay file or socket + + usage: $0 [option] -o file|-k + + -h : this (help) message + -d delay : in milliseconds, the delay between each update [$DELAY] + -k : indicate to use socket to relay updates + -o file : file to which to output periodic CPU usage info + -s : be silent, no period info to stdout + +EOF + exit; +} + +sub cpuTime () { + my ($user, $nice, $sys, $idle, $iowait); + + local(*FIN); + open(FIN, ") { + chomp; + if (/^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(\s+(\d+))?/o) { + ($user, $nice, $sys, $idle, $iowait) = ($1, $2, $3, $4, $6); + if (!defined($iowait)) { + $iowait = 0; + } + last; + } + } + close(FIN); + return ($user, $nice, $sys, $idle, $iowait); +} + +# get options +my %opts; +getopts('hkso:d:', \%opts) or usage(); +usage() if ($opts{h} || (!$opts{o} && !$opts{k})); + +my($fout, $sock); +if ($opts{o}) { + $fout = openFile($opts{o}); +} +if ($opts{k}) { + $sock = openSocket(); +} + +my $delay = $DELAY; +if ($opts{d}) { + $delay = $opts{d}; +} +$delay *= 1000; + +my $doPrint = 1; +if ($opts{s}) { + $doPrint = 0; +} + +# save current cpu ticks +my($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = cpuTime(); + +register($ALIAS, $NAME, location(), [$sock,$fout]); + +while (!shouldTerminate($sock)) { + usleep($delay); + # retrieve new cpu ticks + my ($userN, $niceN, $sysN, $idleN, $iowaitN) = cpuTime(); + # compute delta cpu ticks + my ($user, $nice, $sys, $idle, $iowait) = + ($userN - $userSv, $niceN - $niceSv, $sysN - $sysSv, $idleN - $idleSv, $iowaitN - $iowaitSv); + # store the new saved ticks + ($userSv, $niceSv, $sysSv, $idleSv, $iowaitSv) = ($userN, $niceN, $sysN, $idleN, $iowaitN); + my $total = $user + $nice + $sys + $idle + $iowait; + my $rpt = sprintf("[%s] %9.7f %9.7f %9.7f %9.7f %9.7f\n", "".localtime(), + $user/$total, $nice/$total, $sys/$total, $idle/$total, $iowait/$total); + print $rpt if ($doPrint); + announce($ALIAS, $rpt, [$sock,$fout]); +} + +deregister($ALIAS, [$sock,$fout]); +cleanup($sock, [$fout]); diff --git a/targets/znews1-d/system/probes/runApachetop.pl b/targets/znews1-d/system/probes/runApachetop.pl index 2d9a80a4d..741ee43f6 100644 --- a/targets/znews1-d/system/probes/runApachetop.pl +++ b/targets/znews1-d/system/probes/runApachetop.pl @@ -1,16 +1,16 @@ -#!/usr/bin/perl -w - -use strict; - -############################# -my $APACHE_LOG = "/var/log/apache2/access-delegate.log"; -my $APACHETOP_LOG = "../../log/apachetop.log"; -my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; -############################# - -if (! -e $APACHETOP_LOG) { - open(FOUT, ">> $APACHETOP_LOG"); - close(FOUT); -} -exec($APACHETOP_EXEC) - || die "exec $APACHETOP_EXEC failed: $! $?"; +#!/usr/bin/perl -w + +use strict; + +############################# +my $APACHE_LOG = "/var/log/apache2/access-delegate.log"; +my $APACHETOP_LOG = "../../log/apachetop.log"; +my $APACHETOP_EXEC = "./apachetop -f $APACHE_LOG -o $APACHETOP_LOG"; +############################# + +if (! -e $APACHETOP_LOG) { + open(FOUT, ">> $APACHETOP_LOG"); + close(FOUT); +} +exec($APACHETOP_EXEC) + || die "exec $APACHETOP_EXEC failed: $! $?"; diff --git a/targets/znews1-d/system/webpages/www1/index.html b/targets/znews1-d/system/webpages/www1/index.html index 050159b89..4ec9f5304 100644 --- a/targets/znews1-d/system/webpages/www1/index.html +++ b/targets/znews1-d/system/webpages/www1/index.html @@ -1,46 +1,46 @@ - - -Somewhere Over the Rainbow - - -

Z.com News - Hello World! (Low-fidelity Settings)

- -We apologize for this text-only content, as we are currently swamped with visitors. Thank you for your patience as we work hard to serve your requests. (This file is a little over 3 KB.) -

-SYDNEY, Australia (Reuters) -- In death as in life, iconic TV naturalist Steve Irwin captivated millions worldwide and clogged the Internet as fans from Guam to Glasgow reacted with disbelief to news "The Crocodile Hunter" was dead. -

-Some Web sites groaned to a halt within hours of the first reports Monday that Irwin had been killed by a stingray's barb through his chest in a freak diving accident off Australia's northeast coast. -

-Web measurement company Hitwise said Irwin's death was the biggest news event read by Australians on the Internet since two Australian miners were trapped by a mine collapse in southern Tasmania state in late April. -

-"We noticed that the Web site www.crocodilehunter.com increased in popularity quite substantially. It became the number one entertainment personality Web site in Australia yesterday and in the United States it also became the third most popular," Hitwise Asia-Pacific marketing director James Borg told Reuters. -

-Australian news Web sites struggled to keep up with demand. -

-The Australian Broadcasting Corp.'s site (www.abc.com.au) had to temporarily shut down, posting a notice Monday that it was experiencing higher than normal traffic. -

-It resumed soon after in a low-bandwidth format to cope with hundreds of thousands of hits. -

-Newspaper Web sites also wobbled but kept up with demand. -

-A spokesman for The Sydney Morning Herald's site, www.smh.com.au, said it had experienced a "huge" 40 percent spike in page impressions compared with the previous week's average weekday number of about 500,000. -

-There was also a 70 percent jump in visitors to its pages, the spokesman said. -

-That pattern was mirrored around the world, with Irwin's death leading major news Web sites such as CNN.com and U.S. and British newspaper Web sites, as well as swamping their most viewed and most emailed categories. -

-Web logs and Internet feedback pages were also awash with postings from shocked readers from around the world, many of them from Americans charmed by Irwin's quirky style and his typically Australian catchphrase of "crikey." -

-Irwin first found fame in the United States before his "Crocodile Hunter" documentaries on U.S.-based television company Discovery Communications' Animal Planet attracted a global audience of 200 million -- 10 times Australia's population. -

-"Crikey!, I miss him so much," Tina Treece from Pittsburgh, Pennsylvania, posted on CNN.com's feedback page CNN Exchange. -

-The site had contributions from readers in Guam, Romania, Thailand, France, Scotland, India, New Zealand, Canada, Brunei, Britain, Malaysia, Denmark and the Netherlands. -

-Many faced the problem of explaining to their children how one of their favorite TV characters had died. -

-"Why did it have to be Steve Irwin?" 11-year-old Daniel told Australian Associated Press. -

-Copyright 2006 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed. - - + + +Somewhere Over the Rainbow + + +

Z.com News - Hello World! (Low-fidelity Settings)

+ +We apologize for this text-only content, as we are currently swamped with visitors. Thank you for your patience as we work hard to serve your requests. (This file is a little over 3 KB.) +

+SYDNEY, Australia (Reuters) -- In death as in life, iconic TV naturalist Steve Irwin captivated millions worldwide and clogged the Internet as fans from Guam to Glasgow reacted with disbelief to news "The Crocodile Hunter" was dead. +

+Some Web sites groaned to a halt within hours of the first reports Monday that Irwin had been killed by a stingray's barb through his chest in a freak diving accident off Australia's northeast coast. +

+Web measurement company Hitwise said Irwin's death was the biggest news event read by Australians on the Internet since two Australian miners were trapped by a mine collapse in southern Tasmania state in late April. +

+"We noticed that the Web site www.crocodilehunter.com increased in popularity quite substantially. It became the number one entertainment personality Web site in Australia yesterday and in the United States it also became the third most popular," Hitwise Asia-Pacific marketing director James Borg told Reuters. +

+Australian news Web sites struggled to keep up with demand. +

+The Australian Broadcasting Corp.'s site (www.abc.com.au) had to temporarily shut down, posting a notice Monday that it was experiencing higher than normal traffic. +

+It resumed soon after in a low-bandwidth format to cope with hundreds of thousands of hits. +

+Newspaper Web sites also wobbled but kept up with demand. +

+A spokesman for The Sydney Morning Herald's site, www.smh.com.au, said it had experienced a "huge" 40 percent spike in page impressions compared with the previous week's average weekday number of about 500,000. +

+There was also a 70 percent jump in visitors to its pages, the spokesman said. +

+That pattern was mirrored around the world, with Irwin's death leading major news Web sites such as CNN.com and U.S. and British newspaper Web sites, as well as swamping their most viewed and most emailed categories. +

+Web logs and Internet feedback pages were also awash with postings from shocked readers from around the world, many of them from Americans charmed by Irwin's quirky style and his typically Australian catchphrase of "crikey." +

+Irwin first found fame in the United States before his "Crocodile Hunter" documentaries on U.S.-based television company Discovery Communications' Animal Planet attracted a global audience of 200 million -- 10 times Australia's population. +

+"Crikey!, I miss him so much," Tina Treece from Pittsburgh, Pennsylvania, posted on CNN.com's feedback page CNN Exchange. +

+The site had contributions from readers in Guam, Romania, Thailand, France, Scotland, India, New Zealand, Canada, Brunei, Britain, Malaysia, Denmark and the Netherlands. +

+Many faced the problem of explaining to their children how one of their favorite TV characters had died. +

+"Why did it have to be Steve Irwin?" 11-year-old Daniel told Australian Associated Press. +

+Copyright 2006 Reuters. All rights reserved.This material may not be published, broadcast, rewritten, or redistributed. + + diff --git a/targets/znews1-d/system/webpages/www3/index.html b/targets/znews1-d/system/webpages/www3/index.html index d5801caa4..dee934b7c 100644 --- a/targets/znews1-d/system/webpages/www3/index.html +++ b/targets/znews1-d/system/webpages/www3/index.html @@ -1,11 +1,11 @@ - - -Somewhere Over the Rainbow - - -

Z.com News - Hello World! (Medium-fidelity Settings)

-This file contains an 800x600 pixel image. The total size of this file is approximately 53K. -
- - + + +Somewhere Over the Rainbow + + +

Z.com News - Hello World! (Medium-fidelity Settings)

+This file contains an 800x600 pixel image. The total size of this file is approximately 53K. +
+ + \ No newline at end of file diff --git a/targets/znews1-d/system/webpages/www5/cgi-bin/computePi.pl b/targets/znews1-d/system/webpages/www5/cgi-bin/computePi.pl index 81f2d2cd0..f3cdbad2d 100644 --- a/targets/znews1-d/system/webpages/www5/cgi-bin/computePi.pl +++ b/targets/znews1-d/system/webpages/www5/cgi-bin/computePi.pl @@ -1,118 +1,118 @@ -#!/usr/bin/perl -T - -use strict; -use Carp; -use Math::BigFloat; -use Class::Struct qw(struct); -use Data::Dumper; - -# With due homage to Mathsoft's site: -# http://www.mathsoft.com/asolve/constant/pi/pi.html - -# Set the global precision. Faster than passing it everywhichwhere. -my $precision = @ARGV>0?$ARGV[0]:512; - -# Set the iteration count. -my $maxIterations = @ARGV>1?$ARGV[1]:10; - -# Set the verbose debugging flag. -my $debugVerbose = 0; - -# Constants: -my $_1 = Math::BigFloat->new(1); -my $_2 = Math::BigFloat->new(2); -my $_3 = Math::BigFloat->new(3); -my $_4 = Math::BigFloat->new(4); -my $_6 = Math::BigFloat->new(6); -my $_8 = Math::BigFloat->new(8); -my $_239 = Math::BigFloat->new(239); -my $_half = Math::BigFloat->new(0.5); -my $_fifth = Math::BigFloat->new(0.2); -my $_25th = Math::BigFloat->new(0.04); -my $_239th = inv($_239); -my $_57121th = inv($_239*$_239); - - -# Utility methods: -sub div { - my $a = shift; - my $b = shift; - return new Math::BigFloat $a->copy()->fdiv($b,$precision); -} -sub inv { # Inverse (1/x) function. - my $a = shift; - return new Math::BigFloat $_1->copy()->fdiv($a,$precision); -} -sub root2 { - my $self = shift; - return new Math::BigFloat $self->copy()->fsqrt($precision); -} -sub root4 { - my $self = shift; - return root2(root2($self)); -} -sub pow4 { - my $self = shift; - my $square = round($self*$self); - return round($square*$square); -} -sub round { - my $self = shift; - return new Math::BigFloat $self->copy()->fround($precision); -} - -# Method 4: - -# This uses Ramanujan's elliptic integral-based technique to -# compute Pi monstrously quickly. -# -# This algorithm is neat, since it is quartically convergent - -# that means that the error goes as 4^(-iteration_count). -# -# In other words, one more step = four times the # of correct digits. - -sub RamanujanEI { - if (@_) { - my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. - - my $z_4_term = root4($_1 - pow4($z)); - my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); - - my $z_next_plus_1 = $z_next + $_1; - - my $a_next = pow4($z_next_plus_1) * $a - - $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); - $a_next = round($a_next); - return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; - - } else { # Seed the recurrence - my $a = $_6-$_4*root2($_2); - return [ $a, root2($_2)-$_1, $_8, inv($a)]; - } -} - - - -###################################################################### -# -# Main routine: -# -# - -my $iterResult = RamanujanEI(); -for (my $i=1; $i<$maxIterations; $i++) { - $iterResult = RamanujanEI($iterResult); -} -my $piValue = ${$iterResult}[-1]; -my $piStr = "" . $piValue; - -my $CHUNK = 32; -my $i = $CHUNK + 1; -print "Content-type: text/plain\r\n"; -print "Content-length: 570\r\n\r\n"; -print "Pi_512 :=\n"; -print " " . substr($piValue, 0, $i) . "\n"; -for (; $i < length($piValue) ; $i+=$CHUNK) { - print " " . substr($piValue, $i, $CHUNK) . "\n"; -} - +#!/usr/bin/perl -T + +use strict; +use Carp; +use Math::BigFloat; +use Class::Struct qw(struct); +use Data::Dumper; + +# With due homage to Mathsoft's site: +# http://www.mathsoft.com/asolve/constant/pi/pi.html + +# Set the global precision. Faster than passing it everywhichwhere. +my $precision = @ARGV>0?$ARGV[0]:512; + +# Set the iteration count. +my $maxIterations = @ARGV>1?$ARGV[1]:10; + +# Set the verbose debugging flag. +my $debugVerbose = 0; + +# Constants: +my $_1 = Math::BigFloat->new(1); +my $_2 = Math::BigFloat->new(2); +my $_3 = Math::BigFloat->new(3); +my $_4 = Math::BigFloat->new(4); +my $_6 = Math::BigFloat->new(6); +my $_8 = Math::BigFloat->new(8); +my $_239 = Math::BigFloat->new(239); +my $_half = Math::BigFloat->new(0.5); +my $_fifth = Math::BigFloat->new(0.2); +my $_25th = Math::BigFloat->new(0.04); +my $_239th = inv($_239); +my $_57121th = inv($_239*$_239); + + +# Utility methods: +sub div { + my $a = shift; + my $b = shift; + return new Math::BigFloat $a->copy()->fdiv($b,$precision); +} +sub inv { # Inverse (1/x) function. + my $a = shift; + return new Math::BigFloat $_1->copy()->fdiv($a,$precision); +} +sub root2 { + my $self = shift; + return new Math::BigFloat $self->copy()->fsqrt($precision); +} +sub root4 { + my $self = shift; + return root2(root2($self)); +} +sub pow4 { + my $self = shift; + my $square = round($self*$self); + return round($square*$square); +} +sub round { + my $self = shift; + return new Math::BigFloat $self->copy()->fround($precision); +} + +# Method 4: + +# This uses Ramanujan's elliptic integral-based technique to +# compute Pi monstrously quickly. +# +# This algorithm is neat, since it is quartically convergent - +# that means that the error goes as 4^(-iteration_count). +# +# In other words, one more step = four times the # of correct digits. + +sub RamanujanEI { + if (@_) { + my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. + + my $z_4_term = root4($_1 - pow4($z)); + my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); + + my $z_next_plus_1 = $z_next + $_1; + + my $a_next = pow4($z_next_plus_1) * $a - + $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); + $a_next = round($a_next); + return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; + + } else { # Seed the recurrence + my $a = $_6-$_4*root2($_2); + return [ $a, root2($_2)-$_1, $_8, inv($a)]; + } +} + + + +###################################################################### +# +# Main routine: +# +# + +my $iterResult = RamanujanEI(); +for (my $i=1; $i<$maxIterations; $i++) { + $iterResult = RamanujanEI($iterResult); +} +my $piValue = ${$iterResult}[-1]; +my $piStr = "" . $piValue; + +my $CHUNK = 32; +my $i = $CHUNK + 1; +print "Content-type: text/plain\r\n"; +print "Content-length: 570\r\n\r\n"; +print "Pi_512 :=\n"; +print " " . substr($piValue, 0, $i) . "\n"; +for (; $i < length($piValue) ; $i+=$CHUNK) { + print " " . substr($piValue, $i, $CHUNK) . "\n"; +} + diff --git a/targets/znews1-d/system/webpages/www5/cgi-bin/piComputeLib.pl b/targets/znews1-d/system/webpages/www5/cgi-bin/piComputeLib.pl index afa74a73d..53af038bd 100644 --- a/targets/znews1-d/system/webpages/www5/cgi-bin/piComputeLib.pl +++ b/targets/znews1-d/system/webpages/www5/cgi-bin/piComputeLib.pl @@ -1,233 +1,233 @@ -#!/usr/bin/perl -T - -#map$x+=(-1)**$_*4/(2*$_+1),0..1e6;die$x - -use strict; -use Carp; -use Math::BigFloat; -use Class::Struct qw(struct); -use Data::Dumper; - -# With due homage to Mathsoft's site: -# http://www.mathsoft.com/asolve/constant/pi/pi.html - -# Set the global precision. Faster than passing it everywhichwhere. -my $precision = @ARGV>0?$ARGV[0]:10; - -# Set the iteration count. -my $maxIterations = @ARGV>1?$ARGV[1]:10; - -# Set the verbose debugging flag. -my $debugVerbose = 0; - -# Constants: -my $_1 = Math::BigFloat->new(1); -my $_2 = Math::BigFloat->new(2); -my $_3 = Math::BigFloat->new(3); -my $_4 = Math::BigFloat->new(4); -my $_6 = Math::BigFloat->new(6); -my $_8 = Math::BigFloat->new(8); -my $_239 = Math::BigFloat->new(239); -my $_half = Math::BigFloat->new(0.5); -my $_fifth = Math::BigFloat->new(0.2); -my $_25th = Math::BigFloat->new(0.04); -my $_239th = inv($_239); -my $_57121th = inv($_239*$_239); - - -# Utility methods: -sub div { - my $a = shift; - my $b = shift; - return new Math::BigFloat $a->copy()->fdiv($b,$precision); -} -sub inv { # Inverse (1/x) function. - my $a = shift; - return new Math::BigFloat $_1->copy()->fdiv($a,$precision); -} -sub root2 { - my $self = shift; - return new Math::BigFloat $self->copy()->fsqrt($precision); -} -sub root4 { - my $self = shift; - return root2(root2($self)); -} -sub pow4 { - my $self = shift; - my $square = round($self*$self); - return round($square*$square); -} -sub round { - my $self = shift; - return new Math::BigFloat $self->copy()->fround($precision); -} - - -# Method 1: - -# This gives Archimedes' approximation, -# 3+10/71 < Pi < 3+1/7 -# ...on the 4th iteration. - -sub BorchardtPfaff { - if (@_) { - my ($a,$b) = @{shift()}; # Retrieve the last iteration. - my $a_next = div( $_2*$a*$b, $a+$b ); - my $b_next = root2($a_next*$b); - return [ round($a_next), round($b_next) ]; - } else { # Seed the recurrence - return [ $_2*root2($_3), $_3 ]; - } -} - -# Method 2: - -# This uses Borwein's AGM method to compute Pi very quickly. -# The 'AGM' is short for the iterated arithmetic-geometric mean; -# which was looked at by Lagrange and Gauss way back in 1799. -# We basically look at the tuple [a,b] which holds the arithmetic -# and geometric means of the previous iteration: -# a[n+1] = (a[n] + b[n])/2 // Arithmetic mean -# b[n+1] = sqrt(a[n] * b[n]) // Geometric mean -# -# This algorithm is neat, since it is quadratically convergent - -# that means that the error goes as 2^(-iteration_count). -# -# In other words, one more step = twice the # of correct digits. - -sub BorweinAGM { - if (@_) { - my ($a,$b,$pi) = @{shift()}; # Retrieve the last iteration. - - my $sqrt_a = root2($a); - my $inv_sqrt_a = inv($sqrt_a); - my $b_plus_1 = $b+$_1; - - my $a_next = $_half * ($sqrt_a+$inv_sqrt_a); - my $b_next = div( $b*$sqrt_a+$inv_sqrt_a , $b_plus_1 ); - my $pi_next = $pi*div( $a_next+$_1 , $b_next+$_1 ); - return [ round($a_next), round($b_next), round($pi_next) ]; - - } else { # Seed the recurrence - my $a0 = root2($_2); - my $pi0 = $_2+root2($_2); - my $b1 = root2($a0); # = root4($_2) - my $a1 = $_half * ($b1 + inv($b1)); - - return [ round($a1), round($b1), round($pi0 * div($a1 + $_1, $b1 + $_1)) ]; - } -} - -# Method 3: - -# The arctangent approximation, as determined by Machin (1706). -# Pi = 4(4 * arctan(1/5) - arctan(1/239)), -# ...where arctan(x) = sum( (-1)^k/(2*k+1)*x^(2*k+1), x=0..infinity). - -sub ArctanPi { - if (@_) { - my ($k, $atan5, $atan239, $denom5, $denom239, $pi) = @{shift()}; # Retrieve the last iteration. - - $k++; - my $parity=$k & 1; - $denom5 = $denom5 * $_25th; - - my $inv_2_k_plus_1='Math::BigFloat'->new(2*$k+1); - - my $term5 = div($denom5, $inv_2_k_plus_1 ); - $denom239 = $denom239 * $_57121th; - - my $term239 = div($denom239, $inv_2_k_plus_1 ); - $atan5 = $parity ? $atan5 - $term5 : $atan5 + $term5; - $atan239 = $parity ? $atan239 - $term239 : $atan239 + $term239; - my $pi = $_4*($_4*$atan5 - $atan239); - - return [ $k, round($atan5), round($atan239), - round($denom5), round($denom239), round($pi) ]; - } else { # Seed the recurrence - my ($k, $atan5, $atan239) = (0, $_fifth, $_239th); - return [ $k, $atan5, $atan239, $atan5, $atan239, $_4*($_4*$atan5 - $atan239)]; - } -} - -# Method 4: - -# This uses Ramanujan's elliptic integral-based technique to -# compute Pi monstrously quickly. -# -# This algorithm is neat, since it is quartically convergent - -# that means that the error goes as 4^(-iteration_count). -# -# In other words, one more step = four times the # of correct digits. - -sub RamanujanEI { - if (@_) { - my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. - - my $z_4_term = root4($_1 - pow4($z)); - my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); - - my $z_next_plus_1 = $z_next + $_1; - - my $a_next = pow4($z_next_plus_1) * $a - - $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); - $a_next = round($a_next); - return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; - - } else { # Seed the recurrence - my $a = $_6-$_4*root2($_2); - return [ $a, root2($_2)-$_1, $_8, inv($a)]; - } -} - - - -###################################################################### -# -# Main routine: -# -# - -my $methods = ["BorchardtPfaff", "ArctanPi", "BorweinAGM", "RamanujanEI" ]; - -my $longestMethodLen=0; -foreach my $method (@{$methods}) { - $longestMethodLen = length($method) if length($method) > $longestMethodLen; -} - -my $pis = [ BorchardtPfaff(), ArctanPi(), BorweinAGM(), RamanujanEI() ]; - -for (my $i=0; $i<$maxIterations; $i++) { - print "Iteration $i:\n"; - if (!$debugVerbose) { - for (my $j=0; $j<@{$methods}; $j++) { - - # The following piece of line noise is equivalent to the - # STL C++, " - - # piValue = pis[j].last(); - - # ", if the declaration for pis is: - - # std::vector > pis; - # - - my $methodName = ${$methods}[$j]; - my $piValue = ${${$pis}[$j]}[-1]; - print ${$methods}[$j] . ": " . - ' ' x ($longestMethodLen - length($methodName)) . - $piValue . "\n"; - } - print "\n"; - } - print(Dumper($pis)) if $debugVerbose; - - last if $i+1 == $maxIterations; - - $pis = [ BorchardtPfaff(${$pis}[0]), - ArctanPi(${$pis}[1]), - BorweinAGM(${$pis}[2]), - RamanujanEI(${$pis}[3]) ]; -} - +#!/usr/bin/perl -T + +#map$x+=(-1)**$_*4/(2*$_+1),0..1e6;die$x + +use strict; +use Carp; +use Math::BigFloat; +use Class::Struct qw(struct); +use Data::Dumper; + +# With due homage to Mathsoft's site: +# http://www.mathsoft.com/asolve/constant/pi/pi.html + +# Set the global precision. Faster than passing it everywhichwhere. +my $precision = @ARGV>0?$ARGV[0]:10; + +# Set the iteration count. +my $maxIterations = @ARGV>1?$ARGV[1]:10; + +# Set the verbose debugging flag. +my $debugVerbose = 0; + +# Constants: +my $_1 = Math::BigFloat->new(1); +my $_2 = Math::BigFloat->new(2); +my $_3 = Math::BigFloat->new(3); +my $_4 = Math::BigFloat->new(4); +my $_6 = Math::BigFloat->new(6); +my $_8 = Math::BigFloat->new(8); +my $_239 = Math::BigFloat->new(239); +my $_half = Math::BigFloat->new(0.5); +my $_fifth = Math::BigFloat->new(0.2); +my $_25th = Math::BigFloat->new(0.04); +my $_239th = inv($_239); +my $_57121th = inv($_239*$_239); + + +# Utility methods: +sub div { + my $a = shift; + my $b = shift; + return new Math::BigFloat $a->copy()->fdiv($b,$precision); +} +sub inv { # Inverse (1/x) function. + my $a = shift; + return new Math::BigFloat $_1->copy()->fdiv($a,$precision); +} +sub root2 { + my $self = shift; + return new Math::BigFloat $self->copy()->fsqrt($precision); +} +sub root4 { + my $self = shift; + return root2(root2($self)); +} +sub pow4 { + my $self = shift; + my $square = round($self*$self); + return round($square*$square); +} +sub round { + my $self = shift; + return new Math::BigFloat $self->copy()->fround($precision); +} + + +# Method 1: + +# This gives Archimedes' approximation, +# 3+10/71 < Pi < 3+1/7 +# ...on the 4th iteration. + +sub BorchardtPfaff { + if (@_) { + my ($a,$b) = @{shift()}; # Retrieve the last iteration. + my $a_next = div( $_2*$a*$b, $a+$b ); + my $b_next = root2($a_next*$b); + return [ round($a_next), round($b_next) ]; + } else { # Seed the recurrence + return [ $_2*root2($_3), $_3 ]; + } +} + +# Method 2: + +# This uses Borwein's AGM method to compute Pi very quickly. +# The 'AGM' is short for the iterated arithmetic-geometric mean; +# which was looked at by Lagrange and Gauss way back in 1799. +# We basically look at the tuple [a,b] which holds the arithmetic +# and geometric means of the previous iteration: +# a[n+1] = (a[n] + b[n])/2 // Arithmetic mean +# b[n+1] = sqrt(a[n] * b[n]) // Geometric mean +# +# This algorithm is neat, since it is quadratically convergent - +# that means that the error goes as 2^(-iteration_count). +# +# In other words, one more step = twice the # of correct digits. + +sub BorweinAGM { + if (@_) { + my ($a,$b,$pi) = @{shift()}; # Retrieve the last iteration. + + my $sqrt_a = root2($a); + my $inv_sqrt_a = inv($sqrt_a); + my $b_plus_1 = $b+$_1; + + my $a_next = $_half * ($sqrt_a+$inv_sqrt_a); + my $b_next = div( $b*$sqrt_a+$inv_sqrt_a , $b_plus_1 ); + my $pi_next = $pi*div( $a_next+$_1 , $b_next+$_1 ); + return [ round($a_next), round($b_next), round($pi_next) ]; + + } else { # Seed the recurrence + my $a0 = root2($_2); + my $pi0 = $_2+root2($_2); + my $b1 = root2($a0); # = root4($_2) + my $a1 = $_half * ($b1 + inv($b1)); + + return [ round($a1), round($b1), round($pi0 * div($a1 + $_1, $b1 + $_1)) ]; + } +} + +# Method 3: + +# The arctangent approximation, as determined by Machin (1706). +# Pi = 4(4 * arctan(1/5) - arctan(1/239)), +# ...where arctan(x) = sum( (-1)^k/(2*k+1)*x^(2*k+1), x=0..infinity). + +sub ArctanPi { + if (@_) { + my ($k, $atan5, $atan239, $denom5, $denom239, $pi) = @{shift()}; # Retrieve the last iteration. + + $k++; + my $parity=$k & 1; + $denom5 = $denom5 * $_25th; + + my $inv_2_k_plus_1='Math::BigFloat'->new(2*$k+1); + + my $term5 = div($denom5, $inv_2_k_plus_1 ); + $denom239 = $denom239 * $_57121th; + + my $term239 = div($denom239, $inv_2_k_plus_1 ); + $atan5 = $parity ? $atan5 - $term5 : $atan5 + $term5; + $atan239 = $parity ? $atan239 - $term239 : $atan239 + $term239; + my $pi = $_4*($_4*$atan5 - $atan239); + + return [ $k, round($atan5), round($atan239), + round($denom5), round($denom239), round($pi) ]; + } else { # Seed the recurrence + my ($k, $atan5, $atan239) = (0, $_fifth, $_239th); + return [ $k, $atan5, $atan239, $atan5, $atan239, $_4*($_4*$atan5 - $atan239)]; + } +} + +# Method 4: + +# This uses Ramanujan's elliptic integral-based technique to +# compute Pi monstrously quickly. +# +# This algorithm is neat, since it is quartically convergent - +# that means that the error goes as 4^(-iteration_count). +# +# In other words, one more step = four times the # of correct digits. + +sub RamanujanEI { + if (@_) { + my ($a, $z, $factor, $pi) = @{shift()}; # Retrieve the last iteration. + + my $z_4_term = root4($_1 - pow4($z)); + my $z_next = div( $_1-$z_4_term, $_1+$z_4_term ); + + my $z_next_plus_1 = $z_next + $_1; + + my $a_next = pow4($z_next_plus_1) * $a - + $factor * $z_next * round($z_next_plus_1 + $z_next * $z_next); + $a_next = round($a_next); + return [ $a_next, $z_next, round($factor * $_4), inv($a_next) ]; + + } else { # Seed the recurrence + my $a = $_6-$_4*root2($_2); + return [ $a, root2($_2)-$_1, $_8, inv($a)]; + } +} + + + +###################################################################### +# +# Main routine: +# +# + +my $methods = ["BorchardtPfaff", "ArctanPi", "BorweinAGM", "RamanujanEI" ]; + +my $longestMethodLen=0; +foreach my $method (@{$methods}) { + $longestMethodLen = length($method) if length($method) > $longestMethodLen; +} + +my $pis = [ BorchardtPfaff(), ArctanPi(), BorweinAGM(), RamanujanEI() ]; + +for (my $i=0; $i<$maxIterations; $i++) { + print "Iteration $i:\n"; + if (!$debugVerbose) { + for (my $j=0; $j<@{$methods}; $j++) { + + # The following piece of line noise is equivalent to the + # STL C++, " + + # piValue = pis[j].last(); + + # ", if the declaration for pis is: + + # std::vector > pis; + # + + my $methodName = ${$methods}[$j]; + my $piValue = ${${$pis}[$j]}[-1]; + print ${$methods}[$j] . ": " . + ' ' x ($longestMethodLen - length($methodName)) . + $piValue . "\n"; + } + print "\n"; + } + print(Dumper($pis)) if $debugVerbose; + + last if $i+1 == $maxIterations; + + $pis = [ BorchardtPfaff(${$pis}[0]), + ArctanPi(${$pis}[1]), + BorweinAGM(${$pis}[2]), + RamanujanEI(${$pis}[3]) ]; +} + diff --git a/targets/znews1-d/system/webpages/www5/index.php b/targets/znews1-d/system/webpages/www5/index.php index 9ece5f82a..f7f80e4da 100644 --- a/targets/znews1-d/system/webpages/www5/index.php +++ b/targets/znews1-d/system/webpages/www5/index.php @@ -1,83 +1,83 @@ - 1 && time()%$content == 0) { - echo << - -Please come back... - - -I (the server) am swamped right now!!
-Please kindly come back in a couple of minutes.
-Sorry for the inconvenience, and thanks for understanding! - - -REJECT; - exit(); -} - -/* -$mysql_url = 'localhost'; -$mysql_user = 'wikiuser'; -$mysql_password = 'ns.wwwp'; -$mysql_db = 'wiki_wwwp'; - -$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) - or die('Could not connect: ' . mysql_error()); - -$mydb = mysql_select_db($mysql_db, $link); -if(!$mydb) { - die('Could not select Test database: ' . mysql_error()); -} - -// Performing SQL query -$query = "SELECT COUNT(*) FROM cur"; -$result = mysql_query($query, $link) - or die('Query COUNT failed: ' . mysql_error()); -$row = mysql_fetch_row($result); -if ($row != false) { - $numItems = $row[0]; -} - -$idx = rand(1, $numItems); -$query = "SELECT cur_text FROM cur LIMIT $idx,1"; -$result = mysql_query($query, $link) - or die('Query item $idx failed: ' . mysql_error()); -$row = mysql_fetch_row($result); -if($row != false) { - $text = $row[0]; -} -*/ -$text = ""; - -echo << - -Somewhere Over the Rainbow - - - -

Z.com News - Hello World! (High-fidelity Settings)

-This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. - - - - -END - -?> + 1 && time()%$content == 0) { + echo << + +Please come back... + + +I (the server) am swamped right now!!
+Please kindly come back in a couple of minutes.
+Sorry for the inconvenience, and thanks for understanding! + + +REJECT; + exit(); +} + +/* +$mysql_url = 'localhost'; +$mysql_user = 'wikiuser'; +$mysql_password = 'ns.wwwp'; +$mysql_db = 'wiki_wwwp'; + +$link = mysql_connect($mysql_url, $mysql_user, $mysql_password) + or die('Could not connect: ' . mysql_error()); + +$mydb = mysql_select_db($mysql_db, $link); +if(!$mydb) { + die('Could not select Test database: ' . mysql_error()); +} + +// Performing SQL query +$query = "SELECT COUNT(*) FROM cur"; +$result = mysql_query($query, $link) + or die('Query COUNT failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if ($row != false) { + $numItems = $row[0]; +} + +$idx = rand(1, $numItems); +$query = "SELECT cur_text FROM cur LIMIT $idx,1"; +$result = mysql_query($query, $link) + or die('Query item $idx failed: ' . mysql_error()); +$row = mysql_fetch_row($result); +if($row != false) { + $text = $row[0]; +} +*/ +$text = ""; + +echo << + +Somewhere Over the Rainbow + + + +

Z.com News - Hello World! (High-fidelity Settings)

+This file contains a 1024x768 pixel image. The total size of this file is approximately 205K. + + + + +END + +?> diff --git a/testing/pom.xml b/testing/pom.xml index 805645059..5246b4704 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -53,7 +53,7 @@ rainbow rainbow-core - 2.1.3-SNAPSHOT + 3.0 provided